//TODO multiple packets in 1 read
bool DatabaseConnection::parse(  char *data, int len){

	LOG4CXX_DEBUG(logger,"In DatabaseConnection::parse() :" << len) ;
	if(len < 1){
		return false;
	}
	packet_data_length = len;
	int offset_describe = 0;
	int frame_offset = 0;
	// Reverse parse to find @ then move forward
	if(*(data) == '@'){
		LOG4CXX_DEBUG(logger,"Found describe packet " );


		while(*(data+offset_describe) == '@' && offset_describe < len){
			string end = (data+offset_describe);
			if(len > 5){
				if(end.size() > 5 && end.at(1) == ' ' && end.at(2) == '[' && end.find_first_of('-') != -1){
					event.appname = "mysql";
					event.src_ip = "127.0.0.1";

					event.appname = end.substr(3,end.find_first_of(':')-3);
					string port = end.substr(end.find_first_of(':')+1,(end.find_first_of('-') - (end.find_first_of(':')+1)));
					event.src_port = (short)atoi(port.c_str());
					frame_offset = end.find_first_of(']')+2;

					event_timestamp event_ts;
				    event_ts.event_in_s = std::time(0);
				    event_ts.event_in_ms = 0;
					userManager.regEventTimestamp(event.src_ip,port,event_ts);
					userManager.regAppName(event.src_ip,port,event.appname);
				}
			}



			int start_of_packet = end.find_first_of(':',frame_offset);
			packet_data_length = atoi(end.substr(frame_offset,start_of_packet-frame_offset).c_str());
			LOG4CXX_DEBUG(logger,"SRC Packet size:" << end.substr(frame_offset,start_of_packet-frame_offset) << ":" << packet_data_length);


			memcpy(packet_data,data+start_of_packet+1+offset_describe,packet_data_length);

			parseRequest(0);

			offset_describe = offset_describe + start_of_packet+1+packet_data_length;
		}
		LOG4CXX_DEBUG(logger,"Exiting DatabaseConnection::parse()");
		return true;
	}else{


		memcpy(packet_data,data+offset_describe,len-offset_describe);

		bool rc = parseRequest(0);

		LOG4CXX_DEBUG(logger,"Exiting DatabaseConnection::parse()");
		return rc;
	}
}
    void listener() {
        //start timer:
        struct timeval tv,tv1;
        gettimeofday(&tv,NULL);
        int start_time;
        memcpy(&start_time, &tv.tv_sec, sizeof(int));
        //timeout:
        tv1.tv_sec=PERS_TIME_OUT;
        tv1.tv_usec=0;
        setsockopt(newsockfd, SOL_SOCKET, SO_RCVTIMEO,
                   (char *)&tv1,sizeof(struct timeval));
        while(tv.tv_sec-start_time<PERS_TIME_OUT) {
            recv(newsockfd,buf,4096,0);
            if(std::string(buf).length()==0) {
                //probably just tcp keepalive message, ignore.
                gettimeofday(&tv,NULL);
                continue;
            }
            parseRequest(buf);

            memset(buf,0,4096);
            std::string content=serializeFile(this->requestFile.c_str());
            sendStr(content.c_str(),content.length());
            gettimeofday(&tv,NULL);
        }
        return;
    }
Beispiel #3
0
QHttpConnection::QHttpConnection(QTcpSocket *socket, QObject *parent)
    : QObject(parent),
      m_socket(socket),
      m_parser(0),
      m_parserSettings(0),
      m_request(0),
      m_transmitLen(0),
      m_transmitPos(0)
{
    m_parser = (http_parser *)malloc(sizeof(http_parser));
    http_parser_init(m_parser, HTTP_REQUEST);

    m_parserSettings = new http_parser_settings();
    m_parserSettings->on_message_begin = MessageBegin;
    m_parserSettings->on_url = Url;
    m_parserSettings->on_header_field = HeaderField;
    m_parserSettings->on_header_value = HeaderValue;
    m_parserSettings->on_headers_complete = HeadersComplete;
    m_parserSettings->on_body = Body;
    m_parserSettings->on_message_complete = MessageComplete;

    m_parser->data = this;

    connect(socket, SIGNAL(readyRead()), this, SLOT(parseRequest()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
    connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(updateWriteCount(qint64)));
}
void TWorker::work(int socket)
{
    std::string request;
    std::string fileName;
   // setNonBlock(socket);

    if( readRequest(socket, request) ) {
        #if defined(DEBUG)
            std::cout << "\n\nReqest:\n" << request;
        #endif
        std::string answer;
        if( parseRequest(request, fileName) ) {
            std::string context;
            if( getContext(fileName, context) ) {
                answer = createHeader(200, context.size() ) + context;
            }
            else {
                answer = createHeader(404);
            }
        }
        else {
            answer = createHeader(500);
        }
        #if defined(DEBUG)
            std::cout << "\n\nAnswer:\n" << answer;
        #endif
        sendAnswer(socket, answer);
    }
    disconnect(socket);
}
Beispiel #5
0
    Status CmdCount::explain(OperationContext* txn,
                             const std::string& dbname,
                             const BSONObj& cmdObj,
                             Explain::Verbosity verbosity,
                             BSONObjBuilder* out) const {
        CountRequest request;
        Status parseStatus = parseRequest(dbname, cmdObj, &request);
        if (!parseStatus.isOK()) {
            return parseStatus;
        }

        // Acquire the db read lock.
        Client::ReadContext ctx(txn, request.ns);
        Collection* collection = ctx.ctx().db()->getCollection(txn, request.ns);

        PlanExecutor* rawExec;
        Status getExecStatus = getExecutorCount(txn, collection, request, &rawExec);
        if (!getExecStatus.isOK()) {
            return getExecStatus;
        }
        scoped_ptr<PlanExecutor> exec(rawExec);

        const ScopedExecutorRegistration safety(exec.get());

        return Explain::explainStages(exec.get(), verbosity, out);
    }
bool HttpHandler::serveConnection(char *clientRequest, char **responseToSend, size_t *sizeOfResponseToSend, bool timedOut)
{
    if(timedOut)
        responseTimeOut();
    else
    {
        if(clientRequest)
        {
            this->request = clientRequest;
            this->isNew = true;
            bool parseOkay = parseRequest();
        }
        else
            this->isNew = false;

        getResponse();
    }

    *responseToSend = this->response;
    *sizeOfResponseToSend = this->sizeOfResponse;
    this->fileSizeForPublic = this->fileSize;

    if(this->dataLeft == 0)
        return true;
    else
        return false;
}
void ApiV2::parseRemoteCommand(Command &command)
{
    if (command.data->length() >= 2)
    {
        switch (command.data->at(1)) {
        case cmd_mouse:
            parseMouseCommand(command);
            break;
        case cmd_pointer:
            parsePointerCommand(command);
            break;
        case cmd_media:
            parseMediaCommand(command);
            break;
        case cmd_request:
            parseRequest(command);
            break;
        case cmd_laser:
            parseLaserCommand(command);
            break;
        case cmd_custom:
            parseCustomCommand(command);
            break;
        default:
            //Logger::Instance()->add("Unkown remote command");
            break;
        }
    }
}
Beispiel #8
0
bool Catalog::getItemsFromQuery(InputList &inputData, QList<CatItem>& outResults,
                                int itemsDesired,
                                int* beginPos){

    QString userKeys = inputData.getUserKeys();
    QList<CatItem> partialList = parseRequest(inputData,itemsDesired, beginPos);
    plugins.getLabels(&inputData);
    plugins.getResults(&inputData, &partialList);

    //outResults = expandStubs(inputData.getUserKeys(), &partialList);
    outResults = partialList;

    //Skipping because it should happen in more detail later...
    //...
    //Sort by single keys ... even if we're on multiple words otherwise
    if(inputData.selectingByKeys()){
        Catalog::curFilterStr = userKeys;
        qSort(outResults.begin(), outResults.end(), CatLessNoPtr);

        while(outResults.count() > itemsDesired ){
            outResults.pop_back();
        }
    }

    return true;
}
Beispiel #9
0
        virtual Status explain(OperationContext* txn,
                               const std::string& dbname,
                               const BSONObj& cmdObj,
                               ExplainCommon::Verbosity verbosity,
                               BSONObjBuilder* out) const {

            CountRequest request;
            Status parseStatus = parseRequest(dbname, cmdObj, &request);
            if (!parseStatus.isOK()) {
                return parseStatus;
            }

            request.explain = true;

            // Acquire the db read lock.
            AutoGetCollectionForRead ctx(txn, request.ns);
            Collection* collection = ctx.getCollection();

            PlanExecutor* rawExec;
            Status getExecStatus = getExecutorCount(txn,
                                                    collection,
                                                    request,
                                                    PlanExecutor::YIELD_AUTO,
                                                    &rawExec);
            if (!getExecStatus.isOK()) {
                return getExecStatus;
            }

            scoped_ptr<PlanExecutor> exec(rawExec);

            Explain::explainStages(exec.get(), verbosity, out);
            return Status::OK();
        }
Beispiel #10
0
void handleIncomingRequests(int socketfd){

	for(;;){
		printf("Waiting for connection...\n");
		int connectfd = accept(socketfd, NULL, NULL);
		if(0 > connectfd){
			perror("Error accept failed");
			close(socketfd);
			exit(EXIT_FAILURE);
		}

		zHttpRequest *zreq = parseRequest(connectfd);
		sendResponse(zreq);

		freeReq(zreq);

		if( -1 == shutdown(connectfd, SHUT_RDWR) ) {
			perror("cannot shutdown socket\n");
			close(connectfd);
			exit(EXIT_FAILURE);
		}

		close(connectfd);
		printf("Terminated Connection Following Response\n");

	}
}
Beispiel #11
0
HttpMessage simplesocket::ReceiveHttpMessage(){
  string message;
  string s;
  char temp;
  while (true){
    recvNBytes(&temp, 1, false);
    s = temp;
    message += s;
    if (temp == 0xD)
      {
	recvNBytes(&temp,1, false);
	s = temp;
	message += s;
	if (temp == 0xA)
	  break;
      }
  }

  HttpMessage ret = parseRequest(message);
  recvNBytes(&temp, 1, false);
  s = temp;
  message += s;
  if (temp == 0xD){
    recvNBytes(&temp,1, false);
    s = temp;
    message += s;
    if (temp == 0xA)
      {
	return ret;
      }
  }
  while (true){
    recvNBytes(&temp, 1, false);
    s = temp;
    message += s;
    if (temp == 0xD){
      recvNBytes(&temp,1, false);
      s = temp;
      message += s;
      if (temp == 0xA){
	recvNBytes(&temp,1, false);
	s = temp;
	message += s;
	if (temp == 0xD){
	  recvNBytes(&temp,1, false);
	  s = temp;
	  message += s;
	  if (temp == 0xA)
	    {
	      if (_debug)
		cout << "Full message: " << message << endl;
	      return ret;
	    }
	}
      }
    }
  }
}
void test_cmd0x03separator(void)
{
	REQUEST_STRUCT request = {0,0};
	for(int i = 0; i < 10; i++)//multiple loops to check for data corruption
	{	
		parseRequest(&request, "cmd=0x03;", strlen("cmd=0x03;"));
		TEST_ASSERT_EQUAL(3, request.cmd);
	}
}
void test_cmd0x04value0x02request(void)
{
	REQUEST_STRUCT request = {0,0};
	for(int i = 0; i < 10; i++)//multiple loops to check for data corruption
	{		
		parseRequest(&request, "cmd=0x04;val=0x02", strlen("cmd=0x04;val=0x02"));
		TEST_ASSERT_EQUAL(4, request.cmd);
		TEST_ASSERT_EQUAL(2, request.val);
	}	
}
Beispiel #14
0
void handle(int sock, char* buf, fd_set *set, int i){
    printf("sending HTTP header to back to socket %d\n", sock);

    httpRequest details = parseRequest(buf);
    sendHeader(sock, details.returncode, details.filename);
    sendFile(sock, details.filename);

    //close(sock);
    //FD_CLR(sock, set);
    //client_sockets[i] = 0;
}
Beispiel #15
0
void DebuggerIPCServer::requestThread() {
  while (!kill_thread) {
    // non-blocking (timeout after 100ms)
    PFPSimDebugger::DebugMsg *request = recv();
    if (request) {
      // std::cout << "Msg Received!" << std::endl;
      parseRequest(request);
      delete request;
    }
  }
}
 //non-persistent service:
 void serviceRequest() {
     //printf("non-persistent service\n");
     //first, create a thread that listens for requests.
     //int reqsize=read(newsockfd, buf, 4096);
     read(newsockfd,buf,4096);
     parseRequest(buf);
     memset(buf,0,4096);
     std::string content=
         serializeFile(this->requestFile.c_str());
     //std::cout<<"content:\n"<<content<<std::endl;
     sendStr(content.c_str(),content.length());
 }
HandleRequestReply handleRequest(struct evhttp_request* req, worker* workerPtr,
			   struct evkeyvalq* replyHeaders, struct evbuffer* replyBody) {
  RequestInfo requestInfo = {req, workerPtr};  // partial init (http://stackoverflow.com/questions/10828294/c-and-c-partial-initialization-of-automatic-structure)
  RequestOutput requestOutput = {replyHeaders, replyBody};
  
  parseRequest(requestInfo);

  WebHandlerInternal* const webHandlerInternal = WebHandlerInternal::bindIfExists();
  if (webHandlerInternal == nullptr) {
    return WebHandler::replyServerUnavail;
  }
  return webHandlerInternal->process(requestInfo, requestOutput);
}
Beispiel #18
0
    bool GroupCommand::run(OperationContext* txn,
                           const std::string& dbname,
                           BSONObj& cmdObj,
                           int,
                           std::string& errmsg,
                           BSONObjBuilder& out,
                           bool fromRepl) {
        GroupRequest groupRequest;
        Status parseRequestStatus = parseRequest(dbname, cmdObj, &groupRequest);
        if (!parseRequestStatus.isOK()) {
            return appendCommandStatus(out, parseRequestStatus);
        }

        Client::ReadContext ctx(txn, groupRequest.ns);
        Database* db = ctx.ctx().db();

        PlanExecutor *rawPlanExecutor;
        Status getExecStatus = getExecutorGroup(txn, db, groupRequest, &rawPlanExecutor); 
        if (!getExecStatus.isOK()) {
            return appendCommandStatus(out, getExecStatus);
        }
        scoped_ptr<PlanExecutor> planExecutor(rawPlanExecutor);

        // Group executors return ADVANCED exactly once, with the entire group result.
        BSONObj retval;
        PlanExecutor::ExecState state = planExecutor->getNext(&retval, NULL);
        if (PlanExecutor::ADVANCED != state) {
            if (PlanExecutor::EXEC_ERROR == state &&
                WorkingSetCommon::isValidStatusMemberObject(retval)) {
                return appendCommandStatus(out, WorkingSetCommon::getMemberObjectStatus(retval));
            }
            return appendCommandStatus(out,
                                       Status(ErrorCodes::BadValue,
                                              str::stream() << "error encountered during group "
                                                            << "operation, executor returned "
                                                            << PlanExecutor::statestr(state)));
        }
        invariant(planExecutor->isEOF());

        invariant(STAGE_GROUP == planExecutor->getRootStage()->stageType());
        GroupStage* groupStage = static_cast<GroupStage*>(planExecutor->getRootStage());
        const GroupStats* groupStats =
            static_cast<const GroupStats*>(groupStage->getSpecificStats());
        const CommonStats* groupChildStats = groupStage->getChildren()[0]->getCommonStats();

        out.appendArray("retval", retval);
        out.append("count", static_cast<long long>(groupChildStats->advanced));
        out.append("keys", static_cast<long long>(groupStats->nGroups));

        return true;
    }
void WebServerInstance::readPartialRequest()
{
  if (! m_socket)                                          // to be sure.
    return;

  //while ((m_socket->isReadable()) && (m_socket->bytesAvailable() > 0)) {
  while (m_socket->canReadLine()) {
    QByteArray neu = m_socket->readAll();
    neu.replace('\r', "");                                 // we don't need them
    m_array.append(neu);

    parseRequest();
  }
}
Beispiel #20
0
void parserSelector(const Byte* bytes, size_t size, Log& logfile)
{
	UINT64 signature = *((UINT64*)(bytes + 4));
	if (signature == kRequestSignature)
	{
		parseRequest(bytes, logfile);
	}
	else if (signature == kResponseSignature)
	{
		parseResponse(bytes, logfile);
	}
	else
	{
		printf("invalid packet file\n");
	}	
}
bool DatabaseConnection::parse(const u_char *packet, pcap_pkthdr *header, int packet_offset)
{
	LOG4CXX_DEBUG(logger,"In DatabaseConnection::parse()");

	//First parse the header for non DBMS specific information
	parseHeader(packet,header,packet_offset);

	//As were not looking at responses yet parse the request
	bool rc = parseRequest(0);

	LOG4CXX_DEBUG(logger,"Exiting DatabaseConnection::parse()");



	return rc;
}
Beispiel #22
0
        virtual bool run(OperationContext* txn,
                         const string& dbname,
                         BSONObj& cmdObj,
                         int, string& errmsg,
                         BSONObjBuilder& result,
                         bool fromRepl) {

            CountRequest request;
            Status parseStatus = parseRequest(dbname, cmdObj, &request);
            if (!parseStatus.isOK()) {
                return appendCommandStatus(result, parseStatus);
            }

            AutoGetCollectionForRead ctx(txn, request.ns);
            Collection* collection = ctx.getCollection();

            PlanExecutor* rawExec;
            Status getExecStatus = getExecutorCount(txn,
                                                    collection,
                                                    request,
                                                    PlanExecutor::YIELD_AUTO,
                                                    &rawExec);
            if (!getExecStatus.isOK()) {
                return appendCommandStatus(result, getExecStatus);
            }

            scoped_ptr<PlanExecutor> exec(rawExec);

            // Store the plan summary string in CurOp.
            if (NULL != txn->getCurOp()) {
                txn->getCurOp()->debug().planSummary = Explain::getPlanSummary(exec.get());
            }

            Status execPlanStatus = exec->executePlan();
            if (!execPlanStatus.isOK()) {
                return appendCommandStatus(result, execPlanStatus);
            }

            // Plan is done executing. We just need to pull the count out of the root stage.
            invariant(STAGE_COUNT == exec->getRootStage()->stageType());
            CountStage* countStage = static_cast<CountStage*>(exec->getRootStage());
            const CountStats* countStats =
                static_cast<const CountStats*>(countStage->getSpecificStats());

            result.appendNumber("n", countStats->nCounted);
            return true;
        }
Beispiel #23
0
void NSClientSocket::onAccept(simpleSocket::Socket client) {
	if (!inAllowedHosts(client.getAddrString())) {
		NSC_LOG_ERROR("Unothorized access from: " + client.getAddrString());
		client.close();
		return;
	}
	simpleSocket::DataBuffer db;
	client.readAll(db);
	if (db.getLength() > 0) {
		std::string incoming(db.getBuffer(), db.getLength());
		NSC_DEBUG_MSG_STD("Incoming data: " + incoming);
		std::string response = parseRequest(incoming);
		NSC_DEBUG_MSG("Outgoing data: " + response);
		client.send(response.c_str(), static_cast<int>(response.length()), 0);
	}
	client.close();
}
Beispiel #24
0
    bool CmdCount::run(OperationContext* txn,
                       const string& dbname,
                       BSONObj& cmdObj,
                       int, string& errmsg,
                       BSONObjBuilder& result, bool) {
        CountRequest request;
        Status parseStatus = parseRequest(dbname, cmdObj, &request);
        if (!parseStatus.isOK()) {
            return appendCommandStatus(result, parseStatus);
        }

        // Acquire the db read lock.
        Client::ReadContext ctx(txn, request.ns);
        Collection* collection = ctx.ctx().db()->getCollection(txn, request.ns);

        PlanExecutor* rawExec;
        Status getExecStatus = getExecutorCount(txn, collection, request, &rawExec);
        if (!getExecStatus.isOK()) {
            return appendCommandStatus(result, getExecStatus);
        }
        scoped_ptr<PlanExecutor> exec(rawExec);

        // Store the plan summary string in CurOp.
        if (NULL != txn->getCurOp()) {
            PlanSummaryStats stats;
            Explain::getSummaryStats(exec.get(), &stats);
            txn->getCurOp()->debug().planSummary = stats.summaryStr.c_str();
        }

        const ScopedExecutorRegistration safety(exec.get());

        Status execPlanStatus = exec->executePlan();
        if (!execPlanStatus.isOK()) {
            return appendCommandStatus(result, execPlanStatus);
        }

        // Plan is done executing. We just need to pull the count out of the root stage.
        invariant(STAGE_COUNT == exec->getRootStage()->stageType());
        CountStage* countStage = static_cast<CountStage*>(exec->getRootStage());
        const CountStats* countStats =
            static_cast<const CountStats*>(countStage->getSpecificStats());

        result.appendNumber("n", countStats->nCounted);
        return true;
    }
Beispiel #25
0
void servertest(char *port) {
    char *request, *hostname, *response, *client_ip_address;
    struct sockaddr_in clientaddr;
    struct hostent *hp;
    int clientlen, connfd;

    // start listening and enter infinite listening loop
    int listenfd = Open_listenfd(port);
    while (1) {
        // accept a connection
        clientlen = sizeof(clientaddr);
        connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
        // get some information from the client
        hp = Gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr,
            sizeof(clientaddr.sin_addr.s_addr), AF_INET);
        client_ip_address = inet_ntoa(clientaddr.sin_addr);
        // read the request from the end-user
        request = read_until(connfd, "\r\n\r\n\0");
        // Store the hostname from the request
        hostname = parseRequest(request);
        // printf("S-Parse result:%s", hostname);
        if (hostname) {
            // Pass on the client's request
            response = clienttest(hostname, request);
            // printf("S-Response result:\n%s\n", response);
            //check that the response isn't empty (end-server responded)

            // respond to the end-user
            Rio_writen(connfd, response, strlen(response));
            // writeLogEntry (only if there was a response)
            if (strcmp(response, "") != 0) {
               writeLogEntry(client_ip_address, hostname, strlen(response));
               // printf("S-Wrote log.\n");
            }
        }
        // Finished, close connection
        Close(connfd);
        // Free the buffers except
        // client_ip_address is statically managed by inet_ntoa
        free(request);
        free(hostname);
        free(response);
    }
}
//this listens for rtsp packet and calls parseRequest 
//to fill info into rtspd such as videoName, request
//getResponse will generate a string reponse according
//the rtsp . Every loop listens(recv) and response(send).
void recieve_next_message(rtspd_t *rtspd){

	int client_fd = rtspd->client_fd;
	char buf[MAXDATASIZE];
	char response[MAXDATASIZE];
	int numbytes;
	int byte_sent;
	int count = 0;
	while(1){
		memset( buf, 0, sizeof(buf) );
		memset( response, 0, sizeof(response) );
		if ((numbytes = recv(client_fd, buf, MAXDATASIZE-1, 0)) == -1) {
		  perror("recv");
		  exit(1);
		}
		if(numbytes == 0){
			break;
		}
		printf("client_fd  %d\n", client_fd);
		printf("listener: packet is %d bytes long\n", numbytes);
		buf[numbytes] = '\0';
		printf("listener: packet contains \"%s\"\n", buf);

		//char response[MAXDATASIZE] = parse(buf);

		parseRequest(buf, rtspd);
		printf("request: %s, video = %s, cseq= %d, transport: %s, interleaved: %d.\n", rtspd->request, rtspd->videoName, rtspd->cseq, rtspd->transport, rtspd->interleaved);
		
		getResponse(rtspd, response);

		printf("response%d: \n\"%s\"\n", count, response);
		byte_sent = send(client_fd, response, strlen(response), 0);

		if (byte_sent == -1){
			perror("send");
			exit(1);
		}
		printf("bytes sent: %d\n", byte_sent);
		count++;
	}
	disconnect(rtspd);
}
Beispiel #27
0
void updateSerialReader()
{
    while(Serial.available() > 0 && parserReadyDelegate())
    {
        (*lineBuffer) = Serial.read();

        if(*lineBuffer == '\n')
        {
            lineBuffer = &buffer[0];
        	if(readingRequest)
        		parseRequest(lineBuffer);
        	else
        		parseGCodeDelegate(lineBuffer);
        }
        else if(*lineBuffer == '@')
        	readingRequest = true;
        else if(*lineBuffer != 32)
        	lineBuffer++;
    }
}
/******** DOSTUFF() *********************
 There is a separate instance of this function 
 for each connection.  It handles all communication
 once a connnection has been established.
 *****************************************/
void dostuff (int sock)
{
   int n,m;
   char buffer[BUF_SIZE],request[BUF_SIZE];
   bzero(buffer,BUF_SIZE);
   ReqInfo internalData;
   n = recv(sock,buffer,BUF_SIZE-1,0);
   if (n < 0) error("ERROR reading from socket");
   strcpy(request,buffer);
    internalData = parseRequest(request);
    //printf("%s,%s\n",internalData.Method,internalData.Protocol);
    printf("Here is the message:\n%s",buffer);
    bzero(buffer,BUF_SIZE);
    //PART A: Dump Request Message to the Console
    while (n == BUF_SIZE-1)
    {
        n = recv(sock,buffer,BUF_SIZE-1,0);
        if (n < 0) error("ERROR reading from socket");
        printf("%s",buffer);
        bzero(buffer,BUF_SIZE);
    }
   if(!IsValidHeader(internalData))
   {
       m = send(sock,"HTTP/1.1 400 Bad Request\r\n\r\n 400 Bad Request",sizeof("HTTP/1.1 400 Bad Request\r\n\r\n 400 Bad Request")-1,0);
       printf("HTTP/1.1 400 Bad Request\r\n\r\n");
       if (m < 0) error("ERROR writing to socket");
   }
   else if(Length(internalData.Path)<0)
    {
        m = send(sock,"HTTP/1.1 404 Not Found\r\n\r\n 404 Not found",sizeof("HTTP/1.1 404 Not Found\r\n\r\n 404 Not found")-1,0);
        printf("HTTP/1.1 404 Not Found\r\n\r\n");
        if (m < 0) error("ERROR writing to socket");
        //printf("%d",m);
        fprintf(stderr,"file cannot open\n");
    }
   
    else
    {datasend(sock,internalData.Path);}
   
}
Beispiel #29
0
    Status GroupCommand::explain(OperationContext* txn,
                                 const std::string& dbname,
                                 const BSONObj& cmdObj,
                                 Explain::Verbosity verbosity,
                                 BSONObjBuilder* out) const {
        GroupRequest groupRequest;
        Status parseRequestStatus = parseRequest(dbname, cmdObj, &groupRequest);
        if (!parseRequestStatus.isOK()) {
            return parseRequestStatus;
        }

        Client::ReadContext ctx(txn, groupRequest.ns);
        Database* db = ctx.ctx().db();

        PlanExecutor *rawPlanExecutor;
        Status getExecStatus = getExecutorGroup(txn, db, groupRequest, &rawPlanExecutor); 
        if (!getExecStatus.isOK()) {
            return getExecStatus;
        }
        scoped_ptr<PlanExecutor> planExecutor(rawPlanExecutor);

        return Explain::explainStages(planExecutor.get(), verbosity, out);
    }
Beispiel #30
0
/*
 *  Process incoming requests. This will process as many requests as possible before returning. All socket I/O is 
 *  non-blocking, and this routine must not block. 
 */
void maProcessReadEvent(MaConn *conn, MaPacket *packet)
{
    mprAssert(conn);

    conn->canProceed = 1;
    mprLog(conn, 7, "ENTER maProcessReadEvent state %d, packet %p", conn->state, packet);
    
    while (conn->canProceed) {
        mprLog(conn, 7, "maProcessReadEvent, state %d, packet %p", conn->state, packet);

        switch (conn->state) {
        case MPR_HTTP_STATE_BEGIN:
            conn->canProceed = parseRequest(conn, packet);
            break;

        case MPR_HTTP_STATE_CONTENT:
            conn->canProceed = processContent(conn, packet);
            packet = conn->input;
            break;

        case MPR_HTTP_STATE_PROCESSING:
            conn->canProceed = maServiceQueues(conn);
            break;

        case MPR_HTTP_STATE_COMPLETE:
            conn->canProceed = maProcessCompletion(conn);
            packet = conn->input;
            break;

        default:
            conn->keepAliveCount = 0;
            mprAssert(0);
            return;
        }
    }
    mprLog(conn, 7, "LEAVE maProcessReadEvent state %d, packet %p, dedicated %d", conn->state, packet, conn->dedicated);
}