示例#1
0
文件: listcommand.cpp 项目: KDE/simon
bool ListCommand::greedyTrigger(const QString& inputText)
{
  kDebug() << "Triggering greedy " << inputText;

  QHash<CommandListElements::Element, VoiceInterfaceCommand*> adaption = getAdaption();

  QList<CommandListElements::Element> adaptionKeys = adaption.keys();
  foreach (const CommandListElements::Element& element, adaptionKeys) {
    QList<VoiceInterfaceCommand*> interfaceCommands = adaption.values(element);
    foreach (VoiceInterfaceCommand* command, interfaceCommands) {
      if (command->matches(0, inputText)) {
        switch (element) {
          case CommandListElements::Back: return processRequest(0);
          case CommandListElements::One: return processRequest(1);
          case CommandListElements::Two: return processRequest(2);
          case CommandListElements::Three: return processRequest(3);
          case CommandListElements::Four: return processRequest(4);
          case CommandListElements::Five: return processRequest(5);
          case CommandListElements::Six: return processRequest(6);
          case CommandListElements::Seven: return processRequest(7);
          case CommandListElements::Eight: return processRequest(8);
          case CommandListElements::Next: return processRequest(9);
          case CommandListElements::Cancel:
            clw->close();
            return true;
        }
      }

    }

  }
示例#2
0
bool RequestItemMgr_c::handleRequest(int nFd, TempMemBuffer_c& dataReceived)
{
    //MSG("[%d] data received from client, to analyze...\n", dataReceived.getLength());

    bool bRet = true;

    bool bNewRequester = false;

    RequestItem_c* pReqItem = htRequestItems_m.lookup(nFd);
    if (NULL == pReqItem)
    {
        pReqItem = allocateReqItem();
        if (NULL == pReqItem)
        {
            return false;
        }

        pReqItem->setSocketFd(nFd);
        bNewRequester = true;

        // insert into hash table
        htRequestItems_m.insert(pReqItem->getFdAddress(), pReqItem);
    }


    if (!bNewRequester)
    {
        pReqItem->appendBuffer(dataReceived.getBuffer(), dataReceived.getLength());
        if (TlvParser_c::isMessageCompleted(pReqItem->getRequest(), pReqItem->getLength()))
        {
            bRet= processRequest(pReqItem, pReqItem->getRequest(), pReqItem->getLength());

            pReqItem->releaseBuffer();
        }
    }
    else
    {
        if (TlvParser_c::isMessageCompleted(dataReceived.getBuffer(), dataReceived.getLength()))
        {
            bRet = processRequest(pReqItem, dataReceived.getBuffer(), dataReceived.getLength());

            pReqItem->releaseBuffer();
        }
        else
        {
            pReqItem->appendBuffer(dataReceived.getBuffer(), dataReceived.getLength());
        }
    }

    return bRet;
}
示例#3
0
void * threadPool(void * socket)
{
	int masterSocket = (intptr_t) socket;
	
	
	while( 1 )
	{
	
		
		sem_wait(&sema);
		
		struct sockaddr_in clientIPAddressThread;
		int alenThread = 0;
	
		int slaveSocket = accept( masterSocket, (struct sockaddr *)&clientIPAddressThread, (socklen_t*)&alenThread);
		
		
		if ( slaveSocket < 0 ) 
		{
			perror( "accept" );
			exit( -1 );
		}
		
	
		// Process request.
		processRequest( slaveSocket );	
		
	
		// Close socket
		close( slaveSocket );

		sem_post(&sema);
		
	}
}
示例#4
0
bool RosterItemExchange::stanzaReadWrite(int AHandleId, const Jid &AStreamJid, Stanza &AStanza, bool &AAccept)
{
	if (FSHIExchangeRequest==AHandleId && !AStanza.isError())
	{
		QDomElement xElem = AStanza.firstElement("x",NS_ROSTERX);
		if (!xElem.isNull() && !xElem.firstChildElement("item").isNull())
		{
			AAccept = true;

			LOG_STRM_INFO(AStreamJid,QString("Roster exchange request received, from=%1, kind=%2, id=%3").arg(AStanza.from(),AStanza.kind(),AStanza.id()));

			IRosterExchangeRequest request;
			request.streamJid = AStreamJid;
			request.contactJid = AStanza.from();
			request.id = AStanza.kind()==STANZA_KIND_IQ ? AStanza.id() : QString::null;
			request.message = AStanza.kind()==STANZA_KIND_MESSAGE ? Message(AStanza).body() : QString::null;

			QList<Jid> existItems;
			QDomElement itemElem = xElem.firstChildElement("item");

			bool isItemsValid = true;
			while (isItemsValid && !itemElem.isNull())
			{
				IRosterExchangeItem item;
				item.itemJid = Jid(itemElem.attribute("jid")).bare();
				item.name = itemElem.attribute("name");
				item.action = itemElem.attribute("action",ROSTEREXCHANGE_ACTION_ADD);

				QDomElement groupElem = itemElem.firstChildElement("group");
				while(!groupElem.isNull())
				{
					item.groups += groupElem.text();
					groupElem = groupElem.nextSiblingElement("group");
				}

				if (item.itemJid.isValid() && !existItems.contains(item.itemJid) && 
					(item.action==ROSTEREXCHANGE_ACTION_ADD || item.action==ROSTEREXCHANGE_ACTION_DELETE || item.action==ROSTEREXCHANGE_ACTION_MODIFY))
				{
					request.items.append(item);
					existItems.append(item.itemJid);
				}
				else
				{
					isItemsValid = false;
					LOG_STRM_WARNING(AStreamJid,QString("Failed to append roster exchange item, jid=%1, action=%2: Invalid item").arg(item.itemJid.bare(),item.action));
				}

				itemElem = itemElem.nextSiblingElement("item");
			}

			if (isItemsValid && !request.items.isEmpty())
				processRequest(request);
			else
				replyRequestError(request,XmppStanzaError::EC_BAD_REQUEST);

			return true;
		}
	}
	return false;
}
示例#5
0
//SLOT : quand un message arrive, le récupère et le traite
void Server::receiveMessage()
{

    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0)
        return;

    QDataStream in(socket);

    while(1) {

        if (tailleMessage == 0) {
            if (socket->bytesAvailable() < (int)sizeof(tailleMessage))
                return;

            in >> tailleMessage;
        }

        if (socket->bytesAvailable() < tailleMessage)
            return;

        //récupère le message
        QString messageRecu;
        in >> messageRecu;


        qDebug() <<"Received message: " << messageRecu;
        processRequest(messageRecu,socket);

        // reset for the next message
        tailleMessage = 0;
    }
}
示例#6
0
void HistoryManager::loop()
{
    while(true)
    {
        boost::any polled = mpQueue->poll();

        if(!polled.empty())
        {
            if(polled.type() == typeid(spHistoryPack))
            {
                spHistoryPack sphp = boost::any_cast<spHistoryPack>(polled);
                processPack(sphp);
            }
            else if(polled.type() == typeid(spHistoryRequest))
            {
                spHistoryRequest request = boost::any_cast<spHistoryRequest>(polled);
                processRequest(request);
            }
            else if(polled.type() == typeid(LoginPackage))
            {
                LoginPackage loginPackage = boost::any_cast<LoginPackage>(polled);
                processLogin(loginPackage);
            }
            else
            {
            }

        }
    }
}
示例#7
0
void loop() {
  // NETWORKING
  // TODO FIGURE OUT WHETHRE THIS IS BLOCKING
  WiFiClient client = server.available();
  if (!client) return; // TODO CONTINUE LOOPING
  
  int timeout = COMM_TIMEOUT; // TODO LESS BUSY WAIT?
  logMsg("New client");
  while(!client.available() && --timeout>0) {
    delay(1);
  }
  if (timeout <= 0) {
    logMsg("TIMEOUT");
    client.flush();
    return;
  }
  
  // GET MSG
  // TODO FIGURE OUT WHY DOESN'T WORK DIRECTLY
  String str = client.readStringUntil(0);  
  client.flush();
  logMsg(String("Got message [") + str + "]");
  
  // SEND REPLY
  client.print(processRequest(str).toString());
  delay(1);
  logMsg("Client disonnected");
}
示例#8
0
void ICServer::processPendingDatagrams()
{
    QByteArray datagram;
    QUdpSocket *socket = isRunning ? udpSocket : testUdpSocket;

    do {
        QHostAddress *address = new QHostAddress;
        datagram.resize(socket->pendingDatagramSize());
        socket->readDatagram(datagram.data(), datagram.size(), address);

        ICMessageHandler *messageHandler = new ICMessageHandler(this);
        connect(messageHandler, SIGNAL(connectionOffer(QString)), this, SLOT(processSidCollision(QString)));
        connect(messageHandler, SIGNAL(serverDiscovery(QHostAddress,QString)), this, SLOT(processDiscovery(QHostAddress,QString)));
        connect(messageHandler, SIGNAL(questionRequest(QHostAddress)), this, SLOT(processRequest(QHostAddress)));
        connect(messageHandler, SIGNAL(answerReady(ICAnswer,QString)), this, SLOT(processAnswer(ICAnswer,QString)));

        ICMessageProcessor *processor = new ICMessageProcessor(messageHandler, *address, datagram);

        QThreadPool::globalInstance()->start(processor);

        qDebug()<< "[1] Received from " << *address << datagram;

        delete address;
    } while (socket->hasPendingDatagrams());
}
示例#9
0
KIO::AuthInfo KPasswdServer::queryAuthInfo(KIO::AuthInfo info, QString errorMsg, long windowId, long seqNr, unsigned long usertime)
{
    kdDebug(130) << "KPasswdServer::queryAuthInfo: User= "******", Message= " << info.prompt << ", WindowId = " << windowId << endl;
    if(!info.password.isEmpty()) // should we really allow the caller to pre-fill the password?
        kdDebug(130) << "password was set by caller" << endl;
    if(usertime != 0)
        kapp->updateUserTimestamp(usertime);

    QString key = createCacheKey(info);
    Request *request = new Request;
    request->client = callingDcopClient();
    request->transaction = request->client->beginTransaction();
    request->key = key;
    request->info = info;
    request->windowId = windowId;
    request->seqNr = seqNr;
    if(errorMsg == "<NoAuthPrompt>")
    {
        request->errorMsg = QString::null;
        request->prompt = false;
    }
    else
    {
        request->errorMsg = errorMsg;
        request->prompt = true;
    }
    m_authPending.append(request);

    if(m_authPending.count() == 1)
        QTimer::singleShot(0, this, SLOT(processRequest()));

    return info;
}
示例#10
0
QueryData genCurl(QueryContext& context) {
  QueryData results;

  auto requests = context.constraints["url"].getAll(EQUALS);
  auto user_agents = context.constraints["user_agent"].getAll(EQUALS);

  if (user_agents.size() > 1) {
    LOG(WARNING) << "Can only accept a single user_agent";
    return results;
  }

  // Using the like clause for urls wouldn't make sense
  if (context.constraints["url"].getAll(LIKE).size()) {
    LOG(WARNING) << "Using LIKE clause for url is not supported";
  }

  for (const auto& request : requests) {
    Row r;
    r["url"] = request;
    r["method"] = "GET";
    r["user_agent"] =
        user_agents.empty() ? kOsqueryUserAgent : *(user_agents.begin());

    auto status = processRequest(r);
    if (!status.ok()) {
      LOG(WARNING) << status.getMessage();
    }

    results.push_back(r);
  }

  return results;
}
示例#11
0
int main(int argc, char **argv){
    
    char *conf, buf[MAXLINE];

    if (argc != 2) {
        fprintf(stderr, "Please Specify a Config File.");
        exit(0);
    }

    conf = argv[1];
    
    getConfig(conf);

    servers[0].fd = open_clientfd(servers[0].host, servers[0].port);
    servers[1].fd = open_clientfd(servers[1].host, servers[1].port);
    servers[2].fd = open_clientfd(servers[2].host, servers[2].port);
    servers[3].fd = open_clientfd(servers[3].host, servers[3].port);

    printf("Please Enter A Command: \n");

    while (fgets(buf, MAXLINE, stdin) != NULL) {
        // printf("The line was: %s\n", buf);
        processRequest(buf);
        printf("Please Enter a Command: \n");
    }

    close(servers[0].fd);
    close(servers[1].fd);
    close(servers[2].fd);
    close(servers[3].fd);

    exit(0);
}
示例#12
0
void ListenRISRequests::newRISRequest()
{
    QTcpSocket *tcpSocket = m_tcpRISServer->nextPendingConnection();
    QString risRequestData;

    INFO_LOG("Rebuda peticio de la IP " + tcpSocket->peerAddress().toString());
    if (tcpSocket->waitForReadyRead(TimeOutToReadData))
    {
        risRequestData = QString(tcpSocket->readAll());
        INFO_LOG("Dades rebudes: " + risRequestData);
    }
    else
    {
        INFO_LOG("No s'ha rebut dades, error: " + tcpSocket->errorString());
    }

    INFO_LOG("Tanco socket");
    tcpSocket->disconnectFromHost();
    INFO_LOG("Faig delete del socket");
    delete tcpSocket;

    if (!risRequestData.isEmpty())
    {
        processRequest(risRequestData);
    }
}
void *handleCall(void *ta)
{
    //int fd = *(int *)fdPointer;
    struct threadArguments *taPointer = (struct threadArguments *)ta;
    int fd = taPointer->fd;
    struct logInformation logInfo = taPointer->logInfo;
    free(ta);
    char request[BUFFERLENGTH];
    
    // read request
    FILE *inputStream = fdopen(fd, "r");
    fgets(request, BUFFERLENGTH, inputStream);
    //printf("Received a call on %d: request = %s", fd, request);
    skipRestOfHeader(inputStream);
    
    // process request
    processRequest(request, fd, &logInfo);
    
    fclose(inputStream);
    
    // clean up the memory allocated for the log strings
    //free(logInfo.IPaddress);
    //free(logInfo.timeRequestReceived);
    free(logInfo.quotedFirstLineOfRequest);
}
示例#14
0
	integer ServiceApp::pumpMessages()
	{
/*		if(instance->takeOwnership() == false)
			return -1;*/

		timeout = naturalNull;
		bool go_on = true;
		while(go_on){
			try {
				natural counter = 0;
				bool request = instance->anyRequest();
				while(!request && onIdle(counter)){
					counter++;
					request = instance->anyRequest();
				}
				const void *req = instance->waitForRequest(timeout);
				if(req){
					go_on = processRequest(req);
				} else {
					go_on = !stopCommand;
				}
			}
			catch(const Exception & e){
				onWaitException(e);
			}
		}

		return 0;
	}
示例#15
0
void * threadRequest(void * args)
{
	int slaveSocket = (intptr_t) args;
	processRequest(slaveSocket);
	
	// Close socket
	close( slaveSocket );
}
示例#16
0
文件: server.c 项目: wudikua/lookup
int serverRead(event *ev, int fd) {
	lookup_log(LOG_DEBUG, "read\n");
	int read = 0;
	char buf[IO_PACKET_SIZE];

	if (ev->wr_pos == 0) {
		read = anetRead(fd, &buf[0], PROTOCOL_HAEDER_SIZE);
		if (read == 0 && errno == ECONNRESET) {
free_conn:
			ev->wr_pos = 0;
			del_event(pool, fd);	
			close(fd);
			zfree(ev->data);
			lookup_log(LOG_DEBUG, "close fd\n");
			return 0;
		}
		ev->data = parse_protocol_header(buf);
	} else {
		int block = (ev->data->body_len + PROTOCOL_HAEDER_SIZE - ev->wr_pos) 
			/ IO_PACKET_SIZE;
		if (block > 0) {
			read = anetRead(fd, &buf[0], IO_PACKET_SIZE);			
		} else {
			read = anetRead(fd, &buf[0], 
				(ev->data->body_len + PROTOCOL_HAEDER_SIZE - ev->wr_pos) % IO_PACKET_SIZE);			
		}
		if (read == 0 && errno == ECONNRESET) {
			goto free_conn;
		}
		if (ev->body_data == NULL) {
			ev->body_data_size = IO_PACKET_SIZE * 2;
			ev->body_data = (char *)zmalloc(ev->body_data_size);
			memcpy(ev->body_data + ev->body_data_wr_pos, buf, read);
			ev->body_data_wr_pos += read;
		} else {
			if ((ev->body_data_wr_pos + read) > ev->body_data_size) {
				//resize
				ev->body_data_size = ev->body_data_size * 2;
				ev->body_data = (char *)zrealloc(ev->body_data, 
					ev->body_data_size);
			}
			memcpy(ev->body_data + ev->body_data_wr_pos, buf, read);
			ev->body_data_wr_pos += read;
		}
	}
	if (read > 0) {
		ev->wr_pos += read;	
	}
	lookup_log(LOG_DEBUG, "pos:%d\n", ev->wr_pos);
	if (ev->wr_pos >= (ev->data->body_len +  PROTOCOL_HAEDER_SIZE)) {
		parse_protocol_body(ev->body_data, ev->data);
		ev->wr_pos = 0;
		processRequest((lookup_protocol *)ev->data);
		ev->cb = serverWrite;
		set_event(pool, fd, EPOLLOUT);
	}
	return 0;
}
示例#17
0
	void Page::handleRequest(Callback cb) {
		this->cb = cb;
		try {
			processRequest();
		} catch (exception& ex) {
			server->handleError(*request, *response, ex, cb);
			destruct();
		}
	}
示例#18
0
文件: Task.cpp 项目: tsalidis/dune
      void
      onMain(void)
      {
        setInitialState();

        while (!stopping())
        {
          if (m_report_timer.overflow())
          {
            if (m_args.progress)
              reportProgress();

            dispatch(m_pcs);

            m_report_timer.reset();
          }

          double now = Clock::get();

          if ((getEntityState() == IMC::EntityState::ESTA_NORMAL) &&
              (now - m_last_vstate >= c_vs_timeout))
          {
            changeMode(IMC::PlanControlState::PCS_BLOCKED, DTR("vehicle state timeout"));
            m_last_vstate = now;
          }

          // got requests to process
          if (!pendingReply() && m_requests.size())
          {
            processRequest(&m_requests.front());
            m_requests.pop();
          }

          double delta = m_vc_reply_deadline < 0 ? 1 : m_vc_reply_deadline - now;

          if (delta > 0)
          {
            waitForMessages(std::min(1.0, delta));
            continue;
          }

          // handle reply timeout
          m_vc_reply_deadline = -1;

          changeMode(IMC::PlanControlState::PCS_READY, DTR("vehicle reply timeout"));

          // Popping all requests
          while (m_requests.size())
            m_requests.pop();

          // Increment local request id to prevent old replies from being processed
          ++m_vreq_ctr;

          err(DTR("cleared all requests"));
        }
      }
示例#19
0
int listenPort(int port) 
{
    int socket_desc , client_sock, c, *new_sock;
    struct sockaddr_in server , client;
     
    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Failed Creating Socket!");
    }
    puts("Socket created!");
     
    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( port );
     
    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
        //print the error message
        perror("ERROR: Binding Failed");
        return 1;
    }
    puts("binding completed!");
     
    //Listen
    listen(socket_desc , 3);
     
    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);
    while((client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)))
    {
        puts("Accepted Connection Request!");
        new_sock = malloc(1);
        *new_sock = client_sock;
         
        if(fork() == 0){
            printf("Connected to Socket! %d\n", server_port);         
            processRequest(client_sock);    
            exit(0);        
        }
         
        puts("Handlers assigned!");
    }
     
    if (client_sock < 0)
    {
        perror("failed connection!");
        return 1;
    }
    return 0;
}
示例#20
0
void FileSystem::pathHandler(FileSystemMessage *msg)
{
    // Copy the request
    FileSystemRequest *req = new FileSystemRequest(msg);

    // Process the request.
    if (processRequest(req) == EAGAIN)
        m_requests->append(req);
    else
        delete req;
}
示例#21
0
void processFirstRequest()
{
	if (invalidated || requests.empty())
		return;
	c_publish_event("checked");

	c_wait_event("cleared");
	c_assert_false(requests.empty(), "requests queue is empty!");
	processRequest(requests.front());
	requests.pop();
}
示例#22
0
QVariant RequestManager::processMessage(QString buffered_message)
{
    // Parse function method and parameters
    buffered_message.chop(1);
    buffered_message.remove(0,1);
    // First turn string into QJSonDocument
    QJsonParseError error;
    QJsonDocument document( QJsonDocument::fromJson(buffered_message.toLocal8Bit(),&error));
    // Check if there was an error
    if(error.error != QJsonParseError::NoError)
    {
        qDebug() << "Error Parsing incoming Json Message:" << error.errorString() << "\nMessage Recieved: " << buffered_message;
        return QVariant();
    }

    // Begin Parsing Arguments
    QJsonArray request_array (document.array());
    QVariant parameter;
    QJsonObject func = request_array.first().toObject();
    int param_count = request_array.size()-1;
    if(param_count > 1)
    {
        QVariantList params;
        for(int i = 1; i < param_count+1; ++i)
        {
            params.append(request_array.at(i).toObject());
        }
        parameter.setValue(params);
    }
    else if( param_count == 1)
    {
        parameter = QVariant::fromValue(request_array.at(param_count).toObject());
    }
    else
    {
        parameter = QVariant();
    }
    QString functionname(func["FuncName"].toString());
    QTcpSocket * caller(qobject_cast<QTcpSocket*>(sender()));
    QVariant return_val = processRequest(functionname,caller,parameter);
    if(!return_val.isNull())
    {
        QJsonObject obj = return_val.value<QJsonObject>();
        QJsonDocument doc;
        doc.setObject(obj);
        QByteArray message(doc.toJson());
        return_val = QVariant::fromValue(doc);
        message.push_front("\001");
        message.push_back("\004");
        emit returnMessageReady(caller,message);
    }

    return return_val;
}
示例#23
0
int cutstock::processRequest(vector<int> & requests, pipeStock & state) {
	
	cout << "processing remaining requests\n";
	printvec(requests);
	
	cout << "at state\n";
	printdvec(state);
	
	// static int memHit=0;
	
	if (requests.empty()) return state.size();
	
	
	
	int nextReq=requests.back();
	requests.pop_back();
	
	set<int> numPipes;
	
	for (int i=0; i<state.size()+1; i++) {
		
		if (i == state.size() || checkPipe(state[i], nextReq)) {
			pipeStock newState=state;
			vector<int> newReq=requests;
			
			if (i == state.size()) {
				pipe p;
				newState.push_back(p);
			}
			newState[i].push_back(nextReq);
			int stocks;
			//search memory
			if (m.find(mapIndex(newState)) != m.end()) {
				stocks=m.find(mapIndex(newState))->second;
				memHit++;
			}
			else {
			//if not found in memory, go through recursion
				stocks=processRequest(newReq, newState);
			//record it in memory
				m[mapIndex(newState)]=stocks;
			}
			
			numPipes.insert(stocks);
			
			
// 			numPipes.insert(processRequest(newReq, newState));
		}
	}
	
	set<int>::iterator it=numPipes.begin();
	return *it;
		
}
示例#24
0
void ESURegistration::processRequest(int indexRequest, bool accept)
{
    QString addr; // = d->ui->modelQueries.getAddress(indexRequest);

    if(processRequest(addr, accept))
    {
        //d->ui->modelQueries.remove(indexRequest);
    } else
    {
        //d->ui->messageBox("Ошибка", "Пустой адрес отправителя");
    }
}
示例#25
0
QString KDEPrintd::requestPassword(const QString &user, const QString &host, int port, int seqNbr)
{
    Request *req = new Request;
    req->user = user;
    req->uri = "print://" + user + "@" + host + ":" + QString::number(port);
    req->seqNbr = seqNbr;
    req->transaction = callingDcopClient()->beginTransaction();
    m_requestsPending.append(req);
    if(m_requestsPending.count() == 1)
        QTimer::singleShot(0, this, SLOT(processRequest()));
    return "::";
}
示例#26
0
文件: client.c 项目: ChellsChen/wind
void  processInputBuffer(vuiClient *c)
{
    int res;
    char *buf;
    int len;

    buf = c->querybuf;
    len = sdslen(c->querybuf);

    if (c->prot.waiting)
    {
        if (len >= c->prot.waiting)
        {
            c->querymsg = sdscatlen(c->querymsg, buf, c->prot.waiting);
            buf += c->prot.waiting;
            c->prot.waiting = 0;
            goto deal;
        }
        else
        {
            c->querymsg = sdscatlen(c->querymsg, buf, len);
            c->prot.waiting -= len;
            goto clear;
        }
    }

    while((buf = strstr(buf, REQUEST_POST " ")))//找报文头
    {
        res = resloveMessage(&buf, c);
        switch(res)
        {
            case -3:
                goto clear;
            case -2://contiune read
                if (buf != c->querybuf)
                {
                    sdsrange(c->querybuf, buf - c->querybuf, -1);
                }
                goto res;
            case 0:
deal:
                c->prot.body = c->querymsg + c->prot.hlenght;
                processRequest(c);
            case -1:
                break;
        }
    }
clear:
    sdsclear(c->querybuf);
res:
    return;
}
示例#27
0
void
TinyWebServer::readFromSocket()
{
    Q_ASSERT( m_clientSocket );

    m_header += m_clientSocket->read( m_clientSocket->bytesAvailable() );
    if ( m_header.endsWith( "\r\n\r\n" ) )
    {
        processRequest();
        m_clientSocket->disconnectFromHost();
        m_tcpServer->close();
    }
}
示例#28
0
void run_server(int port,char document_root[])
{

	int sock, cli;
	struct sockaddr_in server,client;
	unsigned int len;
	//char mesg[] = "Hello to the world of socket programming";
	int *sent;

	if((sock = socket(AF_INET,SOCK_STREAM,0)) == -1)
			{
			perror("socket: ");
			exit(-1);
			}
	
	server.sin_family = AF_INET;
	server.sin_port = htons(port);
	server.sin_addr.s_addr = INADDR_ANY;
	bzero(&server.sin_zero,8);
	
	len = sizeof(struct sockaddr_in);
	
	if((bind(sock,(struct sockaddr *)&server,len)) == -1)
	{
		perror("bind");
		exit(-1);
	}

	if((listen(sock,5))==-1)
	{
		perror("listen");
		exit(-1);
	}

	while(1)
	{
		if((cli = accept(sock, (struct sockaddr *)&client,&len))==-1)
		{
			perror("accept");
			exit(-1);
		}
		
		//sent = send(cli, mesg, strlen(mesg),0);
		//printf("Sent %d bytes to client : %s\n",sent,inet_ntoa(client.sin_addr));
        *sent = cli;
        processRequest((void *) sent,document_root);

		close(cli);
	}
	
}
示例#29
0
        void EstablishmentManager::stateChanged(EstablishmentStatePtr es)
        {
            const Endpoint &ep = es->getTheirEndpoint();
            I2P_LOG_SCOPED_TAG(m_log, "Endpoint", ep);

            switch(es->getState())
            {
                case EstablishmentState::State::REQUEST_SENT:
                    I2P_LOG(m_log, debug) << "sent session request";
                    break;

                case EstablishmentState::State::REQUEST_RECEIVED:
                    I2P_LOG(m_log, debug) << "received session request";
                    processRequest(es);
                    break;

                case EstablishmentState::State::CREATED_SENT:
                    I2P_LOG(m_log, debug) << "sent session created";
                    break;

                case EstablishmentState::State::CREATED_RECEIVED:
                    I2P_LOG(m_log, debug) << "received session created";
                    processCreated(es);
                    break;

                case EstablishmentState::State::CONFIRMED_SENT:
                    {
                        const RouterHash &rh = es->getTheirIdentity().getHash();
                        I2P_LOG_SCOPED_TAG(m_log, "RouterHash", rh);
                        I2P_LOG(m_log, debug) << "sent session confirmed";
                        m_context.ios.post(boost::bind(boost::ref(m_context.establishedSignal), rh, (es->getDirection() == EstablishmentState::Direction::INBOUND)));
                        delState(ep);
                    }
                    break;

                case EstablishmentState::State::CONFIRMED_RECEIVED:
                    I2P_LOG(m_log, debug) << "received session confirmed";
                    processConfirmed(es);
                    break;

                case EstablishmentState::State::UNKNOWN:
                case EstablishmentState::State::FAILURE:
                    I2P_LOG(m_log, info) << "establishment failed";
                    if(es->getDirection() == EstablishmentState::Direction::OUTBOUND)
                        m_context.ios.post(boost::bind(boost::ref(m_context.failureSignal), es->getTheirIdentity().getHash()));

                    delState(ep);
                    break;
            }
        }
示例#30
0
文件: Task.cpp 项目: tsalidis/dune
      void
      consume(const IMC::PlanControl* pc)
      {
        if (pc->type != IMC::PlanControl::PC_REQUEST)
          return;

        if (pendingReply())
        {
          m_requests.push(*pc);
          debug("saved request %u", pc->request_id);
          return;
        }
        else if (m_requests.size())
        {
          m_requests.push(*pc);
          processRequest(&m_requests.front());
          m_requests.pop();
        }
        else
        {
          processRequest(pc);
        }
      }