示例#1
0
/* Callback used for the /dump URI, and for every non-GET request:
 * dumps all information to stdout and gives back a trivial 200 ok */
static void
fetch_request_cb(struct evhttp_request *req, void *arg)
{
  struct evkeyvalq    args;
	const char *uri = evhttp_request_get_uri(req);
  evhttp_parse_query(uri, &args);
  char* url = (char *)evhttp_find_header(&args, "url");
  
	struct evbuffer *evb = NULL;
  if (url && strlen(url) > 0) {
    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if (curl) {
	    evb = evbuffer_new();
      curl_easy_setopt(curl, CURLOPT_URL, url);
      curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, evb);
      res = curl_easy_perform(curl);
      curl_easy_cleanup(curl);
      // this should probably use the curlcode status
      evhttp_send_reply(req, 200, "OK", evb);
      evbuffer_free(evb);
    }
  } else {
    evhttp_send_reply(req, 500, "MEH", NULL);
  }
}
示例#2
0
/*
 * Get request URI
 * @return [String] uri string
 */
static VALUE t_get_uri(VALUE self) {
    Libevent_HttpRequest *http_request;

    Data_Get_Struct(self, Libevent_HttpRequest, http_request);

    return rb_str_new2(evhttp_request_get_uri(http_request->ev_request));
}
/**
 *
 * @param *request the opaque data structure containing the request infos
 * @param *privParams global parameters set when the callback was associated
 * @return nothing
 */
void testing (struct evhttp_request *request, void *privParams) {
	struct evbuffer *buffer;
	struct evkeyvalq headers;
	const char *q;
	// Parse the query for later lookups
	evhttp_parse_query (evhttp_request_get_uri (request), &headers);

	// lookup the 'q' GET parameter 
	q = evhttp_find_header (&headers, "q");

	// Create an answer buffer where the data to send back to the browser will be appened
	buffer = evbuffer_new ();
	evbuffer_add (buffer, "coucou !", 8);
	evbuffer_add_printf (buffer, "%s", q);

	// Add a HTTP header, an application/json for the content type here
	evhttp_add_header (evhttp_request_get_output_headers (request),
			"Content-Type", "text/plain");

	// Tell we're done and data should be sent back
	evhttp_send_reply(request, HTTP_OK, "OK", buffer);

	// Free up stuff
	evhttp_clear_headers (&headers);

	evbuffer_free (buffer);

	return;
}
示例#4
0
static void http_request_cb(struct evhttp_request *req, void *arg)
{
    struct context *ctx = (struct context *) arg;
    const char *uri = evhttp_request_get_uri(req);
    struct evbuffer *evb = NULL;
    const char *type;

    if (evhttp_request_get_command(req) != EVHTTP_REQ_GET)
    {
        evhttp_send_error(req, HTTP_BADREQUEST, 0);
        return;
    }

    printf("GET: %s",  uri);

    if (strcmp(uri,"/") == 0)
    {
        type = "text/html";
        evb = evbuffer_new();
        evbuffer_add_printf(evb, "<html><body><h1>Hello World!</h1></body></html>");
        evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", type);
        evhttp_send_reply(req, 200, "OK", evb);
        printf(" - 200 - ok\n");
    }
    else if (strcmp(uri,"/sample") == 0)
    {
        evb = evbuffer_new();
        if (get_sample(ctx) == 0)
        {
            if (format_sample_response(ctx, evb) == 0)
            {
                evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "application/json");
                evhttp_send_reply(req, 200, "OK", evb);
                printf(" - 200 - ok\n");
            }
            else
            {
                internal_error(req, evb);
            }
        }
        else
        {
            internal_error(req, evb);
        }
    }
    else
    {
        type = "text/plain";
        evb = evbuffer_new();
        evbuffer_add_printf(evb, "Not Found");
        evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", type);
        evhttp_send_reply(req, 404, "Not Found", evb);
        printf(" - 404 - not found\n");
    }

    if (evb)
        evbuffer_free(evb);
}
示例#5
0
static void on_srv_gen_request (struct evhttp_request *req, void *ctx)
{
	const char *uri = evhttp_request_get_uri(req);
    
    if (!strstr (uri, "/storage/")) {
        LOG_debug (HTTP_TEST, "%s", uri);
        g_assert_not_reached ();
    }
}
示例#6
0
/* Thread: httpd */
static void
httpd_gen_cb(struct evhttp_request *req, void *arg)
{
  const char *req_uri;
  char *uri;
  char *ptr;

  req_uri = evhttp_request_get_uri(req);
  if (!req_uri)
    {
      redirect_to_index(req, "/");

      return;
    }

  uri = strdup(req_uri);
  ptr = strchr(uri, '?');
  if (ptr)
    {
      DPRINTF(E_SPAM, L_HTTPD, "Found query string\n");

      *ptr = '\0';
    }

  ptr = uri;
  uri = evhttp_decode_uri(uri);
  free(ptr);

  /* Dispatch protocol-specific URIs */
  if (rsp_is_request(req, uri))
    {
      rsp_request(req);

      goto out;
    }
  else if (daap_is_request(req, uri))
    {
      daap_request(req);

      goto out;
    }
  else if (dacp_is_request(req, uri))
    {
      dacp_request(req);

      goto out;
    }

  DPRINTF(E_DBG, L_HTTPD, "HTTP request: %s\n", uri);

  /* Serve web interface files */
  serve_file(req, uri);

 out:
  free(uri);
}
示例#7
0
文件: server.cpp 项目: ieee820/icomet
int Server::sub(struct evhttp_request *req){
	struct evkeyvalq params;
	const char *uri = evhttp_request_get_uri(req);
	evhttp_parse_query(uri, &params);

	struct bufferevent *bev = evhttp_connection_get_bufferevent(req->evcon);
	bufferevent_enable(bev, EV_READ);

	int cid = -1;
	const char *cb = NULL;
	//const char *token = NULL;
	struct evkeyval *kv;
	for(kv = params.tqh_first; kv; kv = kv->next.tqe_next){
		if(strcmp(kv->key, "id") == 0){
			cid = atoi(kv->value);
		}else if(strcmp(kv->key, "cb") == 0){
			cb = kv->value;
		}
	}
	
	if(cid < 0 || cid >= channels.size()){
		evhttp_send_reply(req, 404, "Not Found", NULL);
		return 0;
	}
	
	Channel *channel = &channels[cid];
	if(channel->sub_count >= MAX_SUBSCRIBERS_PER_CHANNEL){
		evhttp_send_reply(req, 429, "Too Many Requests", NULL);
		return 0;
	}
	
	Subscriber *sub = sub_pool.alloc();
	sub->req = req;
	sub->serv = this;
	sub->cb = cb? cb : DEFAULT_JSONP_CALLBACK;
	//sub->last_recv = ...
	channel->add_subscriber(sub);
	log_debug("channel: %d, add sub, sub_count: %d", channel->id, channel->sub_count);

	evhttp_add_header(req->output_headers, "Content-Type", "text/html; charset=utf-8");
	evhttp_send_reply_start(req, HTTP_OK, "OK");

	struct evbuffer *buf;
	buf = evbuffer_new();
	evbuffer_add_printf(buf, "%s({type: \"hello\", id: \"%d\", content: \"From icomet server.\"});\n",
		sub->cb.c_str(),
		channel->id);
	evhttp_send_reply_chunk(req, buf);
	evbuffer_free(buf);

	evhttp_connection_set_closecb(req->evcon, on_disconnect, sub);

	return 0;
}
示例#8
0
void httpsrv_process_req(struct evhttp_request* req)
{
	struct evbuffer* buf = evbuffer_new();
	if (NULL == buf)
		return;

	evbuffer_add_printf(buf, "server response by thread %u, request uri:%s\n",
			pthread_self(), evhttp_request_get_uri(req));
	evhttp_send_reply(req, HTTP_OK, "OK", buf);

	evbuffer_free(buf);
	buf = NULL;
}
示例#9
0
//simple function for the LED blick command
static void led_blink(struct evhttp_request* req, void* arg)
{
    printf("Received a request for %s\nDispatching dbb command\n", evhttp_request_get_uri(req));

    //dispatch command
    executeCommand("{\"led\" : \"toggle\"}", "0000", [](const std::string& cmdOut) {
    });

    //form a response, mind, no cmd result is available at this point, at the moment we don't block the http response thread
    struct evbuffer* out = evbuffer_new();
    evbuffer_add_printf(out, "Command dispatched\n");
    evhttp_send_reply(req, 200, "OK", out);
}
示例#10
0
static void put_playlist_remove_tracks(sp_playlist *playlist,
                                       struct evhttp_request *request,
                                       void *userdata) {
  // sp_session *session = userdata;
  const char *uri = evhttp_request_get_uri(request);
  struct evkeyvalq query_fields;
  evhttp_parse_query(uri, &query_fields);

  // Parse index
  const char *index_field = evhttp_find_header(&query_fields, "index");
  int index;

  if (index_field == NULL ||
      sscanf(index_field, "%d", &index) <= 0 ||
      index < 0) {
    send_error(request, HTTP_BADREQUEST,
               "Bad parameter: index must be numeric");
    return;
  }

  const char *count_field = evhttp_find_header(&query_fields, "count");
  int count;

  if (count_field == NULL ||
      sscanf(count_field, "%d", &count) <= 0 ||
      count < 1) {
    send_error(request, HTTP_BADREQUEST,
               "Bad parameter: count must be numeric and positive");
    return;
  }

  int *tracks = calloc(count, sizeof(int));

  for (int i = 0; i < count; i++)
    tracks[i] = index + i;

  struct playlist_handler *handler = register_playlist_callbacks(
      playlist, request, &get_playlist,
      &playlist_update_in_progress_callbacks, NULL);
  sp_error remove_tracks_error = sp_playlist_remove_tracks(playlist, tracks,
                                                           count);

  if (remove_tracks_error != SP_ERROR_OK) {
    sp_playlist_remove_callbacks(playlist, handler->playlist_callbacks, handler);
    free(handler);
    send_error_sp(request, HTTP_BADREQUEST, remove_tracks_error);
  }

  free(tracks);
}
示例#11
0
文件: http.c 项目: pearsonalan/stats
static void http_metrics_request_cb(struct evhttp_request *req, void *arg)
{
    struct http *http = (struct http *)arg;
    struct evbuffer *evb = NULL;
    const char *uri = NULL;
    struct evhttp_uri *decoded = NULL;
    const char *query;
    struct metric_history *mh;

    uri = evhttp_request_get_uri(req);

    /* Decode the URI */
    decoded = evhttp_uri_parse(uri);
    if (!decoded)
    {
        evhttp_send_error(req, HTTP_BADREQUEST, 0);
        goto exit;
    }

    query = evhttp_uri_get_query(decoded);

    printf("metrics request %s\n", query ? query : "null");

    /* This holds the content we're sending. */
    evb = evbuffer_new();

    mh = http_find_metrics_from_query(http->metrics, query);
    if (!mh)
    {
        printf("Series not found in query: %s\n", query);
        http_format_error_response(evb, "metric not found");
    }
    else
    {
        http_format_metric_response(evb,mh);
    }

    /* add headers */
    evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "application/json");

    /* send the response */
    evhttp_send_reply(req, 200, "OK", evb);

exit:
    if (decoded)
        evhttp_uri_free(decoded);

    if (evb)
        evbuffer_free(evb);
}
int HttpServerMsgHandler::processMessage(void *arg) {
	struct evhttp_request *req = (struct evhttp_request *)arg;

	const char *cmdtype;
	struct evkeyvalq *headers;
	struct evkeyval *header;

	switch (evhttp_request_get_command(req)) {
	case EVHTTP_REQ_GET: cmdtype = "GET"; break;
	case EVHTTP_REQ_POST: cmdtype = "POST"; break;
	case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
	case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
	case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
	case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
	case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
	case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
	case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
	default: cmdtype = "unknown"; break;
	}

	printf("Received a %s request for %s\nHeaders:\n",
		cmdtype, evhttp_request_get_uri(req));

	headers = evhttp_request_get_input_headers(req);
	for (header = headers->tqh_first; header;
		header = header->next.tqe_next) {
			printf("  %s: %s\n", header->key, header->value);
	}

	ConnectionManager *conn = ConnectionManager::getInstance();
	struct evbuffer *return_buffer=evbuffer_new();

	long long total_req = conn->getTotalRequests();
	long long total_res = conn->getTotalResponses();
	unsigned int conns = conn->getConnections();

	long long timeouts = conn->getTimeoutRequests();
	long long err_res = conn->getErrorResponses();
	long long conn_except = conn->getConnExceptions();
	long long ok_res = conn->getOkResponses();

	evbuffer_add_printf(return_buffer,"    total request: %lld<br>	   total response: %lld<br>	   connnections: %u<br><br><hr><br>	ok: %lld	\
		<br>	timeout: %lld<br>	http error: %lld<br>    connExcept: %u<br>"
		, total_req, total_res, conns, ok_res, timeouts, err_res, conn_except);
	evhttp_send_reply(req, HTTP_OK, "OK", return_buffer);
	evbuffer_free(return_buffer);

	return 0;
}
示例#13
0
文件: server.cpp 项目: ITSTONE/icomet
	HttpQuery(struct evhttp_request *req){
		_has_post = false;
		if(evhttp_request_get_command(req) == EVHTTP_REQ_POST){
			evbuffer *body_evb = evhttp_request_get_input_buffer(req);
			size_t len = evbuffer_get_length(body_evb);
			if(len > 0){
				_has_post = true;
				char *data = (char *)malloc(len + 1);
				evbuffer_copyout(body_evb, data, len);
				data[len] = '\0';
				evhttp_parse_query_str(data, &_post);
				free(data);
			}
		}
		evhttp_parse_query(evhttp_request_get_uri(req), &_get);
	}
示例#14
0
static void http_request_handler(struct evhttp_request *req, void *arg)
{
    int ret = -1;
    const char *uri;

    uri = evhttp_request_get_uri(req);
    if (NULL != uri)
    {
        ret = http_request_dispatch(req, uri);
    }
    if(ret)
    {
        evhttp_send_reply(req, HTTP_BADREQUEST, NULL, NULL);
    }
    return;
}
示例#15
0
文件: http.c 项目: snip/aprsc
static void http_router(struct evhttp_request *r, void *which_server)
{
	char *remote_host;
	ev_uint16_t remote_port;
	const char *uri = evhttp_request_get_uri(r);
	struct evhttp_connection *conn = evhttp_request_get_connection(r);
	evhttp_connection_get_peer(conn, &remote_host, &remote_port);
	
	hlog(LOG_DEBUG, "http %s [%s] request %s", (which_server == (void *)1) ? "status" : "upload", remote_host, uri);
	
	http_requests++;
	
	/* status server routing */
	if (which_server == (void *)1) {
		if (strncmp(uri, "/status.json", 12) == 0) {
			http_status(r);
			return;
		}
		
		if (strncmp(uri, "/counterdata?", 13) == 0) {
			http_counterdata(r, uri);
			return;
		}
		
		http_route_static(r, uri);
		return;
	}
	
	/* position upload server routing */
	if (which_server == (void *)2) {
		if (strncmp(uri, "/", 7) == 0) {
			http_upload_position(r, remote_host);
			return;
		}
		
		hlog(LOG_DEBUG, "http request on upload server for '%s': 404 not found", uri);
		evhttp_send_error(r, HTTP_NOTFOUND, "Not found");
		return;
	}
	
	hlog(LOG_ERR, "http request on unknown server for '%s': 404 not found", uri);
	evhttp_send_error(r, HTTP_NOTFOUND, "Server not found");
	
	return;
}
示例#16
0
文件: server.cpp 项目: ieee820/icomet
int Server::pub(struct evhttp_request *req){
	struct evkeyvalq params;
	const char *uri = evhttp_request_get_uri(req);
	evhttp_parse_query(uri, &params);

	int cid = -1;
	const char *content = "";
	struct evkeyval *kv;
	for(kv = params.tqh_first; kv; kv = kv->next.tqe_next){
		if(strcmp(kv->key, "id") == 0){
			cid = atoi(kv->value);
		}else if(strcmp(kv->key, "content") == 0){
			content = kv->value;
		}
	}
	
	Channel *channel = NULL;
	if(cid < 0 || cid >= MAX_CHANNELS){
		channel = NULL;
	}else{
		channel = &channels[cid];
		log_debug("channel: %d, pub, sub_count: %d", channel->id, channel->sub_count);
	}
	if(!channel || !channel->subs){
		struct evbuffer *buf = evbuffer_new();
		evbuffer_add_printf(buf, "id: %d not connected\n", channel->id);
		evhttp_send_reply(req, 404, "Not Found", buf);
		evbuffer_free(buf);
		return 0;
	}
	log_debug("pub: %d content: %s", channel->id, content);

	// push to subscribers
	channel->send("data", content);
		
	// response to publisher
	struct evbuffer *buf = evbuffer_new();
	evhttp_add_header(req->output_headers, "Content-Type", "text/html; charset=utf-8");
	evbuffer_add_printf(buf, "ok\n");
	evhttp_send_reply(req, 200, "OK", buf);
	evbuffer_free(buf);

	return 0;
}
示例#17
0
/* Callback used for the /dump URI, and for every non-GET request:
 * dumps all information to stdout and gives back a trivial 200 ok */
static void
dump_request_cb(struct evhttp_request *req, void *arg)
{
	const char *cmdtype;
	struct evkeyvalq *headers;
	struct evkeyval *header;
	struct evbuffer *buf;

	switch (evhttp_request_get_command(req)) {
	case EVHTTP_REQ_GET: cmdtype = "GET"; break;
	case EVHTTP_REQ_POST: cmdtype = "POST"; break;
	case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
	case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
	case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
	case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
	case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
	case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
	case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
	default: cmdtype = "unknown"; break;
	}

	printf("Received a %s request for %s\nHeaders:\n",
	    cmdtype, evhttp_request_get_uri(req));

	headers = evhttp_request_get_input_headers(req);
	for (header = headers->tqh_first; header;
	    header = header->next.tqe_next) {
		printf("  %s: %s\n", header->key, header->value);
	}

	buf = evhttp_request_get_input_buffer(req);
	puts("Input data: <<<");
	while (evbuffer_get_length(buf)) {
		int n;
		char cbuf[128];
		n = evbuffer_remove(buf, cbuf, sizeof(cbuf));
		if (n > 0)
			(void) fwrite(cbuf, 1, n, stdout);
	}
	puts(">>>");

	evhttp_send_reply(req, 200, "OK", NULL);
}
示例#18
0
void gen_handler(struct evhttp_request *req, void *arg)
{
    DBG();
    /*struct evbuffer *evb = evbuffer_new(); */

    const char *uri = evhttp_request_get_uri(req);
    struct evhttp_uri *decoded_uri = NULL;
    const char *path;
    char *decoded_path;

    /* Decode the URI */
    decoded_uri = evhttp_uri_parse(uri);
    if (!decoded_uri) {
        reply_error(req, HTTP_BADREQUEST, "Bad URI: %s", uri);
        return;
    }

    path = evhttp_uri_get_path(decoded_uri);
    if (!path) {
        logging(LOG_INFO, "request path is nil, replace it as /");
        path = "/";
    }

    decoded_path = evhttp_uridecode(path, 0, NULL);

    uint64_t chunkid;
    char *slash = strchr(path + 1, '/');
    *slash = '\0';
    const char *op = path + 1;
    sscanf(slash + 1, "%" SCNu64, &chunkid);

    logging(LOG_INFO, "%s, %" PRIu64, op, chunkid);

    if (strcmp(op, "put") == 0) {
        write_chunk(chunkid, req);
    } else if (strcmp(op, "get") == 0) {
        read_chunk(chunkid, req);
    } else {
        reply_error(req, HTTP_NOTFOUND, "not found: %s", uri);
        return;
    }
}
示例#19
0
static void on_srv_request (struct evhttp_request *req, void *ctx)
{
    struct evbuffer *in;
    gchar *dir = (gchar *) ctx;
    gchar *path, *decoded_path;
    const gchar *tmp;
    const char *uri = evhttp_request_get_uri(req);
    struct evhttp_uri *decoded = NULL;
    struct evbuffer *evb = NULL;
    char buf[BUFFER_SIZE];
    FILE *f;
    size_t bytes_read;
    size_t total_bytes = 0;

    in = evhttp_request_get_input_buffer (req);

    decoded = evhttp_uri_parse(uri);
    g_assert (decoded);
    tmp = evhttp_uri_get_path (decoded);
    g_assert (tmp);
    decoded_path = evhttp_uridecode(tmp, 0, NULL);

    evb = evbuffer_new();

    path = g_strdup_printf ("%s/%s", dir, decoded_path);
    LOG_debug (POOL_TEST, "SRV: received %d bytes. Req: %s, path: %s", evbuffer_get_length (in), evhttp_request_get_uri (req), path);

    f = fopen (path, "r");
    g_assert (f);

    while ((bytes_read = fread (buf, 1, BUFFER_SIZE, f)) > 0) {
        evbuffer_add (evb, buf, bytes_read);
        total_bytes += bytes_read;
    }
    evhttp_send_reply(req, 200, "OK", evb);

    LOG_debug (POOL_TEST, "Total bytes sent: %u", total_bytes);

    fclose(f);
    evbuffer_free(evb);
}
示例#20
0
文件: xBlog.cpp 项目: iomato/xblog
const char *xBlog::DebugHttpGetCommand(struct evhttp_request *req)
{
    const char *cmdtype;

    switch (evhttp_request_get_command(req))
    {
    case EVHTTP_REQ_GET:
        cmdtype = "GET";
        break;
    case EVHTTP_REQ_POST:
        cmdtype = "POST";
        break;
    case EVHTTP_REQ_HEAD:
        cmdtype = "HEAD";
        break;
    case EVHTTP_REQ_PUT:
        cmdtype = "PUT";
        break;
    case EVHTTP_REQ_DELETE:
        cmdtype = "DELETE";
        break;
    case EVHTTP_REQ_OPTIONS:
        cmdtype = "OPTIONS";
        break;
    case EVHTTP_REQ_TRACE:
        cmdtype = "TRACE";
        break;
    case EVHTTP_REQ_CONNECT:
        cmdtype = "CONNECT";
        break;
    case EVHTTP_REQ_PATCH:
        cmdtype = "PATCH";
        break;
    default:
        cmdtype = "unknown";
        break;
    }

    log_debug("Received a %s request for %s \n", cmdtype, evhttp_request_get_uri(req));
    return cmdtype;
}
示例#21
0
文件: http.c 项目: pearsonalan/stats
static void http_list_request_cb(struct evhttp_request *req, void *arg)
{
    // struct http *http = (struct http *)arg;
    struct evbuffer *evb = NULL;
    const char *uri = NULL;
    struct evhttp_uri *decoded = NULL;
    const char *query;

    uri = evhttp_request_get_uri(req);

    /* Decode the URI */
    decoded = evhttp_uri_parse(uri);
    if (!decoded)
    {
        evhttp_send_error(req, HTTP_BADREQUEST, 0);
        goto exit;
    }

    query = evhttp_uri_get_query(decoded);

    printf("list request %s\n", query ? query : "null");

    /* This holds the content we're sending. */
    evb = evbuffer_new();

    http_format_list_response(evb);

    /* add headers */
    evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "application/json");

    /* send the response */
    evhttp_send_reply(req, 200, "OK", evb);

exit:
    if (decoded)
        evhttp_uri_free(decoded);

    if (evb)
        evbuffer_free(evb);

}
示例#22
0
static void send_document_cb(struct evhttp_request *req, void *arg) {
	struct evbuffer *evb = NULL;
	const char *uri = evhttp_request_get_uri(req);
	char *whole_path = NULL;
	int fd = -1, fsize;

	printf("Got a GET request for <%s>\n",  uri);

	fsize = encode_request_to_file_path(uri, &whole_path);
	if (!fsize) {
		goto err;
	}

	evb = evbuffer_new();

	const char *type = guess_content_type(whole_path);
	if ((fd = open(whole_path, O_RDONLY)) < 0) {
		perror("open");
		goto err;
	}

	evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", type);
	evbuffer_add_file(evb, fd, 0, fsize);

	evhttp_send_reply(req, 200, "OK", evb);
	goto done;
err:
	evhttp_send_error(req, 404, "Document was not found");
	if (fd>=0) {
		close(fd);
	}
done:
	if (whole_path) {
		free(whole_path);
	}
	if (evb) {
		evbuffer_free(evb);
	}
}
示例#23
0
void httpserver_handler(struct evhttp_request *req, void *arg)  
{  
    int fd=open("./test.html",O_RDONLY);
    const char *cmdtype;   
    struct evbuffer *buf = evbuffer_new();  
    if (buf == NULL)   
    {  
        printf("evbuffer_new error !\n");  
        return;  
    }  
      
    switch (evhttp_request_get_command(req))  
    {    
        case EVHTTP_REQ_GET:    cmdtype = "GET";    break;    
        case EVHTTP_REQ_POST:   cmdtype = "POST";   break;    
        case EVHTTP_REQ_HEAD:   cmdtype = "HEAD";   break;    
        case EVHTTP_REQ_PUT:    cmdtype = "PUT";    break;    
        case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;    
        case EVHTTP_REQ_OPTIONS:cmdtype = "OPTIONS";break;    
        case EVHTTP_REQ_TRACE:  cmdtype = "TRACE";  break;    
        case EVHTTP_REQ_CONNECT:cmdtype = "CONNECT";break;    
        case EVHTTP_REQ_PATCH:  cmdtype = "PATCH";  break;    
        default: cmdtype = "unknown"; break;    
    }  
  
    printf("%s url=%s \n", cmdtype, evhttp_request_get_uri(req));  
  
    //evbuffer_add_printf(buf,"<html>\n"  
    //        "<head>\n"  
    //        "  <title>Libevnet Test</title>\n"            
    //        "</head>\n"  
    //        "<body>\n"  
    //        "  <h1>Hello world ,This is a Libenvet Test !</h1>\n"            
    //        "</body>\n"  
    //        "</html>\n");
    evbuffer_read(buf,fd,75);
    evhttp_send_reply(req, 200, "OK", buf);    
}   
示例#24
0
文件: request.cpp 项目: respu/w
    Request make_request_from_evhttp_request(evhttp_request* req) {
      Request r;

      switch (evhttp_request_get_command(req)) {
        case EVHTTP_REQ_GET:     r.method = "GET";     break;
        case EVHTTP_REQ_POST:    r.method = "POST";    break;
        case EVHTTP_REQ_HEAD:    r.method = "HEAD";    break;
        case EVHTTP_REQ_PUT:     r.method = "PUT";     break;
        case EVHTTP_REQ_DELETE:  r.method = "DELETE";  break;
        case EVHTTP_REQ_OPTIONS: r.method = "OPTIONS"; break;
        case EVHTTP_REQ_TRACE:   r.method = "TRACE";   break;
        case EVHTTP_REQ_CONNECT: r.method = "CONNECT"; break;
        case EVHTTP_REQ_PATCH:   r.method = "PATCH";   break;
      }

      evkeyvalq* headers = evhttp_request_get_input_headers(req);
      for (evkeyval* header = headers->tqh_first; header; header = header->next.tqe_next) {
        r.headers[header->key] = header->value;
      }

      evbuffer* body = evhttp_request_get_input_buffer(req);
      if (body) {
        std::stringstream body_buffer;
        while (evbuffer_get_length(body)) {
          char tmp[128];
          int n = evbuffer_remove(body, tmp, sizeof(tmp));
          if (n > 0)
            body_buffer.write(tmp, n);
        }
        r.body = body_buffer.str();
      }

      char* decoded_uri_str = evhttp_decode_uri(evhttp_request_get_uri(req));
      r.uri = URI(decoded_uri_str);
      ::free(decoded_uri_str);
      return r;
    }
static void static_list_request_cb(struct evhttp_request *req, void *arg)
{
	struct evbuffer *evb = NULL;
	struct evhttp_uri *decoded = NULL;
	const char *path;
	char *decoded_path;
	int fd = -1;
	struct stat st;
	char uri_root[512] = {0};
	struct evhttp_bound_socket *handle = (struct evhttp_bound_socket *)arg;

	size_t len;
	char *whole_path = NULL;

	const char *uri = evhttp_request_get_uri(req);
	get_uri_root(handle, uri_root, sizeof(uri_root));


	decoded = evhttp_uri_parse(uri);
	if (decoded == NULL) {
		LOG(LOG_ERROR, "%s", "evhttp_decode_uri error");
		evhttp_send_error(req, HTTP_BADREQUEST, 0);
		exit(1);
	}

	path = evhttp_uri_get_path(decoded);
	if (!path) path = "/";

	decoded_path = evhttp_uridecode(path, 0, NULL);
	if (decoded_path == NULL)
		goto err;

	if (strstr(decoded_path, ".."))
		goto err;

	len = strlen(decoded_path)+strlen(docroot)+2;
	if (!(whole_path = malloc(len))) {
		perror("malloc");
		goto err;
	}
	evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);

	if (stat(whole_path, &st)<0) {
		goto err;
	}

	evb = evbuffer_new();

	if (S_ISDIR(st.st_mode)) {
		DIR *d;
		struct dirent *ent;

		const char *trailing_slash = "";

		if (!strlen(path) || path[strlen(path)-1] != '/')
			trailing_slash = "/";

		if (!(d = opendir(whole_path)))
			goto err;

		evbuffer_add_printf(evb, "<html>\n <head>\n"
		    "  <title>%s</title>\n"
		    "  <base href='%s%s%s'>\n"
		    " </head>\n"
		    " <body>\n"
		    "  <h1>%s</h1>\n"
		    "  <ul>\n",
		    decoded_path, /* XXX html-escape this. */
		    uri_root, path, /* XXX html-escape this? */
		    trailing_slash,
		    decoded_path /* XXX html-escape this */);

		while((ent = readdir(d))) {
			const char *name = ent->d_name;
			evbuffer_add_printf(evb, "    <li><a href=\"%s\">%s</a>\n", name, name);
			evbuffer_add_printf(evb, "</ul></body></html>\n");
		}
		closedir(d);
		evhttp_add_header(evhttp_request_get_output_headers(req), "Content-type", "text/html");
	} else {
		const char *type = guess_content_type(decoded_path);
		if ((fd = open(whole_path, O_RDONLY)) < 0) {
			perror("open");
			goto err;
		}

		if (fstat(fd, &st)<0) {
					/* Make sure the length still matches, now that we
					 * opened the file :/ */
					perror("fstat");
					goto err;
		}

		evhttp_add_header(evhttp_request_get_output_headers(req),
			    "Content-Type", type);

		evbuffer_add_file(evb, fd, 0, st.st_size);
	}

	evhttp_send_reply(req, HTTP_OK, "OK", evb);
	goto done;

err:
	evhttp_send_error(req, HTTP_NOTFOUND, "Document was not found");
	if (fd>=0)
		close(fd);

done:
	if (decoded)
		evhttp_uri_free(decoded);
	if (decoded_path)
		free(decoded_path);
	if (whole_path)
		free(whole_path);
	if (evb)
		evbuffer_free(evb);
}
示例#26
0
文件: server.cpp 项目: 1yfgT53/icomet
	HttpQuery(struct evhttp_request *req){
		evhttp_parse_query(evhttp_request_get_uri(req), &params);
	}
示例#27
0
char *
httpd_fixup_uri(struct evhttp_request *req)
{
  struct evkeyvalq *headers;
  const char *ua;
  const char *uri;
  const char *u;
  const char *q;
  char *fixed;
  char *f;
  int len;

  uri = evhttp_request_get_uri(req);
  if (!uri)
    return NULL;

  /* No query string, nothing to do */
  q = strchr(uri, '?');
  if (!q)
    return strdup(uri);

  headers = evhttp_request_get_input_headers(req);
  ua = evhttp_find_header(headers, "User-Agent");
  if (!ua)
    return strdup(uri);

  if ((strncmp(ua, "iTunes", strlen("iTunes")) != 0)
      && (strncmp(ua, "Remote", strlen("Remote")) != 0)
      && (strncmp(ua, "Roku", strlen("Roku")) != 0))
    return strdup(uri);

  /* Reencode + as %2B and space as + in the query,
     which iTunes and Roku devices don't do */
  len = strlen(uri);

  u = q;
  while (*u)
    {
      if (*u == '+')
	len += 2;

      u++;
    }

  fixed = (char *)malloc(len + 1);
  if (!fixed)
    return NULL;

  strncpy(fixed, uri, q - uri);

  f = fixed + (q - uri);
  while (*q)
    {
      switch (*q)
	{
	  case '+':
	    *f = '%';
	    f++;
	    *f = '2';
	    f++;
	    *f = 'B';
	    break;

	  case ' ':
	    *f = '+';
	    break;

	  default:
	    *f = *q;
	    break;
	}

      q++;
      f++;
    }

  *f = '\0';

  return fixed;
}
static void static_dump_request_cb(struct evhttp_request *req, void *arg)
{

	const char *cmdtype;
	struct evkeyvalq *headers;
	struct evkeyval *header;
	struct evbuffer *buf;


	switch (evhttp_request_get_command(req)) {
		case EVHTTP_REQ_GET:
			cmdtype = "GET";
		break;
		case EVHTTP_REQ_POST:
			cmdtype = "POST";
		break;
		default:
			cmdtype = "unknown";
		break;
	}
	printf("Received a %s request for %s\nHeaders:\n",
	    cmdtype, evhttp_request_get_uri(req));

	headers = evhttp_request_get_input_headers(req);
	for (header = headers->tqh_first; header;
	    header = header->next.tqe_next) {
		printf("  %s: %s\n", header->key, header->value);
	}

	buf = evhttp_request_get_input_buffer(req);
	puts("Input data: <<<");
	printf("len:%d", evbuffer_get_length(buf));

	/*
	while (evbuffer_get_length(buf)) {
		int n;
		char cbuf[128];
		n = evbuffer_remove(buf, cbuf, sizeof(buf)-1);
		if (n > 0)
			(void) fwrite(cbuf, 1, n, stdout);
	}
	puts(">>>");
	*/

	//get params
	struct evkeyvalq *query_params_ptr = calloc(sizeof(struct evkeyvalq), 1);
	getParams(req, query_params_ptr);
	char *test = NULL;
	test = getParam(query_params_ptr, "test");
	if (test != NULL) {
		fprintf(stderr, "param test: %s", test);
	}
	evhttp_clear_headers(query_params_ptr);
	free(test);


	//post params
	struct evkeyvalq *post_params_ptr = calloc(sizeof(struct evkeyvalq), 1);
	postParams(req, post_params_ptr);
	char *name = NULL;
	name = postParam(post_params_ptr, "name");
	if (name != NULL) {
		fprintf(stderr, "param name: %s", name);
	}

	evhttp_clear_headers(post_params_ptr);
	free(name);

	evhttp_send_reply(req, 200, "OK", NULL);

	//evhttp_request_free(req);
}
示例#29
0
文件: http.c 项目: pearsonalan/stats
static void http_document_request_cb(struct evhttp_request *req, void *arg)
{
    struct evbuffer *evb = NULL;
    struct http *http = (struct http *) arg;
    const char *docroot = http->docroot;
    const char *uri = evhttp_request_get_uri(req);
    struct evhttp_uri *decoded = NULL;
    const char *path;
    char *decoded_path;
    char *whole_path = NULL;
    size_t len;
    int fd = -1;
    struct stat st;

    if (evhttp_request_get_command(req) != EVHTTP_REQ_GET)
    {
        evhttp_send_error(req, HTTP_BADREQUEST, 0);
        return;
    }

    printf("GET: %s\n",  uri);

    /* Decode the URI */
    decoded = evhttp_uri_parse(uri);
    if (!decoded)
    {
        evhttp_send_error(req, HTTP_BADREQUEST, 0);
        return;
    }

    /* Let's see what path the user asked for. */
    path = evhttp_uri_get_path(decoded);
    if (!path) path = "/";

    /* We need to decode it, to see what path the user really wanted. */
    decoded_path = evhttp_uridecode(path, 0, NULL);
    if (decoded_path == NULL)
        goto err;

    /* Don't allow any ".."s in the path, to avoid exposing stuff outside
     * of the docroot.  This test is both overzealous and underzealous:
     * it forbids aceptable paths like "/this/one..here", but it doesn't
     * do anything to prevent symlink following." */
    if (strstr(decoded_path, ".."))
        goto err;

    len = strlen(decoded_path) + strlen(docroot) + 2;
    if (!(whole_path = malloc(len)))
    {
        goto err;
    }

    snprintf(whole_path, len, "%s/%s", docroot, decoded_path);

    if (stat(whole_path, &st) < 0)
    {
        goto err;
    }

    /* This holds the content we're sending. */
    evb = evbuffer_new();

    if (S_ISDIR(st.st_mode))
    {
        /* TODO: send index.html if the request is for a directory */
        goto err;
    }
    else
    {
        /* Otherwise it's a file; add it to the buffer to get
         * sent via sendfile */
        const char *type = guess_content_type(decoded_path);
        if ((fd = open(whole_path, O_RDONLY)) < 0)
        {
            goto err;
        }

        if (fstat(fd, &st) < 0)
        {
            /* Make sure the length still matches, now that we
             * opened the file :/ */
            goto err;
        }

        evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", type);

        /* TODO: does this read the whole thing into memory??  well, we are only going to be
         * serving small files out of the static content directory, so its probably OK. */
        evbuffer_add_file(evb, fd, 0, st.st_size);
    }

    evhttp_send_reply(req, 200, "OK", evb);
    goto done;

err:
    evhttp_send_error(req, 404, "Document was not found");
    if (fd >= 0)
        close(fd);

done:
    if (decoded)
        evhttp_uri_free(decoded);

    if (decoded_path)
        free(decoded_path);

    if (whole_path)
        free(whole_path);

    if (evb)
        evbuffer_free(evb);
}
示例#30
0
/* This callback gets invoked when we get any http request that doesn't match
 * any other callback.  Like any evhttp server callback, it has a simple job:
 * it must eventually call evhttp_send_error() or evhttp_send_reply().
 */
static void
send_document_cb(struct evhttp_request *req, void *arg)
{
	struct evbuffer *evb = NULL;
	const char *docroot = arg;
	const char *uri = evhttp_request_get_uri(req);
	struct evhttp_uri *decoded = NULL;
	const char *path;
	char *decoded_path;
	char *whole_path = NULL;
	size_t len;
	int fd = -1;
	struct stat st;

	if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
		dump_request_cb(req, arg);
		return;
	}

	printf("Got a GET request for <%s>\n",  uri);

	/* Decode the URI */
	decoded = evhttp_uri_parse(uri);
	if (!decoded) {
		printf("It's not a good URI. Sending BADREQUEST\n");
		evhttp_send_error(req, HTTP_BADREQUEST, 0);
		return;
	}

	/* Let's see what path the user asked for. */
	path = evhttp_uri_get_path(decoded);
	if (!path) path = "/";

	/* We need to decode it, to see what path the user really wanted. */
	decoded_path = evhttp_uridecode(path, 0, NULL);
	if (decoded_path == NULL)
		goto err;
	/* Don't allow any ".."s in the path, to avoid exposing stuff outside
	 * of the docroot.  This test is both overzealous and underzealous:
	 * it forbids aceptable paths like "/this/one..here", but it doesn't
	 * do anything to prevent symlink following." */
	if (strstr(decoded_path, ".."))
		goto err;

	len = strlen(decoded_path)+strlen(docroot)+2;
	if (!(whole_path = malloc(len))) {
		perror("malloc");
		goto err;
	}
	evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);

	if (stat(whole_path, &st)<0) {
		goto err;
	}

	/* This holds the content we're sending. */
	evb = evbuffer_new();

	if (S_ISDIR(st.st_mode)) {
		/* If it's a directory, read the comments and make a little
		 * index page */
#ifdef WIN32
		HANDLE d;
		WIN32_FIND_DATAA ent;
		char *pattern;
		size_t dirlen;
#else
		DIR *d;
		struct dirent *ent;
#endif
		const char *trailing_slash = "";

		if (!strlen(path) || path[strlen(path)-1] != '/')
			trailing_slash = "/";

#ifdef WIN32
		dirlen = strlen(whole_path);
		pattern = malloc(dirlen+3);
		memcpy(pattern, whole_path, dirlen);
		pattern[dirlen] = '\\';
		pattern[dirlen+1] = '*';
		pattern[dirlen+2] = '\0';
		d = FindFirstFileA(pattern, &ent);
		free(pattern);
		if (d == INVALID_HANDLE_VALUE)
			goto err;
#else
		if (!(d = opendir(whole_path)))
			goto err;
#endif

		evbuffer_add_printf(evb, "<html>\n <head>\n"
		    "  <title>%s</title>\n"
		    "  <base href='%s%s%s'>\n"
		    " </head>\n"
		    " <body>\n"
		    "  <h1>%s</h1>\n"
		    "  <ul>\n",
		    decoded_path, /* XXX html-escape this. */
		    uri_root, path, /* XXX html-escape this? */
		    trailing_slash,
		    decoded_path /* XXX html-escape this */);
#ifdef WIN32
		do {
			const char *name = ent.cFileName;
#else
		while ((ent = readdir(d))) {
			const char *name = ent->d_name;
#endif
			evbuffer_add_printf(evb,
			    "    <li><a href=\"%s\">%s</a>\n",
			    name, name);/* XXX escape this */
#ifdef WIN32
		} while (FindNextFileA(d, &ent));
#else
		}
#endif
		evbuffer_add_printf(evb, "</ul></body></html>\n");
#ifdef WIN32
		FindClose(d);
#else
		closedir(d);
#endif
		evhttp_add_header(evhttp_request_get_output_headers(req),
		    "Content-Type", "text/html");
	} else {