Пример #1
0
void SnmpRouted::run()
{
   timeval tm;
   fd_set rdset;
   int numfd, maxfd;
   int reqfd = listener.getfd();
   tm.tv_sec = 1;
   tm.tv_usec = 0;

   while(1)
   {
      maxfd = setup(rdset);
      numfd = select(maxfd, &rdset, 0, 0, &tm);
      for(int fd = maxfd; ((numfd > 0) && (fd >= 0)); fd--)
      {
         if(FD_ISSET(fd, &rdset))
         {
            if(fd == reqfd)
               routeRequest();
            else
               routeReply(fd);
         }
      }

      purgeRequestTable();
   }
}
Пример #2
0
void RoutingManagerPrivate::saveRoute(const QString &filename)
{
    GeoWriter writer;
    writer.setDocumentType( kml::kmlTag_nameSpaceOgc22 );

    QMutexLocker locker( &m_fileMutex );
    QFile file( filename );
    if ( !file.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
    {
        mDebug() << "Cannot write to " << file.fileName();
        return;
    }

    GeoDataDocument container;
    container.setName(QStringLiteral("Route"));
    GeoDataFolder* request = routeRequest();
    if ( request ) {
        container.append( request );
    }

    GeoDataDocument *route = m_alternativeRoutesModel.currentRoute();
    if ( route ) {
        container.append( new GeoDataDocument( *route ) );
    }

    if ( !writer.write( &file, &container ) ) {
        mDebug() << "Can not write route state to " << file.fileName();
    }
    file.close();
}
Пример #3
0
 void HttpInterface::incomingData(Stream *stream)
 {
     if (stream == asebaStream) {
         // incoming Aseba message
         if (verbose)
             cerr << "incoming for asebaStream " << stream << endl;
         
         Message *message(Message::receive(stream));
         
         // pass message to description manager, which builds
         // the node descriptions in background
         NodesManager::processMessage(message);
         
         // if variables, check for pending requests
         const Variables *variables(dynamic_cast<Variables *>(message));
         if (variables)
             incomingVariables(variables);
         
         // if event, retransmit it on an HTTP SSE channel if one exists
         const UserMessage *userMsg(dynamic_cast<UserMessage *>(message));
         if (userMsg)
             incomingUserMsg(userMsg);
         
         delete message;
     }
     else
     {
         // incoming HTTP request
         if (verbose)
             cerr << "incoming for HTTP stream " << stream << endl;
         HttpRequest* req = new HttpRequest; // [promise] we will eventually delete req in sendAvailableResponses, unscheduleResponse, or stream shutdown
         if ( ! req->initialize(stream))
         {   // protocol failure, shut down connection
             stream->write("HTTP/1.1 400 Bad request\r\n");
             stream->fail(DashelException::Unknown, 0, "400 Bad request");
             unscheduleAllResponses(stream);
             delete req; // not yet in queue, so delete it here [promise]
             return;
         }
         
         if (verbose)
         {
             cerr << stream << " Request " << req->method.c_str() << " " << req->uri.c_str() << " [ ";
             for (unsigned int i = 0; i < req->tokens.size(); ++i)
                 cerr << req->tokens[i] << " ";
             cerr << "] " << req->protocol_version << " new req " << req << endl;
         }
         // continue with incomingData
         scheduleResponse(stream, req);
         req->incomingData(); // read request all at once
         if (req->ready)
             routeRequest(req);
         // run response queues immediately to save time
         sendAvailableResponses();
     }
 }
Пример #4
0
void server(Request * request, Response * response) {
	// open sqlite3 database "URL_Records"
	rc = sqlite3_open("URL_Records.db", &db);
	// if db exist it will open otherwise create a db
	if (rc) {
		fprintf(stderr, "sqlite db connectivity error.");
		exit(0);
	}
	//query to create "Records" table if not exists.
	sql = "CREATE TABLE if not exists Records( "
			"ID INTEGER PRIMARY KEY  AUTOINCREMENT,"
			"Hash CHAR(5)  NOT NULL,URL TEXT NOT NULL);";

	rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
	//Execute the sql statement.
	if (rc != SQLITE_OK) {
		fprintf(stderr, "SQL table creating error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}

	printf("%s %s\n", request->method, request->reqStr);

	if (routeRequest(request, response, "/shorten", form)
			|| routeRequest(request, response, "/", form)) {
		//Request to shorten the URL
	} else {
		response->apiFlags |= API_FLAGS_DONT_SET_HEADER_BEFORE_SENDING;
		char * queryPath = getQueryPath(request);
		char longUrl[4096];
		getLongUrl(queryPath, longUrl);
		STATIC_SEND(response->fd, "HTTP/1.1 301 Moved Permanently\r\n");
		resPrintf(response, "Location: %s\r\n", longUrl);
		STATIC_SEND(response->fd, "\r\n");
		free(queryPath);
	}
	sqlite3_close(db);

}
Пример #5
0
	void Server::handleRoutedRequest(String path, Request& req, Response& resp,
			Delegate<void()> cb) {
		auto it = routeCache.find(path);
		timespec tmp1 = curTime;
		tmp1.tv_sec -= routeCacheDuration;
		if (likely(it != routeCache.end() && tsCompare((*it).second->lastUpdate, tmp1) > 0)) {
			(*it).second->handler(req, resp, cb);
			return;
		}
		//printf("re-routing %s\n", req.path.toSTDString().c_str());
		auto* st = resp.sp->New<requestHandlerState>(
				requestHandlerState { this, &req, &resp, cb, path });
		auto h = routeRequest(path);
		if (h)
			(*st)(h(), nullptr);
		else h.wait(st);
	}
Пример #6
0
RouteRequestPtr BaseUrlRouter::findAndOptionallyCreateRoute(const std::string& route, bool codesAllowed, bool insertionAllowed)
{
    if (route.length() > maxRouteLength)
    {
        throw RouteTooLongException();
    }

    RouteSegmentPtr bestMatchingSegmentSoFar; // REM : points to nothing for now
    RouteRequestPtr routeRequest(new RouteRequest(route)); // result

    std::cout << "* Processing route : \"" << route << "\"..." << std::endl;

    // We'll use the getline technique for splitting
    // http://en.cppreference.com/w/cpp/string/basic_string/getline

    // prepare
    std::istringstream routeDecoder(route);
    char segmentBuffer[maxRouteSegmentDecodingBufferSize+1];

    // check if begins with /
    routeDecoder.getline(segmentBuffer, maxRouteSegmentDecodingBufferSize, '/');
    if (segmentBuffer[0] != '\0' or routeDecoder.eof())
    {
        throw MalformedRouteException("route must start with a / !");
    }
    bestMatchingSegmentSoFar = rootSegment_;

    // now process remaining segments
    do
    {
        routeDecoder.getline(segmentBuffer, maxRouteSegmentDecodingBufferSize+1, '/');

        // debug
        std::cout << "  * current segment : \"" << segmentBuffer << "\"" << std::endl;
        std::cout << "  * current state : good ? " << routeDecoder.good() << ", eof ? " << routeDecoder.eof() << ", fail ? " << routeDecoder.fail() << std::endl;

        if (segmentBuffer[0] == '\0')
        {
            if(routeDecoder.eof())
            {
                // nothing more to parse
                break;
            }
            else
            {
                // empty string but not eof
                // means several '/' concatened,
                // -> this is not allowed
                throw MalformedRouteException("route may not contain consecutive '/' !");
            }
        }

        if(routeDecoder.fail())
        {
            // there was a problem
            // according to the doc, can happen for 2 reasons :
            // - no character was extracted
            //   -> cannot happen since we already tested eof
            // - the buffer was filled
            throw MalformedRouteException("segment too long !");
        }

        // first detect special segments
        if(codesAllowed)
        {
            if(0 == strncmp(NumericalIdCode, segmentBuffer, maxRouteSegmentDecodingBufferSize))
            {
                // this segment is the special code for a numeric id
                if(!bestMatchingSegmentSoFar->numericalLeaf_)
                {
                    if(insertionAllowed)
                    {
                        // an id refer to a rsrc
                        // so we must ensure that previous segment is a non-empty fixed segment
                        if(bestMatchingSegmentSoFar->type_ != RouteSegment::FIXED)
                        {
                            throw MalformedRouteException("an id must follow a fixed segment");
                        }
                        else
                        {
                            bestMatchingSegmentSoFar->setNumericalLeaf(RouteSegmentPtr(new RouteSegment(RouteSegment::NUMERICAL_ID)));
                            bestMatchingSegmentSoFar->numericalLeaf_->canonicalRoute_ = bestMatchingSegmentSoFar->canonicalRoute_ + "/" + NumericalIdCode;
                        }
                    }
                    else
                    {
                        // no match
                        bestMatchingSegmentSoFar.reset();
                        break;
                    }
                }
                else
                {
                    // ...
                }
                bestMatchingSegmentSoFar = bestMatchingSegmentSoFar->numericalLeaf_;
                continue;
            }
            else if(0 == strncmp(AlphanumericalIdCode, segmentBuffer, maxRouteSegmentDecodingBufferSize))
            {
                // this segment is the special code for an alphanumeric id
                if(!bestMatchingSegmentSoFar->alphanumericalLeaf_)
                {
                    if(insertionAllowed)
                    {
                        // an id refer to a rsrc
                        // so we must ensure that previous segment is a non-empty fixed segment
                        if(bestMatchingSegmentSoFar->type_ != RouteSegment::FIXED)
                        {
                            throw MalformedRouteException("an id must follow a fixed segment");
                        }
                        else
                        {
                            bestMatchingSegmentSoFar->setAlphanumericalLeaf(RouteSegmentPtr(new RouteSegment(RouteSegment::ALPHANUMERICAL_ID)));
                            bestMatchingSegmentSoFar->alphanumericalLeaf_->canonicalRoute_ = bestMatchingSegmentSoFar->canonicalRoute_ + "/" + AlphanumericalIdCode;
                        }
                    }
                    else
                    {
                        // no match
                        bestMatchingSegmentSoFar.reset();
                        break;
                    }
                }
                else
                {
                    // ...
                }
                bestMatchingSegmentSoFar = bestMatchingSegmentSoFar->alphanumericalLeaf_;
                continue;
            }
        }

        if(bestMatchingSegmentSoFar->numericalLeaf_)
        {
            // parent segment allow numeric sub-segment
            // is current segment an integer ?
            char *decodingEnd = NULL;
            unsigned long ulRepresentation = strtoul( segmentBuffer, &decodingEnd, 10 );
            // Warning : strtoul API is subtile,
            // cf. http://en.cppreference.com/w/cpp/string/byte/strtoul
            switch(ulRepresentation)
            {
            case 0:
                // error or real O ? (The API is ambiguous for this case)
                if(0 == strncmp(zeroString, segmentBuffer, maxRouteSegmentDecodingBufferSize))
                {
                    // OK, really string "0"
                    // store route info
                    routeRequest->addNumericalIdSegment(ulRepresentation, bestMatchingSegmentSoFar->fixedSegmentString_);
                    bestMatchingSegmentSoFar = bestMatchingSegmentSoFar->numericalLeaf_;
                    continue;
                }
                else
                {
                    // segment is not an integer
                    // fallback to fixed string (below)
                }
                break;
            case ULONG_MAX:
                throw MalformedRouteException("numeric segment is out of range !");
                break;
            default:
                // did the decoding used the whole segment
                // or did it used only a part ?
                // ex. "123foo" decode as 123 but this is not correct
                if (decodingEnd && *decodingEnd == '\0')
                {
                    // current segment is a valid integer, OK
                    routeRequest->addNumericalIdSegment(ulRepresentation, bestMatchingSegmentSoFar->fixedSegmentString_);
                    bestMatchingSegmentSoFar = bestMatchingSegmentSoFar->numericalLeaf_;
                    continue;
                }
                else
                {
                    // segment begins with a number but is not a number
                    // Should we report a malformed string instead ? -> let's be open for now.
                    // Meanwhile, fallback to fixed string (below)
                }
                break;
            }
        }

        if(bestMatchingSegmentSoFar->alphanumericalLeaf_)
        {
            // yes. Anything match.
            routeRequest->addAlphanumericalIdSegment(segmentBuffer, bestMatchingSegmentSoFar->fixedSegmentString_);
            bestMatchingSegmentSoFar = bestMatchingSegmentSoFar->alphanumericalLeaf_;
            continue;
        }

        // is current segment already registered ?
        RouteSegmentPtr candidateMatchingSegment = bestMatchingSegmentSoFar->getStringLeafFor(segmentBuffer);
        if(!candidateMatchingSegment)
        {
            // no route matching this
            if(insertionAllowed)
            {
                candidateMatchingSegment.reset(new RouteSegment(segmentBuffer));
                bestMatchingSegmentSoFar->addStringLeaf(candidateMatchingSegment);
                candidateMatchingSegment->canonicalRoute_ = bestMatchingSegmentSoFar->canonicalRoute_ + "/" + segmentBuffer;
                bestMatchingSegmentSoFar = candidateMatchingSegment;
                routeRequest->addFixedSegment(bestMatchingSegmentSoFar->fixedSegmentString_);
                continue;
            }
            else
            {
                // no match
                bestMatchingSegmentSoFar.reset();
                break;
            }
        }
        else
        {
            // fine
            bestMatchingSegmentSoFar = candidateMatchingSegment;
            routeRequest->addFixedSegment(bestMatchingSegmentSoFar->fixedSegmentString_);
            continue;
        }
    } while(bestMatchingSegmentSoFar and not routeDecoder.eof());

    routeRequest->matchingSegment_ = bestMatchingSegmentSoFar;
    return routeRequest;
}