static void cd_JSONRequest (struct evhttp_request* request, CDServer* server) { struct evbuffer* buffer = evhttp_request_get_input_buffer(request); char* text = CD_alloc(evbuffer_get_length(buffer) + 1); evbuffer_remove(buffer, text, evbuffer_get_length(buffer)); json_error_t error; json_t* input = json_loads(text, 0, &error); json_t* output = json_object(); printf("%s\n", text); if (evhttp_request_get_command(request) != EVHTTP_REQ_POST) { goto error; } if (input == NULL) { SERR(server, "RPC.JSON: error on line %d: %s", error.line, error.text); goto error; } CD_EventDispatch(server, "RPC.JSON", input, output); done: { char* outString = json_dumps(output, JSON_INDENT(2)); struct evbuffer* outBuffer = evbuffer_new(); evbuffer_add_printf(outBuffer, "%s", outString); evhttp_send_reply(request, HTTP_OK, "OK", outBuffer); evbuffer_free(outBuffer); free(outString); json_delete(output); json_delete(input); CD_free(text); return; } error: { evhttp_send_error(request, HTTP_INTERNAL, "Internal server error"); CD_free(text); if (input) { json_delete(input); } if (output) { json_delete(output); } return; } }
int Server::sub(struct evhttp_request *req, Subscriber::Type sub_type){ if(evhttp_request_get_command(req) != EVHTTP_REQ_GET){ evhttp_send_reply(req, 405, "Method Not Allowed", NULL); return 0; } bufferevent_enable(req->evcon->bufev, EV_READ); HttpQuery query(req); int seq = query.get_int("seq", 0); int noop = query.get_int("noop", 0); const char *cb = query.get_str("cb", DEFAULT_JSONP_CALLBACK); const char *token = query.get_str("token", ""); std::string cname = query.get_str("cname", ""); Channel *channel = this->get_channel_by_name(cname); if(!channel && this->auth == AUTH_NONE){ channel = this->new_channel(cname); if(!channel){ evhttp_send_reply(req, 429, "Too Many Channels", NULL); return 0; } } if(!channel || (this->auth == AUTH_TOKEN && channel->token != token)){ channel->error_token_error(req, cb, token); return 0; } if(channel->subs.size >= ServerConfig::max_subscribers_per_channel){ channel->error_too_many_subscribers(req, cb); return 0; } if(channel->idle < ServerConfig::channel_idles){ channel->idle = ServerConfig::channel_idles; } // send buffered messages if(!channel->msg_list.empty() && channel->seq_next != seq){ //channel->send_old_msgs(req, seq, cb); //return 0; } Subscriber *sub = sub_pool.alloc(); sub->req = req; sub->serv = this; sub->type = sub_type; sub->idle = 0; sub->seq = seq; sub->noop_seq = noop; sub->callback = cb; channel->add_subscriber(sub); subscribers ++; log_debug("%s:%d sub %s, subs: %d, channels: %d", req->remote_host, req->remote_port, channel->name.c_str(), channel->subs.size, used_channels.size); sub->start(); return 0; }
void request_handler(struct evhttp_request *req, void *arg) { // resolve route char *decode_uri = strdup((char *)evhttp_request_uri(req)); fprintf(stdout , "request: %s\n", decode_uri); int i = 0; for (; ;) { if (route_table[i].prefix == NULL && route_table[i].type == 0) { break; } enum evhttp_cmd_type type = evhttp_request_get_command(req); if (strncmp(route_table[i].prefix, decode_uri, strlen(route_table[i].prefix)) == 0 && route_table[i].type == type) { route_table[i].callback(req, arg); goto end; } i++; } send_404_page(req); fprintf(stderr, "404:%s\n", decode_uri); end: free(decode_uri); return; }
int Server::broadcast(struct evhttp_request *req){ if(evhttp_request_get_command(req) != EVHTTP_REQ_GET){ evhttp_send_reply(req, 405, "Invalid Method", NULL); return 0; } HttpQuery query(req); const char *content = query.get_str("content", ""); log_debug("%s:%d broadcast, content: %s", req->remote_host, req->remote_port, content); LinkedList<Channel *>::Iterator it = used_channels.iterator(); while(Channel *channel = it.next()){ if(channel->idle < ServerConfig::channel_idles){ channel->idle = ServerConfig::channel_idles; } channel->send("broadcast", content, false); } struct evbuffer *buf = evhttp_request_get_output_buffer(req); evbuffer_add_printf(buf, "ok\n"); evhttp_send_reply(req, 200, "OK", buf); return 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); }
int Server::pub(struct evhttp_request *req, bool encoded){ if(evhttp_request_get_command(req) != EVHTTP_REQ_GET){ evhttp_send_reply(req, 405, "Invalid Method", NULL); return 0; } HttpQuery query(req); const char *cb = query.get_str("cb", NULL); std::string cname = query.get_str("cname", ""); const char *content = query.get_str("content", ""); Channel *channel = NULL; channel = this->get_channel_by_name(cname); if(!channel){ channel = this->new_channel(cname); if(!channel){ evhttp_send_reply(req, 429, "Too Many Channels", NULL); return 0; } int expires = ServerConfig::channel_timeout; log_debug("auto sign channel on pub, cname:%s, t:%s, expires:%d", cname.c_str(), channel->token.c_str(), expires); channel->idle = expires/CHANNEL_CHECK_INTERVAL; /* struct evbuffer *buf = evbuffer_new(); log_trace("cname[%s] not connected, not pub content: %s", cname.c_str(), content); evbuffer_add_printf(buf, "cname[%s] not connected\n", cname.c_str()); evhttp_send_reply(req, 404, "Not Found", buf); evbuffer_free(buf); return 0; */ } log_debug("%s:%d pub %s, seq: %d, subs: %d, content: %s", req->remote_host, req->remote_port, channel->name.c_str(), channel->seq_next, channel->subs.size, content); // response to publisher evhttp_add_header(req->output_headers, "Content-Type", "text/javascript; charset=utf-8"); struct evbuffer *buf = evbuffer_new(); if(cb){ evbuffer_add_printf(buf, "%s(", cb); } evbuffer_add_printf(buf, "{\"type\":\"ok\"}"); if(cb){ evbuffer_add(buf, ");\n", 3); }else{ evbuffer_add(buf, "\n", 1); } evhttp_send_reply(req, 200, "OK", buf); evbuffer_free(buf); // push to subscribers if(channel->idle < ServerConfig::channel_idles){ channel->idle = ServerConfig::channel_idles; } channel->send("data", content, encoded); return 0; }
int Server::sub(struct evhttp_request *req, Subscriber::Type sub_type){ if(evhttp_request_get_command(req) != EVHTTP_REQ_GET){ evhttp_send_reply(req, 405, "Method Not Allowed", NULL); return 0; } HttpQuery query(req); int seq = query.get_int("seq", 0); int noop = query.get_int("noop", 0); const char *cb = query.get_str("cb", ""); const char *token = query.get_str("token", ""); std::string cname = query.get_str("cname", ""); Channel *channel = this->get_channel_by_name(cname); if(!channel && this->auth == AUTH_NONE){ channel = this->new_channel(cname); if(!channel){ //evhttp_send_reply(req, 429, "Too many channels", NULL); Subscriber::send_error_reply(sub_type, req, cb, cname, "429", "Too many channels"); return 0; } } if(!channel || (this->auth == AUTH_TOKEN && channel->token != token)){ //evhttp_send_reply(req, 401, "Token error", NULL); log_info("%s:%d sub %s, token: %s, token error!", req->remote_host, req->remote_port, cname.c_str(), token); Subscriber::send_error_reply(sub_type, req, cb, cname, "401", "Token error"); return 0; } if(channel->subs.size >= ServerConfig::max_subscribers_per_channel){ //evhttp_send_reply(req, 429, "Too many subscribers", NULL); Subscriber::send_error_reply(sub_type, req, cb, cname, "429", "Too many subscribers"); return 0; } if(channel->idle < ServerConfig::channel_idles){ channel->idle = ServerConfig::channel_idles; } Subscriber *sub = new Subscriber(); sub->req = req; sub->type = sub_type; sub->idle = 0; sub->seq_next = seq; sub->seq_noop = noop; sub->callback = cb; channel->add_subscriber(sub); subscribers ++; log_debug("%s:%d sub %s, seq: %d, subs: %d", req->remote_host, req->remote_port, channel->name.c_str(), seq, channel->subs.size); sub->start(); return 0; }
void shutdown_handler(struct evhttp_request *req, void *arg) { DBG(); if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) { reply_error(req, HTTP_BADREQUEST, "should call with GET"); return; } exit(0); }
static void post_command_cb(struct evhttp_request *req, void *arg) { size_t sz; int buffer_sz; struct evbuffer *buf; char *buffer = NULL; pid_t pid; log_write(INFO, "http-server: POST command cb\n"); if (EVHTTP_REQ_POST != evhttp_request_get_command(req)) { log_write(WARN, "http-server: Not support this method.\n"); evhttp_send_reply(req, 500, "not support this method", NULL); return; } log_write(INFO, "http-server: POST Request.\n"); buf = evhttp_request_get_input_buffer(req); sz = evbuffer_get_length(buf); buffer = malloc(sz + 1); if (NULL == buffer) { log_write(ERROR, "http-server: alloc memory error.\n"); evhttp_send_reply(req, 500, "alloc memroy error", NULL); return ; } /* Init temp buffer */ memset(buffer, 0, sz + 1); buffer_sz = evbuffer_remove(buf, buffer, sz); if (sz != buffer_sz) { log_write(ERROR, "http-server: post content error. sz: %ld, buffer_sz:%ld\n", sz, buffer_sz); evhttp_send_reply(req, 501, "post content error", NULL); free(buffer); buffer = NULL; return ; } /* NEED parser POST body and executed it */ int execrc = shell_cmd(buffer); if (0 == execrc) { log_write(INFO, "http-server: reply 200 OK. %d\n", execrc); evhttp_send_reply(req, 200, "OK", NULL); } else { log_write(ERROR, "fork error. %d\n", execrc); evhttp_send_reply(req, 502, "ERR", NULL); } free(buffer); buffer = NULL; return ; }
static void parseRequest(RequestInfo& requestInfo) { const struct evhttp_uri* uri = evhttp_request_get_evhttp_uri(requestInfo.req); /*const*/ struct evhttp_connection* conn = evhttp_request_get_connection(requestInfo.req); requestInfo.method = evhttp_request_get_command(requestInfo.req); requestInfo.uriHost = evhttp_uri_get_host(uri); requestInfo.uriPath = evhttp_uri_get_path(uri); requestInfo.uriQuery = evhttp_uri_get_query(uri); requestInfo.uriScheme = evhttp_uri_get_scheme(uri); requestInfo.requestHeaders = evhttp_request_get_input_headers(requestInfo.req); requestInfo.requestBody = evhttp_request_get_input_buffer(requestInfo.req); evhttp_connection_get_peer(conn, &requestInfo.remoteAddress, (ev_uint16_t*) &requestInfo.remotePort); }
static void handle_user_request(struct evhttp_request *request, char *action, const char *canonical_username, sp_session *session) { if (action == NULL) { evhttp_send_error(request, HTTP_BADREQUEST, "Bad Request"); return; } int http_method = evhttp_request_get_command(request); switch (http_method) { case EVHTTP_REQ_GET: if (strncmp(action, "playlists", 9) == 0) { sp_playlistcontainer *pc = sp_session_publishedcontainer_for_user_create( session, canonical_username); if (sp_playlistcontainer_is_loaded(pc)) { get_user_playlists(pc, request, session); } else { register_playlistcontainer_callbacks(pc, request, &get_user_playlists, &playlistcontainer_loaded_callbacks, session); } } else if (strncmp(action, "starred", 7) == 0) { sp_playlist *playlist = sp_session_starred_for_user_create(session, canonical_username); if (sp_playlist_is_loaded(playlist)) { get_playlist(playlist, request, session); } else { register_playlist_callbacks(playlist, request, &get_playlist, &playlist_state_changed_callbacks, session); } } break; case EVHTTP_REQ_PUT: case EVHTTP_REQ_POST: if (strncmp(action, "inbox", 5) == 0) { put_user_inbox(canonical_username, request, session); } break; default: evhttp_send_error(request, HTTP_BADREQUEST, "Bad Request"); break; } }
void HTTPHandler::info_handle(struct evhttp_request *req, void *arg) { if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) return; LOG(INFO) << "Request for server infomation."; // TODO(binfei): need memory pool struct evbuffer *databuf = evbuffer_new(); evbuffer_add_printf(databuf, "hello world"); evhttp_send_reply_start(req, 200, "OK"); evhttp_send_reply_chunk(req, databuf); evhttp_send_reply_end(req); evbuffer_free(databuf); }
void get_master_pgn(struct evhttp_request *req, void *context) { if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) { evhttp_send_error(req, HTTP_BADMETHOD, "Method Not Allowed"); return; } const struct evhttp_uri *uri = evhttp_request_get_evhttp_uri(req); if (!uri) { puts("evhttp_request_get_evhttp_uri failed"); return; } const char *path = evhttp_uri_get_path(uri); if (!path) { puts("evhttp_uri_get_path failed"); return; } char game_id[9] = {}; int end; if (1 != sscanf(path, "/master/pgn/%8s%n", game_id, &end) || strlen(game_id) != 8 || strlen(path) != end) { evhttp_send_error(req, HTTP_NOTFOUND, "Not Found"); return; } size_t pgn_size; char *pgn = kcdbget(master_pgn_db, game_id, 8, &pgn_size); if (!pgn) { evhttp_send_error(req, HTTP_NOTFOUND, "Master PGN Not Found"); return; } struct evbuffer *res = evbuffer_new(); if (!res) { puts("could not allocate response buffer"); abort(); } struct evkeyvalq *headers = evhttp_request_get_output_headers(req); evhttp_add_header(headers, "Content-Type", "application/vnd.chess-pgn; charset=utf-8"); evbuffer_add(res, pgn, pgn_size); kcfree(pgn); evhttp_send_reply(req, HTTP_OK, "OK", res); evbuffer_free(res); }
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; }
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); }
void write_chunk(uint64_t chunkid, struct evhttp_request *req) { DBG(); struct evbuffer *input; struct evbuffer *evb = evbuffer_new(); if (evhttp_request_get_command(req) != EVHTTP_REQ_POST) { reply_error(req, HTTP_BADREQUEST, "should call write with POST"); return; } uint64_t start = 0, end; const char *range = evhttp_find_header(req->input_headers, "Range"); logging(LOG_DEUBG, "write Range Header: %s", range); if (range) { sscanf(range, "bytes=%" SCNu64 "-%" SCNu64, &start, &end); } input = req->input_buffer; hdd_chunk *chunk = hdd_create_chunk(chunkid, 0); //TODO int fd = open(chunk->path, O_WRONLY | O_CREAT, 0755); logging(LOG_DEUBG, "write seek to : %" PRIu64 "", start); logging(LOG_DEUBG, "evbuffer_get_length(input) = %d", evbuffer_get_length(input)); lseek(fd, start, SEEK_SET); if (-1 == fd) { reply_error(req, HTTP_INTERNAL, "could not open file : %s", chunk->path); return; } int rst = 0; while (evbuffer_get_length(input) && (rst = evbuffer_write(input, fd)) > 0) { ; } /*evbuffer_write(input, fd); */ close(fd); evbuffer_add(evb, "success", strlen("success")); evhttp_send_reply(req, HTTP_OK, "OK", evb); evbuffer_free(evb); }
/* 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); }
HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() { switch (evhttp_request_get_command(req)) { case EVHTTP_REQ_GET: return GET; break; case EVHTTP_REQ_POST: return POST; break; case EVHTTP_REQ_HEAD: return HEAD; break; case EVHTTP_REQ_PUT: return PUT; break; default: return UNKNOWN; break; } }
/* * Get request command (i.e method) * * @return [String] http method for known command * @return [nil] if method is not supported * @example * GET */ static VALUE t_get_command(VALUE self) { Libevent_HttpRequest *http_request; VALUE command; Data_Get_Struct(self, Libevent_HttpRequest, http_request); switch ( evhttp_request_get_command(http_request->ev_request) ) { case EVHTTP_REQ_GET : command = rb_str_new2("GET"); break; case EVHTTP_REQ_POST : command = rb_str_new2("POST"); break; case EVHTTP_REQ_HEAD : command = rb_str_new2("HEAD"); break; case EVHTTP_REQ_PUT : command = rb_str_new2("PUT"); break; case EVHTTP_REQ_DELETE : command = rb_str_new2("DELETE"); break; case EVHTTP_REQ_OPTIONS : command = rb_str_new2("OPTIONS"); break; case EVHTTP_REQ_TRACE : command = rb_str_new2("TRACE"); break; case EVHTTP_REQ_CONNECT : command = rb_str_new2("CONNECT"); break; case EVHTTP_REQ_PATCH : command = rb_str_new2("PATCH"); break; default: command = Qnil; break; } return command; }
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; }
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); }
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; }
// Request dispatcher static void handle_request(struct evhttp_request *request, void *userdata) { evhttp_connection_set_timeout(request->evcon, 1); evhttp_add_header(evhttp_request_get_output_headers(request), "Server", "[email protected]/spotify-api-server"); // Check request method int http_method = evhttp_request_get_command(request); switch (http_method) { case EVHTTP_REQ_GET: case EVHTTP_REQ_PUT: case EVHTTP_REQ_POST: break; default: evhttp_send_error(request, HTTP_NOTIMPL, "Not Implemented"); return; } struct state *state = userdata; sp_session *session = state->session; char *uri = evhttp_decode_uri(evhttp_request_get_uri(request)); char *entity = strtok(uri, "/"); if (entity == NULL) { evhttp_send_error(request, HTTP_BADREQUEST, "Bad Request"); free(uri); return; } // Handle requests to /user/<user_name>/inbox if (strncmp(entity, "user", 4) == 0) { char *username = strtok(NULL, "/"); if (username == NULL) { evhttp_send_error(request, HTTP_BADREQUEST, "Bad Request"); free(uri); return; } char *action = strtok(NULL, "/"); handle_user_request(request, action, username, session); free(uri); return; } // Handle requests to /playlist/<playlist_uri>/<action> if (strncmp(entity, "playlist", 8) != 0) { evhttp_send_error(request, HTTP_BADREQUEST, "Bad Request"); free(uri); return; } char *playlist_uri = strtok(NULL, "/"); if (playlist_uri == NULL) { switch (http_method) { case EVHTTP_REQ_PUT: case EVHTTP_REQ_POST: put_playlist(NULL, request, session); break; default: send_error(request, HTTP_BADREQUEST, "Bad Request"); break; } free(uri); return; } sp_link *playlist_link = sp_link_create_from_string(playlist_uri); if (playlist_link == NULL) { send_error(request, HTTP_NOTFOUND, "Playlist link not found"); free(uri); return; } if (sp_link_type(playlist_link) != SP_LINKTYPE_PLAYLIST) { sp_link_release(playlist_link); send_error(request, HTTP_BADREQUEST, "Not a playlist link"); free(uri); return; } sp_playlist *playlist = sp_playlist_create(session, playlist_link); sp_link_release(playlist_link); if (playlist == NULL) { send_error(request, HTTP_NOTFOUND, "Playlist not found"); free(uri); return; } sp_playlist_add_ref(playlist); // Dispatch request char *action = strtok(NULL, "/"); // Default request handler handle_playlist_fn request_callback = ¬_implemented; void *callback_userdata = session; switch (http_method) { case EVHTTP_REQ_GET: { if (action == NULL) { // Send entire playlist request_callback = &get_playlist; } else if (strncmp(action, "collaborative", 13) == 0) { request_callback = &get_playlist_collaborative; } else if (strncmp(action, "subscribers", 11) == 0) { request_callback = &get_playlist_subscribers; } } break; case EVHTTP_REQ_PUT: case EVHTTP_REQ_POST: { if (strncmp(action, "add", 3) == 0) { request_callback = &put_playlist_add_tracks; } else if (strncmp(action, "remove", 6) == 0) { request_callback = &put_playlist_remove_tracks; } else if (strncmp(action, "patch", 5) == 0) { callback_userdata = state; request_callback = &put_playlist_patch; } } break; } if (sp_playlist_is_loaded(playlist)) { request_callback(playlist, request, callback_userdata); } else { // Wait for playlist to load register_playlist_callbacks(playlist, request, request_callback, &playlist_state_changed_callbacks, callback_userdata); } free(uri); }
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); }
/* 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 {
void get_master(struct evhttp_request *req, void *context) { if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) { evhttp_send_error(req, HTTP_BADMETHOD, "Method Not Allowed"); return; } const char *uri = evhttp_request_get_uri(req); if (!uri) { puts("evhttp_request_get_uri failed"); return; } struct evkeyvalq query; const char *fen = NULL; const char *jsonp = NULL; int moves = 12; int topGames = 4; if (0 == evhttp_parse_query(uri, &query)) { fen = evhttp_find_header(&query, "fen"); jsonp = evhttp_find_header(&query, "callback"); if (evhttp_find_header(&query, "moves")) { moves = atoi(evhttp_find_header(&query, "moves")); } if (evhttp_find_header(&query, "topGames")) { topGames = atoi(evhttp_find_header(&query, "topGames")); } } if (!fen || !strlen(fen)) { evhttp_send_error(req, HTTP_BADREQUEST, "Missing FEN"); return; } // Look up positon. board_t pos; if (!board_set_fen(&pos, fen)) { evhttp_send_error(req, HTTP_BADREQUEST, "Invalid FEN"); } if (verbose) printf("master: %.255s\n", fen); struct evbuffer *res = evbuffer_new(); if (!res) { puts("could not allocate response buffer"); abort(); } // CORS. struct evkeyvalq *headers = evhttp_request_get_output_headers(req); if (cors) evhttp_add_header(headers, "Access-Control-Allow-Origin", "*"); // Set Content-Type. if (jsonp && strlen(jsonp)) { evhttp_add_header(headers, "Content-Type", "application/javascript"); evbuffer_add_printf(res, "%s(", jsonp); } else { evhttp_add_header(headers, "Content-Type", "application/json"); } uint64_t zobrist_hash = board_zobrist_hash(&pos, POLYGLOT); struct master_record *record = master_record_new(); size_t record_size; char *encoded_record = kcdbget(master_db, (const char *) &zobrist_hash, 8, &record_size); if (encoded_record) { decode_master_record((const uint8_t *) encoded_record, record); } unsigned long average_rating_sum = master_record_average_rating_sum(record); unsigned long total_white = master_record_white(record); unsigned long total_draws = master_record_draws(record); unsigned long total_black = master_record_black(record); unsigned long total = total_white + total_draws + total_black; evbuffer_add_printf(res, "{\n"); // Add totals. evbuffer_add_printf(res, " \"white\": %lu,\n", total_white); evbuffer_add_printf(res, " \"draws\": %lu,\n", total_draws); evbuffer_add_printf(res, " \"black\": %lu,\n", total_black); if (total) evbuffer_add_printf(res, " \"averageRating\": %lu,\n", average_rating_sum / total); else evbuffer_add_printf(res, " \"averageRating\": null,\n"); // Add move list. evbuffer_add_printf(res, " \"moves\": [\n"); for (size_t i = 0; i < record->num_moves && i < moves; i++) { unsigned long move_total = record->moves[i].white + record->moves[i].draws + record->moves[i].black; char uci[LEN_UCI], san[LEN_SAN]; move_uci(record->moves[i].move, uci); board_san(&pos, record->moves[i].move, san); evbuffer_add_printf(res, " {\n"); evbuffer_add_printf(res, " \"uci\": \"%s\",\n", uci); evbuffer_add_printf(res, " \"san\": \"%s\",\n", san); evbuffer_add_printf(res, " \"white\": %lu,\n", record->moves[i].white); evbuffer_add_printf(res, " \"draws\": %lu,\n", record->moves[i].draws); evbuffer_add_printf(res, " \"black\": %lu,\n", record->moves[i].black); if (move_total) { evbuffer_add_printf(res, " \"averageRating\": %lu\n", record->moves[i].average_rating_sum / move_total); } else { evbuffer_add_printf(res, " \"averageRating\": null\n"); } evbuffer_add_printf(res, " }%s\n", (i < record->num_moves - 1 && i < moves - 1) ? "," : ""); } evbuffer_add_printf(res, " ],\n"); // Add top games. evbuffer_add_printf(res, " \"topGames\": [\n"); for (size_t i = 0; i < record->num_refs && i < topGames; i++) { char game_id[9] = {}; strncpy(game_id, record->refs[i].game_id, 8); size_t pgn_size; char *pgn = kcdbget(master_pgn_db, game_id, 8, &pgn_size); if (!pgn) continue; char *save_ptr; struct pgn_game_info *game_info = pgn_game_info_read(pgn, &save_ptr); if (!game_info->white || !game_info->black) continue; evbuffer_add_printf(res, " {\n"); // TODO: winner, white.name, white.rating, black.name, black.rating, -avg rating evbuffer_add_printf(res, " \"id\": \"%s\",\n", game_id); evbuffer_add_printf(res, " \"winner\": \"%s\",\n", game_info->result ? (game_info->result > 0 ? "white" : "black") : "draw"); evbuffer_add_printf(res, " \"white\": {\n"); evbuffer_add_printf(res, " \"name\": \"%s\",\n", game_info->white); // XXX TODO ! evbuffer_add_printf(res, " \"rating\": %d\n", game_info->white_elo); evbuffer_add_printf(res, " },\n"); evbuffer_add_printf(res, " \"black\": {\n"); evbuffer_add_printf(res, " \"name\": \"%s\",\n", game_info->black); // XXX TODO ! evbuffer_add_printf(res, " \"rating\": %d\n", game_info->black_elo); evbuffer_add_printf(res, " },\n"); evbuffer_add_printf(res, " \"year\": %d\n", game_info->year); evbuffer_add_printf(res, " }%s\n", (i < record->num_refs - 1 && i < topGames - 1) ? "," : ""); } evbuffer_add_printf(res, " ]\n"); evbuffer_add_printf(res, "}%s\n", (jsonp && strlen(jsonp)) ? ")" : ""); evhttp_send_reply(req, HTTP_OK, "OK", res); evbuffer_free(res); }
static void cd_StaticRequest (struct evhttp_request* request, CDServer* server) { int error = HTTP_OK; const char* message = "OK"; const char* uri = evhttp_request_get_uri(request); struct evhttp_uri* decoded = evhttp_uri_parse(uri); if (evhttp_request_get_command(request) != EVHTTP_REQ_GET) { error = HTTP_BADMETHOD; message = "Invalid request method"; goto end; } if (!decoded || strstr(evhttp_uri_get_path(decoded), "..")) { error = HTTP_BADREQUEST; message = "Bad request"; goto end; } DO { CDString* path = CD_CreateStringFromFormat("%s/%s", server->config->cache.httpd.root, evhttp_uri_get_path(decoded) ? evhttp_uri_get_path(decoded) : "index.html"); if (CD_IsDirectory(CD_StringContent(path))) { CD_AppendCString(path, "/index.html"); } if (!CD_IsReadable(CD_StringContent(path))) { error = HTTP_NOTFOUND; message = "File not found"; CD_DestroyString(path); goto end; } struct evbuffer* buffer = evbuffer_new(); int fd = open(CD_StringContent(path), O_RDONLY); evhttp_add_header(evhttp_request_get_output_headers(request), "Content-Type", cd_GuessContentType(CD_StringContent(path))); evbuffer_add_file(buffer, fd, 0, CD_FileSize(CD_StringContent(path))); evhttp_send_reply(request, HTTP_OK, "OK", buffer); evbuffer_free(buffer); CD_DestroyString(path); } end: { if (decoded) { evhttp_uri_free(decoded); } if (error != HTTP_OK) { evhttp_send_error(request, error, message); } } }
static int64_t HHVM_METHOD(EventHttpRequest, getCommand) { EventHttpRequestResourceData *event_http_request_resource_data = FETCH_RESOURCE(this_, EventHttpRequestResourceData, s_event_http_request); return evhttp_request_get_command((evhttp_request_t *) event_http_request_resource_data->getInternalResourceData()); }
void servlet(struct evhttp_request *req, struct evbuffer *evb, const char *get_query) { /*dbi_conn conn; dbi_result result; unsigned int idnumber; char *fullname; dbi_initialize(NULL); conn = dbi_conn_new("mysql"); dbi_conn_set_option(conn, "host", "localhost"); dbi_conn_set_option(conn, "username", "root"); dbi_conn_set_option(conn, "password", "root"); dbi_conn_set_option(conn, "dbname", "test"); dbi_conn_set_option(conn, "encoding", "UTF-8"); if (dbi_conn_connect(conn) < 0) { printf("Could not connect"); } else { result = dbi_conn_queryf(conn, "SELECT id, name FROM test"); if (result) { printf("dbi_result_get_numrows: %u", dbi_result_get_numrows(result)); while (dbi_result_next_row(result)) { idnumber = dbi_result_get_uint(result, "id"); fullname = dbi_result_get_string(result, "name"); printf("%i. %s", idnumber, fullname); } dbi_result_free(result); } dbi_conn_close(conn); }*/ time_t now; time(&now); const char *value; struct evkeyvalq params; char *data; size_t len; if (evhttp_request_get_command(req) == EVHTTP_REQ_GET) { evhttp_parse_query_str(get_query, ¶ms); value = evhttp_find_header(¶ms, "first_name"); } else { len = evbuffer_get_length(evhttp_request_get_input_buffer(req)); struct evbuffer *in_evb = evhttp_request_get_input_buffer(req); data = malloc(len + 1); evbuffer_copyout(in_evb, data, len); data[len] = '\0'; evhttp_parse_query_str(data, ¶ms); value = evhttp_find_header(¶ms, "first_name"); } evbuffer_add_printf(evb, "<html>\n <head>\n" " <title>C servlet</title>\n" " </head>\n" " <body>\n" " <h1>C servlet</h1>\n" " <p>Current time is: %s (GMT)</p>" " <p>First name is: %s</p>\n<hr>\n" "<form action=\"/servlet\" method=\"POST\">\n" "First name <input type=\"text\" name=\"first_name\">" "<input type=\"submit\" value=\"send via post\">" "</form>\n" "<p>COOKIE: %s</p>" "<p><a href=\"/servlet?first_name=John\">GET with parameters</a></p>" "</body><html>", ctime(&now), value, http_get_cookie(req, "CSESSID")); evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/html"); evhttp_add_header(evhttp_request_get_output_headers(req), "Set-Cookie", "CSESSID=435J43L523J4TTYYY; Path=/; Domain=intranet2.local"); evhttp_add_header(evhttp_request_get_output_headers(req), "Set-Cookie", "[email protected]; Path=/; Domain=intranet2.local"); evhttp_add_header(evhttp_request_get_output_headers(req), "Server", "green httpd"); evhttp_send_reply(req, 200, "OK", evb); if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) { evhttp_clear_headers(¶ms); free(data); } }
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); }