int test_http_parser2() {
    http_parser_settings settings;
    settings.on_message_begin = on_message_begin;
    settings.on_url = request_url_cb;
    settings.on_status = on_status;
    settings.on_header_field = header_field_cb;
    settings.on_header_value = header_value_cb;
    settings.on_headers_complete = on_headers_complete;
    settings.on_body = on_body;
    settings.on_message_complete = on_message_complete;
    settings.on_chunk_header = NULL;
    settings.on_chunk_complete = NULL;

    http_parser parser;
    http_parser_init(&parser, HTTP_REQUEST);
    Request req;
    parser.data = &req;

    int nparsed = http_parser_execute(&parser, &settings, TEST_POST_REQ1.c_str(), TEST_POST_REQ1.size());
    LOG_INFO("parsed size:%d, parser->upgrade:%d,total_size:%u", nparsed, parser.upgrade, TEST_POST_REQ1.size());
    if (parser.http_errno) {
        LOG_INFO("ERROR:%s", http_errno_description(HTTP_PARSER_ERRNO(&parser)));
    }
    nparsed = http_parser_execute(&parser, &settings, TEST_POST_REQ2.c_str(), TEST_POST_REQ2.size());
    LOG_INFO("parsed size:%d, parser->upgrade:%d,total_size:%u", nparsed, parser.upgrade, TEST_POST_REQ2.size());
    if (parser.http_errno) {
        LOG_INFO("ERROR:%s", http_errno_description(HTTP_PARSER_ERRNO(&parser)));
    }
    return 0;
}
TEST(RequestTest, test_http_parser_post) {
    http_parser_settings settings;
    settings.on_message_begin = NULL;
    settings.on_url = request_url_cb;
    settings.on_status = on_status;
    settings.on_header_field = ss_on_header_field;
    settings.on_header_value = ss_on_header_value;
    settings.on_headers_complete = ss_on_headers_complete;
    settings.on_body = ss_on_body;
    settings.on_message_complete = on_message_complete;
    settings.on_chunk_header = NULL;
    settings.on_chunk_complete = NULL;

    http_parser parser;
    http_parser_init(&parser, HTTP_REQUEST);
    Request req;
    parser.data = &req;
    int nparsed = http_parser_execute(&parser, &settings, 
            TEST_POST_REQ_LOW_LEN.c_str(), TEST_POST_REQ_LOW_LEN.size());
    LOG_INFO("parsed size:%d, parser->upgrade:%d,total_size:%u", 
            nparsed, parser.upgrade, TEST_POST_REQ_LOW_LEN.size());
    if (parser.http_errno) {
        LOG_INFO("ERROR:%s", http_errno_description(HTTP_PARSER_ERRNO(&parser)));
    }
    ASSERT_EQ(0, (int)parser.http_errno);
}
Exemple #3
0
void read_response(struct Client *c)
{
	int nparsed;
	int status = recv(c->fd, c->buf, RECV_BUFFER, 0);

	if (status < 0 && errno != EAGAIN && errno != EWOULDBLOCK ) {
		// TODO: Leave this on until we work on the possible errors
		// from recv. In the future we should handle them.
		err(EXIT_FAILURE, "Message recv error (client: %d)\n", c->fd);
	} else {
		if (status == 0) {
			printf("Client %d closed the connection.\n", c->fd);
			c->cstate = DISCONNECTED;
			c->to_reply = 1;
		}

		nparsed = http_parser_execute(c->parser, c->parser_settings, c->buf, status);

		if (nparsed != status) {
			c->pstate = ERROR;
			c->to_reply = 1;
			printf("Parse error: %s\n", http_errno_description(HTTP_PARSER_ERRNO(c->parser)));
		}
	}
}
Exemple #4
0
std::ostream& operator<<(std::ostream& os, const http_parser& parser) {
    os << "{type=" << http_parser_type_name((http_parser_type)parser.type)
       << " flags=`";
    DescribeHttpParserFlags(os, parser.flags);
    os << "' state=" << http_parser_state_name(parser.state)
       << " header_state=" << http_parser_header_state_name(
           parser.header_state)
       << " http_errno=`" << http_errno_description(
           (http_errno)parser.http_errno)
       << "' index=" << parser.index
       << " nread=" << parser.nread
       << " content_length=" << parser.content_length
       << " http_major=" << parser.http_major
       << " http_minor=" << parser.http_minor;
    if (parser.type == HTTP_RESPONSE || parser.type == HTTP_BOTH) {
        os << " status_code=" << parser.status_code;
    }
    if (parser.type == HTTP_REQUEST || parser.type == HTTP_BOTH) {
        os << " method=" << HttpMethod2Str((HttpMethod)parser.method);
    }
    os << " upgrade=" << parser.upgrade
       << " data=" << parser.data
       << '}';
    return os;
}
Exemple #5
0
HTTPScode
https_recv(struct https_request *req, int *code, const char **body, int *len,
        int msecs)
{
        int n, err;
        
        if (BIO_reset(req->body) != 1) {
                ctx->errstr = _SSL_strerror();
                return (HTTPS_ERR_LIB);
        }
        /* Read loop sentinel set by parser in __on_message_done() */
        while (!req->done) {
                while ((n = BIO_read(req->cbio, ctx->parse_buf,
                            sizeof(ctx->parse_buf))) <= 0) {
                        if ((n = _BIO_wait(req->cbio, msecs)) != 1) {
                                ctx->errstr = n ? _SSL_strerror() :
                                    "Connection closed";
                                return (HTTPS_ERR_SERVER);
                        }
                }
                if ((err = http_parser_execute(req->parser,
                            &ctx->parse_settings, ctx->parse_buf, n)) != n) {
                        ctx->errstr = http_errno_description(err);
                        return (HTTPS_ERR_SERVER);
                }
        }
        *len = BIO_get_mem_data(req->body, (char **)body);
        *code = req->parser->status_code;
        
        return (HTTPS_OK);
}
Exemple #6
0
int Request::parse_request(const char *read_buffer, int read_size) {
    _total_req_size += read_size;
    if (_total_req_size > MAX_REQ_SIZE) {
        LOG_INFO("TOO BIG REQUEST WE WILL REFUSE IT!");
        return -1;
    }
    LOG_DEBUG("read from client: size:%d, content:%s", read_size, read_buffer);
    ssize_t nparsed = http_parser_execute(&_parser, &_settings, read_buffer, read_size);
    if (nparsed != read_size) {
        std::string err_msg = "unkonw";
        if (_parser.http_errno) {
            err_msg = http_errno_description(HTTP_PARSER_ERRNO(&_parser));
        }
        LOG_ERROR("parse request error! msg:%s", err_msg.c_str());
        return -1;
    }

    if (_parse_err) {
        return _parse_err;
    }
    if (_parse_part != PARSE_REQ_OVER) {
        return NEED_MORE_STATUS;
    }
    return 0;
}
static int lhp_error(lua_State* L) {
    lhttp_parser* lparser = check_parser(L, 1);
    enum http_errno http_errno = lparser->parser.http_errno;
    lua_pushnumber(L, http_errno);
    lua_pushstring(L, http_errno_name(http_errno));
    lua_pushstring(L, http_errno_description(http_errno));
    return 3;
}
Exemple #8
0
static int do_sync_http_req(struct http_client_ctx *ctx,
			    enum http_method method,
			    const char *url,
			    const char *content_type,
			    const char *payload)
{
	struct http_client_request req = {};
	int ret;

	req.method = method;
	req.url = url;
	req.protocol = " " HTTP_PROTOCOL HTTP_CRLF;

	ret = http_client_send_req(ctx, &req, NULL, result, sizeof(result),
				   NULL, APP_REQ_TIMEOUT);
	if (ret < 0) {
		NET_ERR("Cannot send %s request (%d)", http_method_str(method),
			ret);
		goto out;
	}

	if (ctx->rsp.data_len > sizeof(result)) {
		NET_ERR("Result buffer overflow by %zd bytes",
		       ctx->rsp.data_len - sizeof(result));

		ret = -E2BIG;
	} else {
		NET_INFO("HTTP server response status: %s",
			 ctx->rsp.http_status);

		if (ctx->parser.http_errno) {
			if (method == HTTP_OPTIONS) {
				/* Ignore error if OPTIONS is not found */
				goto out;
			}

			NET_INFO("HTTP parser status: %s",
			       http_errno_description(ctx->parser.http_errno));
			ret = -EINVAL;
			goto out;
		}

		if (method != HTTP_HEAD) {
			if (ctx->rsp.body_found) {
				NET_INFO("HTTP body: %zd bytes, "
					 "expected: %zd bytes",
					 ctx->rsp.processed,
					 ctx->rsp.content_length);
			} else {
				NET_ERR("Error detected during HTTP msg "
					"processing");
			}
		}
	}

out:
	return ret;
}
static void* set_parser_exception(http_parser* parser)
{
    PyObject* args = Py_BuildValue("(s,B)",
        http_errno_description(parser->http_errno),
        parser->http_errno);
    if (args == NULL) return PyErr_NoMemory();
    PyErr_SetObject(PyExc_HTTPParseError, args);
    Py_DECREF(args);
    return NULL;
}
Exemple #10
0
static int lhttp_parser_finish (lua_State *L) {
  http_parser* parser = (http_parser *)luaL_checkudata(L, 1, "lhttp_parser");

  int rv = http_parser_execute(parser, &lhttp_parser_settings, NULL, 0);

  if (rv != 0) {
    return luaL_error(L, http_errno_description(HTTP_PARSER_ERRNO(parser)));
  }

  return 0;
}
Exemple #11
0
void testParser(const char* buf, enum http_parser_type type){
    parser = (struct http_parser*)malloc(sizeof(http_parser));
    http_parser_init(parser, type);

    enum http_errno err;
    size_t nparsed = http_parser_execute(parser, &settings, buf, strlen(buf));
    err = HTTP_PARSER_ERRNO(parser);
    printf("nparsed %d, total %d, err %d\n", nparsed, strlen(buf), err);
    printf("*** %s ***\n\n\n\n", http_errno_description(err));
 
    free(parser);
    parser = NULL;
}
Exemple #12
0
TEST(RequestTest, test_http_parser_stream) {
    set_log_level("WARN");

    http_parser_settings settings;
    settings.on_message_begin = on_message_begin;
    settings.on_url = request_url_cb;
    settings.on_status = on_status;
    settings.on_header_field = header_field_cb;
    settings.on_header_value = header_value_cb;
    settings.on_headers_complete = on_headers_complete;
    settings.on_body = on_body;
    settings.on_message_complete = on_message_complete;
    settings.on_chunk_header = NULL;
    settings.on_chunk_complete = NULL;

    http_parser parser;
    http_parser_init(&parser, HTTP_REQUEST);
    Request req;
    parser.data = &req;

    size_t nparsed = http_parser_execute(&parser, &settings, TEST_POST_REQ1.c_str(), TEST_POST_REQ1.size());
    LOG_INFO("parsed size:%d, parser->upgrade:%d,total_size:%u", nparsed, parser.upgrade, TEST_POST_REQ1.size());
    ASSERT_EQ(TEST_POST_REQ1.size(), nparsed);
    if (parser.http_errno) {
        LOG_INFO("ERROR:%s", http_errno_description(HTTP_PARSER_ERRNO(&parser)));
    }
    ASSERT_EQ((unsigned int)0, parser.http_errno);

    nparsed = http_parser_execute(&parser, &settings, TEST_POST_REQ2.c_str(), TEST_POST_REQ2.size());
    LOG_INFO("parsed size:%d, parser->upgrade:%d,total_size:%u", nparsed, parser.upgrade, TEST_POST_REQ2.size());
    ASSERT_EQ(TEST_POST_REQ2.size(), nparsed);
    if (parser.http_errno) {
        LOG_INFO("ERROR:%s", http_errno_description(HTTP_PARSER_ERRNO(&parser)));
    }
    ASSERT_EQ((unsigned int)0, parser.http_errno);
}
Exemple #13
0
void testParser1(const char* buf[], int len, enum http_parser_type type){
    parser = (struct http_parser*)malloc(sizeof(http_parser));
    http_parser_init(parser, type);
    
    enum http_errno err;
    for (int i = 0; i < len; i++){
        size_t nparsed = http_parser_execute(parser, &settings, buf[i], strlen(buf[i]));
        err = HTTP_PARSER_ERRNO(parser);
        printf("i %d;total %d, nparsed %d, total %d, err %d\n", i,len, nparsed, strlen(buf[i]), err);
        printf("*** %s ***\n\n", http_errno_description(err));
    }
    printf("\n\n");
    free(parser);
    parser = NULL;
}
VALUE rb_parser_parse(VALUE self, VALUE data) {
    http_parser *parser = rb_http_parser_handle(self);
    http_parser_settings settings = {
        .on_url              = (http_data_cb)rb_parser_on_url,
        .on_status_complete  = (http_cb)rb_parser_on_status_complete,
        .on_header_field     = (http_data_cb)rb_parser_on_header_field,
        .on_header_value     = (http_data_cb)rb_parser_on_header_value,
        .on_headers_complete = (http_cb)rb_parser_on_headers_complete,
        .on_body             = (http_data_cb)rb_parser_on_body,
        .on_message_begin    = (http_cb)rb_parser_on_message_begin,
        .on_message_complete = (http_cb)rb_parser_on_message_complete
    };

    size_t parsed = http_parser_execute(parser, &settings, RSTRING_PTR(data), RSTRING_LEN(data));
    if (parsed != (size_t)RSTRING_LEN(data))
        rb_raise(eParserError, "Error Parsing data: %s", http_errno_description(HTTP_PARSER_ERRNO(parser)));
    return Qtrue;
}
Exemple #15
0
static
int parser_parse_request(struct http_server_ctx *ctx, struct net_buf *rx)
{
	int rc;

	ctx->field_values_ctr = 0;
	rc = http_parser_execute(&ctx->parser, &ctx->parser_settings,
				 rx->data, rx->len);
	if (rc < 0) {
		printf("[%s:%d] http_parser_execute: %s\n\t%s\n",
		       __func__, __LINE__,
		       http_errno_name(ctx->parser.http_errno),
		       http_errno_description(ctx->parser.http_errno));

		rc = -EINVAL;
		goto exit_routine;
	}

exit_routine:
	return rc;
}
Exemple #16
0
int processhttp(char* data, int http_length)
{
	if(!start)
		start = time(NULL);
	printf("t=%d\n",t++);
	_init_c_info();
	http_parser_settings settings;
	size_t nparsed;
	memset(&settings, 0, sizeof(settings));
	settings.on_url = on_url;
	settings.on_header_field = on_header_field;
	settings.on_header_value = on_header_value;
	settings.on_body = on_body;

	http_parser parser;
	http_parser_init(&parser, HTTP_REQUEST);
	nparsed = http_parser_execute(&parser, &settings, data, (size_t)http_length);
	http.method = parser.method;

		end = time(NULL);
		printf("%fms\n", difftime(end, start)/t);

	//test
	_print_c_info();

	if (nparsed != (size_t)http_length) 
	{
	    printf( "Error: %s (%s)\n",
	            http_errno_description(HTTP_PARSER_ERRNO(&parser)),
	            http_errno_name(HTTP_PARSER_ERRNO(&parser)));
	}
	if(content_length !=  con_len && http.method == 3 && http_length < 4096)
	{
		memcpy(http.content, data, http_length);
		return FALSE;
	}

	return TRUE;
}
Exemple #17
0
HTTPScode
https_recv(struct https_request *req, int *code, const char **body, int *len, int msecs_timeout)
{
        BUF_MEM *bm;
        int n, err;

        if (BIO_reset(req->body) != 1) {
                ctx->errstr = _SSL_strerror();
                return (HTTPS_ERR_LIB);
        }
        /* Read loop sentinel set by parser in __on_message_done() */
        while (!req->done) {
                while ((n = BIO_read(req->cbio, ctx->parse_buf,
                            sizeof(ctx->parse_buf))) <= 0) {
                        if ((n = _BIO_wait(req->cbio, msecs_timeout)) != 1) {
                                ctx->errstr = n ? _SSL_strerror() :
                                    "Connection closed";
                                return (HTTPS_ERR_SERVER);
                        }
                }
                if ((err = http_parser_execute(req->parser,
                            &ctx->parse_settings, ctx->parse_buf, n)) != n) {
                        ctx->errstr = http_errno_description(err);
                        return (HTTPS_ERR_SERVER);
                }
        }
        /* XXX - NUL-terminate body for string parsing */
        BIO_write(req->body, "\0", 1);
        BIO_get_mem_ptr(req->body, &bm);
        
        *code = req->parser->status_code;
        *body = bm->data;
        *len = bm->length - 1;
        
        return (HTTPS_OK);
}
Exemple #18
0
static void on_read(uv_stream_t* stream,
                       ssize_t nread,
                       uv_buf_t buf)
{
    printf("on_read: <<%.*s\n>>", (int) nread, buf.base);

    if (nread < 0) {
        if (buf.base)
            free(buf.base);

        printf("uv_shutdown\n");
        uv_shutdown_t* req = (uv_shutdown_t*) malloc(sizeof *req);
        uv_shutdown(req, stream, after_shutdown);

        return;
    }

    if (nread == 0) {
        /* Everything OK, but nothing read. */
        free(buf.base);
        return;
    }

    if (stream->data == NULL)
        internal_error("stream->data is null in on_read");

    Connection* connection = (Connection*) stream->data;
    if (connection->server != NULL && connection->server->serverType == WEBSOCK) {

        http_parser* parser = &connection->parser;

        printf("parsing as http\n");

        int parsed = http_parser_execute(parser,
            &connection->server->parser_settings,
            buf.base,
            nread);

        if (parser->upgrade) {
            connection->state = WEBSOCK_DUPLEX_STATE;
            return;
        }

        if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { 

            printf("http parse error: [%s] %s\n",
                http_errno_name(HTTP_PARSER_ERRNO(parser)),
                http_errno_description(HTTP_PARSER_ERRNO(parser))
            );
            // handle parse error 
            return; 
        } 

        if (parsed < nread) {
            printf("TODO: Handle second message?\n");
        }

    } else {

        circa_string_append_len(&connection->incomingStr, buf.base, nread);
        try_parse(&connection->incomingStr, &connection->incomingMsgs);
    }

    free(buf.base);
}
Exemple #19
0
const char *
http_request_get_error_description(http_request_t *request)
{
	assert(request);
	return http_errno_description(HTTP_PARSER_ERRNO(&request->parser));
}
const char *hm_parser_error_description(HMParser *hm_parser) {
	return http_errno_description(hm_parser->parser.http_errno);
}
Exemple #21
0
void *hpcd_server_handle_connection ( void *arg )
{
    char buffer[80 * 1024];
    int n,
        newsockfd = * ( ( int * ) arg );
    free ( arg );


    /** Set time limit on execution of thread **/

    clock_t begin, end;
    double time_spent = 0;

    begin = clock();


    http_parser_settings settings;
    hpcd_server_http_request *request_container = (hpcd_server_http_request *) malloc ( sizeof ( hpcd_server_http_request ) );
    request_container->complete = 0;


    memset ( &settings, 0, sizeof ( settings ) );
    settings.on_url = hpcd_server_handle_on_url;
    settings.on_message_complete = hpcd_server_handle_on_message_complete;
    settings.on_headers_complete = hpcd_server_handle_on_headers_complete;
    settings.on_header_field = hpcd_server_handle_on_header_field;
    settings.on_header_value = hpcd_server_handle_on_header_value;

    /* Clear the buffer */
    bzero ( buffer, 80 * 1024 );

    http_parser *parser = malloc ( sizeof ( http_parser ) );
    http_parser_init ( parser, HTTP_REQUEST );
    request_container->sock_fd = &newsockfd;
    parser->data = request_container;

    while(!request_container->complete) {

        /* Reading from buffer */
        //printf ( "Reading from buffer: %d\n ", request_container->complete );
        n = recv ( newsockfd, buffer, 80 * 1024, 0 );

        if ( n < 0 )
        {
            printf ( "ERROR reading from socket %d", n );
            exit ( 1 );
        }

        //printf("captured n %d\n", n);

        size_t nparsed = http_parser_execute ( parser, &settings, buffer, n );

        if ( nparsed != ( size_t ) n )
        {
            fprintf ( stderr,
                      "Error: %s (%s)\n",
                      http_errno_description ( HTTP_PARSER_ERRNO ( parser ) ),
                      http_errno_name ( HTTP_PARSER_ERRNO ( parser ) ) );
        }

        bzero ( buffer, n );


        /** Thread execution time **/

        end = clock();
        if (((double)(end - begin) / CLOCKS_PER_SEC) > 60) {
            printf("Request timed out\n");
            close(*request_container->sock_fd);
            break;
        }
    }

    printf("Loop Closed\n");

    return NULL;
}
VALUE rb_parser_error(VALUE self) {
    http_parser *parser = rb_http_parser_handle(self);
    int errno = HTTP_PARSER_ERRNO(parser);
    return errno != HPE_OK ? rb_str_new2(http_errno_description(errno)) : Qnil;
}
const char *http_tokenizer_error_description(http_tokenizer* tokenizer) {
	return http_errno_description(tokenizer->parser.http_errno);
}
Exemple #24
0
int main(int argc, char* argv[]) {
  enum http_parser_type file_type;

  if (argc != 3) {
    usage(argv[0]);
  }

  char* type = argv[1];
  if (type[0] != '-') {
    usage(argv[0]);
  }

  switch (type[1]) {
    /* in the case of "-", type[1] will be NUL */
    case 'r':
      file_type = HTTP_RESPONSE;
      break;
    case 'q':
      file_type = HTTP_REQUEST;
      break;
    case 'b':
      file_type = HTTP_BOTH;
      break;
    default:
      usage(argv[0]);
  }

  char* filename = argv[2];
  FILE* file = fopen(filename, "r");
  if (file == NULL) {
    perror("fopen");
    goto fail;
  }

  fseek(file, 0, SEEK_END);
  long file_length = ftell(file);
  if (file_length == -1) {
    perror("ftell");
    goto fail;
  }
  fseek(file, 0, SEEK_SET);

  char* data = malloc(file_length);
  if (fread(data, 1, file_length, file) != (size_t)file_length) {
    fprintf(stderr, "couldn't read entire file\n");
    free(data);
    goto fail;
  }

  http_parser_settings settings;
  memset(&settings, 0, sizeof(settings));
  settings.on_message_begin = on_message_begin;
  settings.on_url = on_url;
  settings.on_header_field = on_header_field;
  settings.on_header_value = on_header_value;
  settings.on_headers_complete = on_headers_complete;
  settings.on_body = on_body;
  settings.on_message_complete = on_message_complete;

  http_parser parser;
  http_parser_init(&parser, file_type);
  size_t nparsed = http_parser_execute(&parser, &settings, data, file_length);
  free(data);

  if (nparsed != (size_t)file_length) {
    fprintf(stderr,
            "Error: %s (%s)\n",
            http_errno_description(HTTP_PARSER_ERRNO(&parser)),
            http_errno_name(HTTP_PARSER_ERRNO(&parser)));
    goto fail;
  }

  return EXIT_SUCCESS;

fail:
  fclose(file);
  return EXIT_FAILURE;
}
Exemple #25
0
   INT32 restAdaptor::recvRequestHeader( pmdRestSession *pSession )
   {
      INT32 rc = SDB_OK ;
      PD_TRACE_ENTRY( SDB__RESTADP_RECVREQHE ) ;
      SDB_ASSERT ( pSession, "pSession is NULL" ) ;
      httpConnection *pHttpCon = pSession->getRestConn() ;
      CHAR *pBuffer = pSession->getFixBuff() ;
      INT32 bufSize = pSession->getFixBuffSize() ;
      http_parser *pParser = &(pHttpCon->_httpParser) ;
      CHAR *pUrl = NULL ;
      INT32 curRecvSize  = 0 ;
      INT32 receivedSize = 0 ;
      INT32 bodyOffset = 0 ;
      INT32 urlSize = 0 ;
      INT32 tempSize = 0 ;
      UINT32 recvSize = 0 ;

      _paraInit( pHttpCon ) ;

      _maxHttpHeaderSize = _maxHttpHeaderSize > bufSize ?
            bufSize : _maxHttpHeaderSize ;
      pHttpCon->_pHeaderBuf = pBuffer ;

      while( true )
      {
         recvSize = _maxHttpHeaderSize - receivedSize - 1 ;
         rc = pSession->recvData( pBuffer + receivedSize,
                                  recvSize,
                                  _timeout,
                                  FALSE,
                                  &curRecvSize,
                                  0 ) ;
         if ( rc )
         {
            PD_LOG ( PDERROR, "Failed to recv, rc=%d", rc ) ;
            goto error ;
         }

         pBuffer[ receivedSize + curRecvSize + 1 ] = '\0' ;

         if ( _checkEndOfHeader( pHttpCon, pBuffer + receivedSize,
                                 curRecvSize, bodyOffset ) )
         {
            if ( bodyOffset > 0 )
            {
               pHttpCon->_partSize  = curRecvSize - bodyOffset ;
               pHttpCon->_pPartBody = pBuffer + receivedSize + bodyOffset ;
               receivedSize += bodyOffset ;
            }
            else
            {
               receivedSize += curRecvSize ;
            }
            pHttpCon->_headerSize = receivedSize ;
            break ;
         }
         else
         {
            receivedSize += curRecvSize ;
            if ( receivedSize >= _maxHttpHeaderSize )
            {
               rc = SDB_REST_RECV_SIZE ;
               PD_LOG ( PDERROR, "http header size %d greater than %d",
                        receivedSize,
                        _maxHttpHeaderSize ) ;
               goto error ;
            }
         }
      }

      http_parser_init( pParser, HTTP_BOTH ) ;
      if( http_parser_execute( pParser, (http_parser_settings *)_pSettings,
                               pBuffer, (UINT32)receivedSize )
                != (UINT32)receivedSize )
      {
         if ( HTTP_PARSER_ERRNO( pParser ) != 28 )
         {
            rc = SDB_REST_EHS ;
            PD_LOG ( PDERROR, "Failed to parse http, %s, rc=%d",
                     http_errno_description( HTTP_PARSER_ERRNO( pParser ) ),
                     rc ) ;
            goto error ;
         }
      }

      if( pHttpCon->_pQuery != NULL )
      {
         urlSize = urlDecodeSize( pHttpCon->_pQuery, pHttpCon->_querySize ) ;
         rc = pSession->allocBuff( urlSize + 1, &pUrl, tempSize ) ;
         if ( rc )
         {
            PD_LOG ( PDERROR, "Unable to allocate %d bytes memory, rc=%d",
                     urlSize + 1, rc ) ;
            goto error ;
         }
         urlDecode( pHttpCon->_pQuery, pHttpCon->_querySize,
                    &pUrl, urlSize ) ;
         pUrl[ urlSize ] = 0 ;
         _parse_http_query( pHttpCon, pUrl, urlSize ) ;
      }
   done:
      PD_TRACE_EXITRC( SDB__RESTADP_RECVREQHE, rc ) ;
      return rc ;
   error:
      goto done ;
   }
Exemple #26
0
void response(struct http_client_ctx *ctx,
	      u8_t *data, size_t buflen,
	      size_t datalen,
	      enum http_final_call data_end,
	      void *user_data)
{
	struct waiter *waiter = user_data;
	int ret;

	if (data_end == HTTP_DATA_MORE) {
		NET_INFO("Received %zd bytes piece of data", datalen);

		/* Do something with the data here. For this example
		 * we just ignore the received data.
		 */
		waiter->total_len += datalen;

		if (ctx->rsp.body_start) {
			/* This fragment contains the start of the body
			 * Note that the header length is not proper if
			 * the header is spanning over multiple recv
			 * fragments.
			 */
			waiter->header_len = ctx->rsp.body_start -
				ctx->rsp.response_buf;
		}

		return;
	}

	waiter->total_len += datalen;

	NET_INFO("HTTP server response status: %s", ctx->rsp.http_status);

	if (ctx->parser.http_errno) {
		if (ctx->req.method == HTTP_OPTIONS) {
			/* Ignore error if OPTIONS is not found */
			goto out;
		}

		NET_INFO("HTTP parser status: %s",
			 http_errno_description(ctx->parser.http_errno));
		ret = -EINVAL;
		goto out;
	}

	if (ctx->req.method != HTTP_HEAD && ctx->req.method != HTTP_OPTIONS) {
		if (ctx->rsp.body_found) {
			NET_INFO("HTTP body: %zd bytes, expected: %zd bytes",
				 ctx->rsp.processed, ctx->rsp.content_length);
		} else {
			NET_ERR("Error detected during HTTP msg processing");
		}

		if (waiter->total_len !=
		    waiter->header_len + ctx->rsp.content_length) {
			NET_ERR("Error while receiving data, "
				"received %zd expected %zd bytes",
				waiter->total_len, waiter->header_len +
				ctx->rsp.content_length);
		}
	}

out:
	k_sem_give(&waiter->wait);
}
Exemple #27
0
static int http_stream_read(
	git_smart_subtransport_stream *stream,
	char *buffer,
	size_t buf_size,
	size_t *bytes_read)
{
	http_stream *s = (http_stream *)stream;
	http_subtransport *t = OWNING_SUBTRANSPORT(s);
	parser_context ctx;
	size_t bytes_parsed;

replay:
	*bytes_read = 0;

	assert(t->connected);

	if (!s->sent_request) {
		git_buf request = GIT_BUF_INIT;

		clear_parser_state(t);

		if (gen_request(&request, s, 0) < 0) {
			giterr_set(GITERR_NET, "Failed to generate request");
			return -1;
		}

		if (gitno_send(&t->socket, request.ptr, request.size, 0) < 0) {
			git_buf_free(&request);
			return -1;
		}

		git_buf_free(&request);

		s->sent_request = 1;
	}

	if (!s->received_response) {
		if (s->chunked) {
			assert(s->verb == post_verb);

			/* Flush, if necessary */
			if (s->chunk_buffer_len > 0 &&
				write_chunk(&t->socket, s->chunk_buffer, s->chunk_buffer_len) < 0)
				return -1;

			s->chunk_buffer_len = 0;

			/* Write the final chunk. */
			if (gitno_send(&t->socket, "0\r\n\r\n", 5, 0) < 0)
				return -1;
		}

		s->received_response = 1;
	}

	while (!*bytes_read && !t->parse_finished) {
		t->parse_buffer.offset = 0;

		if (gitno_recv(&t->parse_buffer) < 0)
			return -1;

		/* This call to http_parser_execute will result in invocations of the
		 * on_* family of callbacks. The most interesting of these is
		 * on_body_fill_buffer, which is called when data is ready to be copied
		 * into the target buffer. We need to marshal the buffer, buf_size, and
		 * bytes_read parameters to this callback. */
		ctx.t = t;
		ctx.s = s;
		ctx.buffer = buffer;
		ctx.buf_size = buf_size;
		ctx.bytes_read = bytes_read;

		/* Set the context, call the parser, then unset the context. */
		t->parser.data = &ctx;

		bytes_parsed = http_parser_execute(&t->parser,
			&t->settings,
			t->parse_buffer.data,
			t->parse_buffer.offset);

		t->parser.data = NULL;

		/* If there was a handled authentication failure, then parse_error
		 * will have signaled us that we should replay the request. */
		if (PARSE_ERROR_REPLAY == t->parse_error) {
			s->sent_request = 0;

			if (http_connect(t) < 0)
				return -1;

			goto replay;
		}

		if (t->parse_error < 0)
			return -1;

		if (bytes_parsed != t->parse_buffer.offset) {
			giterr_set(GITERR_NET,
				"HTTP parser error: %s",
				http_errno_description((enum http_errno)t->parser.http_errno));
			return -1;
		}
	}

	return 0;
}
Exemple #28
0
QByteArray Pillow::HttpResponseParser::errorString() const
{
	const char* desc = http_errno_description(HTTP_PARSER_ERRNO(&parser));
	return QByteArray::fromRawData(desc, qstrlen(desc));
}
Exemple #29
0
static int lhttp_parser_getErrorString (lua_State *L) {
  http_parser* parser = (http_parser *)luaL_checkudata(L, 1, "lhttp_parser");
  lua_pushstring(L, http_errno_description(HTTP_PARSER_ERRNO(parser)));
  return 1;
}