Example #1
0
void
serve_control_javascript(struct evhttp_request *request, void *arg)
{
	struct evbuffer *databuf = evbuffer_new();
	assert(databuf != NULL);
	evhttp_add_header(request->output_headers,
	    "Content-Type", "text/javascript");
	evbuffer_add(databuf, control_js, strlen(control_js));

	/* send along our data */
	evhttp_send_reply(request, HTTP_OK, "OK", databuf);
	evbuffer_free(databuf);
}
Example #2
0
int Server::ping(struct evhttp_request *req){
	HttpQuery query(req);
	const char *cb = query.get_str("cb", DEFAULT_JSONP_CALLBACK);

	struct evbuffer *buf = evbuffer_new();
	evbuffer_add_printf(buf,
		"%s({\"type\":\"ping\",\"sub_timeout\":%d});\n",
		cb,
		ServerConfig::polling_timeout);
	evhttp_send_reply(req, HTTP_OK, "OK", buf);
	evbuffer_free(buf);
	return 0;
}
Example #3
0
void PendingResponseQueue::process() {
  // clean up the pipe for next signals
  char buf[512];
  if (read(m_ready.getOut(), buf, sizeof(buf)) < 0) {
    // an error occured but nothing we can really do
  }

  // making a copy so we don't hold up the mutex very long
  ResponsePtrVec responses;
  for (int i = 0; i < RuntimeOption::ResponseQueueCount; i++) {
    ResponseQueue &q = *m_responseQueues[i];
    Lock lock(q.m_mutex);
    responses.insert(responses.end(),
                     q.m_responses.begin(), q.m_responses.end());
    q.m_responses.clear();
  }

  for (unsigned int i = 0; i < responses.size(); i++) {
    Response &res = *responses[i];
    evhttp_request *request = res.request;
    int code = res.code;

    if (request->evcon == nullptr) {
      evhttp_request_free(request);
      continue;
    }

    bool skip_sync = false;
#ifdef _EVENT_USE_OPENSSL
    skip_sync = evhttp_is_connection_ssl(request->evcon);
#endif

    if (res.chunked) {
      if (res.chunk) {
        if (res.firstChunk) {
          const char *reason = HttpProtocol::GetReasonString(code);
          evhttp_send_reply_start(request, code, reason);
        }
        evhttp_send_reply_chunk(request, res.chunk);
      } else {
        evhttp_send_reply_end(request);
      }
    } else if (RuntimeOption::LibEventSyncSend && !skip_sync) {
      evhttp_send_reply_sync_end(res.nwritten, request);
    } else {
      const char *reason = HttpProtocol::GetReasonString(code);
      evhttp_send_reply(request, code, reason, nullptr);
    }
  }
}
Example #4
0
File: rpc.c Project: dyustc/searaft
static void server_rpc_cb(struct evhttp_request *req, void *arg) {
    struct rpc_context *rpc_context = (struct rpc_context *)arg;

    char *json = read_req_buffer(req);
    if(!json) {
        evhttp_send_error(req, 500, "Internal server error");
        return;
    }

    struct method_t *method = deserialize_method_call(json);
    if(!method) {
        evhttp_send_error(req, 500, "Error deserializing method call");
        free(json);
        return;
    }
    void *satellite_data;
    rpc_method_impl_t impl = search_method_entry(rpc_context->lookup, method->name, &satellite_data);
    if(!impl) {
        evhttp_send_error(req, 500, "Method not found");
    } else {
        //impl should also throw error
        char *err;
        struct data_t *result = impl(method->params, method->nparams, &err, satellite_data);
        char *json_result = NULL;

        struct evbuffer *evb = evbuffer_new();

        if(result && (json_result = serialize_result(result, NULL)) && evb) {
            if(evbuffer_add(evb, json_result, strlen(json_result))) {
                evhttp_send_error(req, 500, "Internal server error");
            } else {
                evhttp_send_reply(req, 200, "OK", evb);
            }
        } else {
            if(err) {
                evhttp_send_error(req, 500, err);
                free(err);
            } else {
                evhttp_send_error(req, 500, "Internal server error");
            }
        }

        if(evb) evbuffer_free(evb);
        if(json_result) free(json_result);
        if(result) free_data_t(result);
    }

    free(json);
    free_method_t(method);
}
Example #5
0
/* 处理模块 */
void httpcws_handler(struct evhttp_request *req, void *arg)
{	
        struct evbuffer *buf;
        buf = evbuffer_new();
		
		/* 分析URL参数 */
		struct evkeyvalq httpcws_http_query;
		evhttp_parse_query(evhttp_request_uri(req), &httpcws_http_query);
		
		/* 接收POST表单信息 */
		const char *tcsql_input_postbuffer = (const char*) EVBUFFER_DATA(req->input_buffer);		
		
		/* 接收GET表单参数 */
		const char *httpcws_input_words = evhttp_find_header (&httpcws_http_query, "w");

		const char *httpcws_output_tmp = NULL;
		char *httpcws_output_words = "\0";
		if (tcsql_input_postbuffer != NULL) {
			char *tcsql_input_postbuffer_tmp = (char *) malloc(EVBUFFER_LENGTH(req->input_buffer)+1);
			memset (tcsql_input_postbuffer_tmp, '\0', EVBUFFER_LENGTH(req->input_buffer)+1);
			strncpy(tcsql_input_postbuffer_tmp, tcsql_input_postbuffer, EVBUFFER_LENGTH(req->input_buffer));
			char *decode_uri = urldecode(tcsql_input_postbuffer_tmp);
			free(tcsql_input_postbuffer_tmp);
			httpcws_output_tmp = ICTCLAS_ParagraphProcess(decode_uri, 0);
			free(decode_uri);
			httpcws_output_words = strdup(httpcws_output_tmp);
			trim (httpcws_output_words);
		} else if (httpcws_input_words != NULL) {
			char *httpcws_input_words_tmp = strdup(httpcws_input_words);
			char *decode_uri = urldecode(httpcws_input_words_tmp);
			free(httpcws_input_words_tmp);
			httpcws_output_tmp = ICTCLAS_ParagraphProcess(decode_uri, 0);
			free(decode_uri);
			httpcws_output_words = strdup(httpcws_output_tmp);
			trim (httpcws_output_words);
		} else {
			httpcws_output_words = strdup("");
		}
		
		/* 输出内容给客户端 */
		evhttp_add_header(req->output_headers, "Server", "HTTPCWS/1.0.0");
		evhttp_add_header(req->output_headers, "Content-Type", "text/plain; charset=GB2312");
		evhttp_add_header(req->output_headers, "Connection", "close");
		evbuffer_add_printf(buf, "%s", httpcws_output_words);
        evhttp_send_reply(req, HTTP_OK, "OK", buf);
		
		free(httpcws_output_words);
		evhttp_clear_headers(&httpcws_http_query);
		evbuffer_free(buf);	
}
Example #6
0
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", "");
	
	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;
}
Example #7
0
void web_json(struct evhttp_request *req, cJSON *root) {
	struct evbuffer *evb = evbuffer_new();
	char *out;

	out = cJSON_Print(root);
	cJSON_Delete(root);

	evbuffer_add(evb, out, strlen(out));
	evhttp_add_header(req->output_headers, "Content-Type", "application/json");
	evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
	evbuffer_free(evb);

	free(out);
}
Example #8
0
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);
}
Example #9
0
File: httpd.c Project: aol/thrasher
void
httpd_driver(struct evhttp_request *req, void *arg)
{
    struct evbuffer *buf;

    buf = evbuffer_new();

    evhttp_add_header(req->output_headers, "Content-Type", "text/plain");
    evbuffer_add_printf(buf, "Thrashd version: %s [%s]\n", VERSION,
                        process_name);

    evhttp_send_reply(req, HTTP_OK, "OK", buf);
    evbuffer_free(buf);
}
Example #10
0
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;
}
Example #12
0
static void httpd_handler(struct evhttp_request *req, void *arg) {
	struct evbuffer *buf;
	buf = evbuffer_new();

	//get http request url
	char *decode_uri = strdup((char*) evhttp_request_uri(req));
	struct evkeyvalq httpd_query;
	evhttp_parse_query(decode_uri, &httpd_query);
	free(decode_uri);

	//recive http params
	const char *start = evhttp_find_header(&httpd_query, "start");
	const char *httpd_charset = evhttp_find_header(&httpd_query, "charset");

	//send http header charset
	if (httpd_charset != NULL && strlen(httpd_charset) <= 40) {
		char content_type[64] = { 0 };
		sprintf(content_type, "text/plain; charset=%s", httpd_charset);
		evhttp_add_header(req->output_headers, "Content-Type", content_type);
	} else {
		evhttp_add_header(req->output_headers, "Content-Type", "text/plain");
	}

	evhttp_add_header(req->output_headers, "Connection", "keep-alive");
	evhttp_add_header(req->output_headers, "Cache-Control", "no-cache");
	evbuffer_add_printf(buf, "%s\n", "HTTRACK_OK");

	char start_t[255] = {0x00};
	sprintf(start_t, "%s", start);
	if (strcmp(start_t, "1") == 0) {

		struct hts_proj proj;
		proj.depth = 5;
		proj.priority = PRIORITY_ONLY_HTML;
		proj.action = ACTION_ONLY_FILES;

		sprintf(proj.name, "%s", "dianying.yisou.com");
		sprintf(proj.urls, "%s", "http://dianying.yisou.com/");

		new_dl_thread();
	}

	//send content to client
	evhttp_send_reply(req, HTTP_OK, "OK", buf);

	//free buf
	evhttp_clear_headers(&httpd_query);
	evbuffer_free(buf);
}
Example #13
0
static void
send_simple_response (struct evhttp_request * req,
                      int                     code,
                      const char            * text)
{
  const char * code_text = tr_webGetResponseStr (code);
  struct evbuffer * body = evbuffer_new ();

  evbuffer_add_printf (body, "<h1>%d: %s</h1>", code, code_text);
  if (text)
    evbuffer_add_printf (body, "%s", text);
  evhttp_send_reply (req, code, code_text, body);

  evbuffer_free (body);
}
Example #14
0
File: httpd.c Project: aol/thrasher
void
httpd_put_connections_html (struct evhttp_request *req, void *arg)
{
    struct evbuffer *buf;

    buf = evbuffer_new();
    httpd_put_html_start(buf, "Connections", TRUE);
    evbuffer_add_printf(buf, "<tr><th>Address</th><th>Port</th><th>Requests</th><th>Connection Date</th><th>Last Date</th></tr>");
    g_slist_foreach(current_connections, (GFunc) fill_current_connections_html, buf);
    httpd_put_html_end(buf);

    evhttp_add_header(req->output_headers, "Content-Type", "text/html");
    evhttp_send_reply(req, HTTP_OK, "OK", buf);
    evbuffer_free(buf);
}
Example #15
0
void cweb_request_handler(struct evhttp_request *req, void *arg)
{
	struct evbuffer *returnbuffer = evbuffer_new();
	struct page *dest = http_router(req->uri);

	if (dest == NULL) {
		if (strstr(req->uri, ".html") != NULL)
			evbuffer_add_printf(returnbuffer, "<!doctype html>\n<html lang=zh>\n<head>\n\t"
				"<title>404 Not Found</title>\n</head>\n<body>\n</body>\n</html>");
	} else
		dest->get(returnbuffer);
	evhttp_send_reply(req, HTTP_OK, "Client", returnbuffer);
	evbuffer_free(returnbuffer);
	return;
}
bool NFCHttpServer::ResponseMsg(const NFHttpRequest& req, const std::string& strMsg, NFWebStatus code,
                                const std::string& strReason)
{
    evhttp_request* pHttpReq = (evhttp_request*) req.req;
    //create buffer
    struct evbuffer* eventBuffer = evbuffer_new();
    //send data
    evbuffer_add_printf(eventBuffer, strMsg.c_str());
    evhttp_add_header(evhttp_request_get_output_headers(pHttpReq), "Content-Type", "text/html");
    evhttp_send_reply(pHttpReq, code, strReason.c_str(), eventBuffer);

    //free
    evbuffer_free(eventBuffer);
    return true;
}
Example #17
0
File: httpd.c Project: aol/thrasher
void
httpd_put_holddowns_html (struct evhttp_request *req, void *arg)
{
    struct evbuffer *buf;

    buf = evbuffer_new();
    httpd_put_html_start(buf, "Hold downs", TRUE);
    evbuffer_add_printf(buf, "<tr><th>Blocked IP</th>%s<th>Triggered By</th><th>Count</th><th>Velocity</th><th>Soft</th><th>Hard</th><th>Recent</th><th>Reason</th>%s</tr>", geoip_header, (http_password?"<th>Actions</th>":""));
    g_tree_foreach(current_blocks, (GTraverseFunc) fill_http_blocks_html, buf);
    httpd_put_html_end(buf);

    evhttp_add_header(req->output_headers, "Content-Type", "text/html");
    evhttp_send_reply(req, HTTP_OK, "OK", buf);
    evbuffer_free(buf);
}
Example #18
0
File: httpd.c Project: aol/thrasher
void
httpd_put_uris_html (struct evhttp_request *req, void *arg)
{
    struct evbuffer *buf;

    buf = evbuffer_new();
    httpd_put_html_start(buf, "URIs", TRUE);
    evbuffer_add_printf(buf, "<tr><th>Address</th>%s<th>Connections</th><th>Timeout</th><th>Reason</th><th>URI (80 char max)</th>%s</tr>",geoip_header, (http_password?"<th>Actions</th>":""));
    g_hash_table_foreach(uri_table, (GHFunc) fill_http_uri_html, buf);
    httpd_put_html_end(buf);

    evhttp_add_header(req->output_headers, "Content-Type", "text/html");
    evhttp_send_reply(req, HTTP_OK, "OK", buf);
    evbuffer_free(buf);
}
Example #19
0
int Server::clear(struct evhttp_request *req){
	HttpQuery query(req);
	std::string cname = query.get_str("cname", "");

	Channel *channel = this->get_channel_by_name(cname);
	if(!channel){
		log_warn("channel %s not found", cname.c_str());
		struct evbuffer *buf = evhttp_request_get_output_buffer(req);
		evbuffer_add_printf(buf, "channel[%s] not connected\n", cname.c_str());
		evhttp_send_reply(req, 404, "Not Found", buf);
		return 0;
	}
	log_debug("clear channel: %s, subs: %d", cname.c_str(), channel->subs.size);
		
	// response to publisher
	evhttp_add_header(req->output_headers, "Content-Type", "text/html; charset=utf-8");
	struct evbuffer *buf = evhttp_request_get_output_buffer(req);
	evbuffer_add_printf(buf, "ok %d\n", channel->seq_next);
	evhttp_send_reply(req, 200, "OK", buf);

	channel->clear();

	return 0;
}
Example #20
0
void CHttpServer::http_reponse(struct evhttp_request *req, 
						 struct evkeyvalq *params, 
						 int statcode, 
						 char *statreason)
{
	struct evbuffer *buff = evbuffer_new();

	evhttp_add_header(req->output_headers, "Content-Type", "text/plain; charset=UTF-8");
	evhttp_add_header(req->output_headers, "Connection", "close");
	evhttp_send_reply(req, statcode, statreason, buff);
	evhttp_clear_headers(params);
	evbuffer_free(buff);
	
	return;
}
Example #21
0
static void send_reply(struct evhttp_request *request,
                       int code,
                       const char *message,
                       struct evbuffer *body) {
  evhttp_add_header(evhttp_request_get_output_headers(request),
                    "Content-type", "application/json; charset=UTF-8");
  bool empty_body = body == NULL;

  if (empty_body)
    body = evbuffer_new();

  evhttp_send_reply(request, code, message, body);

  if (empty_body)
    evbuffer_free(body);
}
Example #22
0
void handle_request_stats(struct evhttp_request *req, void *arg){
	global_data * global = (global_data *) arg;

	struct evbuffer *evb;
	evb = evbuffer_new();

	evbuffer_add_printf(evb, "Uptime:   %u<br />\n", (get_now() - global->stats.starttime));
	evbuffer_add_printf(evb, "Requests: %u<br />\n", global->stats.requests);
//	evbuffer_add_printf(evb, "Games:    %u<br />\n", global->stats.games);
	evbuffer_add_printf(evb, "Moves:    %u<br />\n", global->stats.moves);
	evbuffer_add_printf(evb, "Cpu Time: %u s<br />\n", global->stats.cputime/1000);

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

	evbuffer_free(evb);
}
Example #23
0
File: httpd.c Project: aol/thrasher
void
httpd_put_holddowns(struct evhttp_request *req, void *args)
{
    struct evbuffer *buf;

    buf = evbuffer_new();

    evbuffer_add_printf(buf, "%-15s %-15s %-10s %-9s %-8s %-8s %-8s\n",
                        "Blocked IP", "Triggered By", "Count", "Velocity", "Soft", "Hard", "Recent");

    g_tree_foreach(current_blocks, (GTraverseFunc) fill_http_blocks, buf);

    evhttp_add_header(req->output_headers, "Content-Type", "text/plain");
    evhttp_send_reply(req, HTTP_OK, "OK", buf);
    evbuffer_free(buf);
}
Example #24
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;
}
Example #25
0
/*
 * request start - end 
 * if file_size < end;
 * return start - file_size
 * */
void read_chunk(uint64_t chunkid, struct evhttp_request *req)
{
    DBG();
    struct evbuffer *evb = evbuffer_new();
    hdd_chunk *chunk = chunk_hashtable_get(chunkid);

    if (chunk == NULL) {
        reply_error(req, HTTP_NOTFOUND, "not found chunk %" PRIx64 ";",
                    chunkid);
        return;
    }

    hdd_chunk_printf(chunk);

    uint64_t start = 0, end = 0;
    const char *range = evhttp_find_header(req->input_headers, "Range");
    struct stat st;

    logging(LOG_DEUBG, "get range : %s", range);
    int fd = open(chunk->path, O_RDONLY);
    if (fstat(fd, &st) < 0) {
        reply_error(req, HTTP_NOTFOUND, "file not exist : %s", chunk->path);
        return;
    }
    logging(LOG_DEUBG, "st.st_size = : %d", st.st_size);

    if (range) {
        sscanf(range, "bytes=%" SCNu64 "-%" SCNu64, &start, &end);
        //假设文件st_size = 2
        //if end = 0, 应该返回1个字节           end=end
        //if end = 1, 应该返回0,1 共2个字节.    end = st_size - 1  || end = end
        //if end = 2, 还是应该2个字节.          end = st_size - 1
        if (st.st_size <= end)
            end = st.st_size - 1;
    } else {
        start = 0;
        end = st.st_size - 1;
    }
    logging(LOG_DEUBG, "get return range : %" PRIu64 " - %" PRIu64, start, end);
    logging(LOG_DEUBG, "d : %" PRIu64, end - start + 1);

    lseek(fd, start, SEEK_SET);
    evbuffer_add_file(evb, fd, (int)start, end - start + 1);    //如果编译的时候加上 -D_FILE_OFFSET_BITS=64 ,,evbuffer认为length = 0

    evhttp_send_reply(req, HTTP_OK, "OK", evb);
    evbuffer_free(evb);
}
Example #26
0
int Server::check(struct evhttp_request *req){
	HttpQuery query(req);
	std::string cname = query.get_str("cname", "");

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

	struct evbuffer *buf = evhttp_request_get_output_buffer(req);
	Channel *channel = this->get_channel_by_name(cname);
	if(channel && channel->idle != -1){
		evbuffer_add_printf(buf, "{\"%s\": 1}\n", cname.c_str());
	}else{
		evbuffer_add_printf(buf, "{}\n");
	}
	evhttp_send_reply(req, 200, "OK", buf);

	return 0;
}
Example #27
0
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);
}
Example #28
0
File: owl.c Project: eliasson/owl
//
// -- Spotify stuff -------------------------------------------------------------------------------
//
static int initialize_spotify(struct owl_state* state) {
    TRACE("initialize_spotify\n");

    const sp_session_callbacks session_callbacks = {
        .logged_in = &logged_in_callback,
        .logged_out = &logged_out_callback,
        .notify_main_thread = &notify_main_thread_callback
    };

    const sp_session_config session_config = {
        .api_version = SPOTIFY_API_VERSION,
        .cache_location = ".cache/libspotify/",
        .settings_location = ".config/libspotify/",
        .application_key = g_appkey,
        .application_key_size = g_appkey_size,
        .callbacks = &session_callbacks,
        .user_agent = USER_AGENT,
        .userdata = (void*)state,
    };

    const int error = sp_session_create(&session_config, &(state->spotify_state->session));
    if (SP_ERROR_OK != error) {
        ERROR("Failed to create Spotify session: %s\n", sp_error_message(error));
        return -1;
    }
    return OWL_OK;
}

//
// -- Actions -------------------------------------------------------------------------------------
//

//
// Action handler to retrieve application state
//
static void state_action(struct owl_state *state) {
    TRACE("Retrieving state....\n");
    struct evbuffer *content_buffer = evbuffer_new();

    evbuffer_add_printf(content_buffer, "{ \"state\" : %d }", state->state);
    evhttp_add_header(evhttp_request_get_output_headers(state->http_request), "Content-type", "application/json; charset=UTF-8");
    evhttp_send_reply(state->http_request, HTTP_OK, USER_AGENT, content_buffer);

    evbuffer_free(content_buffer);
}
Example #29
0
File: http.c Project: snip/aprsc
static void http_send_reply_ok(struct evhttp_request *r, struct evkeyvalq *headers, char *data, int len, int allow_compress)
{
#ifdef HAVE_LIBZ
	char *compr = NULL;
	
	/* Gzipping files below 150 bytes can actually make them larger. */
	if (len > 150 && allow_compress) {
		/* Consider returning a compressed version */
		int compr_type = http_check_req_compressed(r);
		/*
		if (compr_type)
			hlog(LOG_DEBUG, "http_send_reply_ok, client supports transfer-encoding: %s", compr_type_strings[compr_type]);
		*/
		
		if (compr_type == HTTP_COMPR_GZIP) {
			/* for small files it's possible that the output is actually
			 * larger than the input
			 */
			int oblen = len + 60;
			compr = hmalloc(oblen);
			int olen = http_compress_gzip(data, len, compr, oblen);
			/* If compression succeeded, replace buffer with the compressed one and free the
			 * uncompressed one. Add HTTP header to indicate compressed response.
			 * If the file got larger, send uncompressed.
			 */
			if (olen > 0 && olen < len) {
				data = compr;
				len = olen;
				evhttp_add_header(headers, "Content-Encoding", "gzip");
			}
		}
	}
#endif
	
	struct evbuffer *buffer = evbuffer_new();
	evbuffer_add(buffer, data, len);
	
	evhttp_send_reply(r, HTTP_OK, "OK", buffer);
	evbuffer_free(buffer);

#ifdef HAVE_LIBZ
	if (compr)
		hfree(compr);
#endif
}
Example #30
0
static void
rsp_send_error(struct evhttp_request *req, char *errmsg)
{
  struct evbuffer *evbuf;
  mxml_node_t *reply;
  mxml_node_t *status;
  mxml_node_t *node;

  /* We'd use mxmlNewXML(), but then we can't put any attributes
   * on the root node and we need some.
   */
  reply = mxmlNewElement(MXML_NO_PARENT, RSP_XML_ROOT);

  node = mxmlNewElement(reply, "response");
  status = mxmlNewElement(node, "status");

  /* Status block */
  node = mxmlNewElement(status, "errorcode");
  mxmlNewText(node, 0, "1");

  node = mxmlNewElement(status, "errorstring");
  mxmlNewText(node, 0, errmsg);

  node = mxmlNewElement(status, "records");
  mxmlNewText(node, 0, "0");

  node = mxmlNewElement(status, "totalrecords");
  mxmlNewText(node, 0, "0");

  evbuf = mxml_to_evbuf(reply);
  mxmlDelete(reply);

  if (!evbuf)
    {
      evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");

      return;
    }

  evhttp_add_header(req->output_headers, "Content-Type", "text/xml; charset=utf-8");
  evhttp_add_header(req->output_headers, "Connection", "close");
  evhttp_send_reply(req, HTTP_OK, "OK", evbuf);

  evbuffer_free(evbuf);
}