Ejemplo n.º 1
0
void web_pipeline_set(struct evhttp_request *req, void *arg) {
	moModule *module;
	struct evkeyvalq headers;
	const char *uri;

	uri = evhttp_request_uri(req);
	evhttp_parse_query(uri, &headers);

	if ( evhttp_find_header(&headers, "objectname") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing objectname");
	}

	if ( evhttp_find_header(&headers, "name") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing name");
	}

	if ( evhttp_find_header(&headers, "value") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing value");
	}

	module = module_search(evhttp_find_header(&headers, "objectname"), pipeline);
	if ( module == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "object not found");
	}

	module->property(evhttp_find_header(&headers, "name")).set(
		(const std::string &)evhttp_find_header(&headers, "value"));

	evhttp_clear_headers(&headers);
	web_message(req, "ok");
}
Ejemplo n.º 2
0
void
cb(struct evhttp_request *req, struct evbuffer *evb,void *ctx)
{
    int ret, fd;
    struct stat st;
    void *pngdata;
    const char *txt;
    struct evkeyvalq args;

    evhttp_parse_query(req->uri, &args);
    txt = evhttp_find_header(&args, "txt");

    ret = qrencode(txt);
    if (ret == 0) {
        fd = fileno(fp);
        fstat(fd, &st);
        pngdata = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
        evhttp_add_header(req->output_headers, "content-type", "image/png");
        evbuffer_add(evb, pngdata, st.st_size);
        evhttp_send_reply(req, HTTP_OK, "OK", evb);
        munmap(pngdata, st.st_size);
    } else {
        evhttp_send_reply(req, HTTP_SERVUNAVAIL, "ERROR", evb);
    }
}
Ejemplo n.º 3
0
void web_pipeline_get(struct evhttp_request *req, void *arg) {
	moModule *module;
	struct evkeyvalq headers;
	const char *uri;

	uri = evhttp_request_uri(req);
	if ( uri == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "unable to retreive uri");
	}

	evhttp_parse_query(uri, &headers);

	if ( evhttp_find_header(&headers, "objectname") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing objectname");
	}

	if ( evhttp_find_header(&headers, "name") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing name");
	}

	module = pipeline->getModuleById(evhttp_find_header(&headers, "objectname"));
	if ( module == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "object not found");
	}

	web_message(req, module->property(evhttp_find_header(&headers, "name")).asString().c_str());
	evhttp_clear_headers(&headers);
}
Ejemplo n.º 4
0
void web_pipeline_create(struct evhttp_request *req, void *arg) {
	moModule *module;
	struct evkeyvalq headers;
	const char *uri;

	uri = evhttp_request_uri(req);
	if ( uri == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "unable to retreive uri");
	}

	evhttp_parse_query(uri, &headers);

	if ( evhttp_find_header(&headers, "objectname") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing objectname");
	}

	module = moFactory::getInstance()->create(evhttp_find_header(&headers, "objectname"));
	if ( module == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "invalid objectname");
	}

	pipeline->addElement(module);

	evhttp_clear_headers(&headers);
	web_message(req, module->property("id").asString().c_str());
}
Ejemplo n.º 5
0
void request_handler(struct evhttp_request *req, void *arg)
{
    const char *uri;
    uri = evhttp_request_uri(req);

    if(strncmp(uri, "/updates/", 9) != 0){
        evhttp_send_error(req, HTTP_NOTFOUND, "Not Found");
        if (settings.verbose > 0)
            fprintf(stderr, "URL not found.. needs to be /updates/... but was %s\n", uri);
        return;
    }
    
    const char *rkey;
    struct evkeyvalq args;
    TAILQ_INIT(&args);

    evhttp_parse_query(uri, &args);
    
    rkey = evhttp_find_header(&args, "rkey");
    
    if (NULL == rkey) {
        evhttp_send_error(req, HTTP_BADREQUEST, "Bad Request");
        if (settings.verbose > 0)
            fprintf(stderr, "RKey param not found in request URI %s\n", uri);
        evhttp_clear_headers(&args);
        return;
    }
    
    fprintf(stderr, "Using RKey: %s\n", rkey);
    
    char *cached = fetch_memcached(rkey);
    
    if (NULL == cached) {
        evhttp_send_error(req, HTTP_BADREQUEST, "Bad Request");
        fprintf(stderr, "RKey %s not found in Memcache!\n", rkey);
        evhttp_clear_headers(&args);
        return;
    }
    
    int uid = atoi(cached);

    fprintf(stderr, "Great, found RKey in Memcached: %s = %s and now UID %d\n", rkey, cached, uid);
    
	struct evbuffer *buf = evbuffer_new();
    
    evhttp_add_header(req->output_headers, "Content-Type", "text/html; charset=UTF-8");
    evhttp_add_header(req->output_headers, "Connection", "keep-alive");
    evhttp_add_header(req->output_headers, "Cache-Control", "no-cache");
    
    evhttp_send_reply_start(req, HTTP_OK, "OK");
    evbuffer_add_printf(buf, "Welcome, RKey: ‘%s’\n", rkey);
    evhttp_send_reply_chunk(req, buf);
    evbuffer_free(buf);

    clients[uid] = req;
    evhttp_clear_headers(&args);
    free(cached);
    
    evhttp_connection_set_closecb( req->evcon, cleanup, &slots[uid] );
}
Ejemplo n.º 6
0
void del_cb(struct evhttp_request *req, struct evbuffer *evb, void *ctx)
{
    char *uri, *json, *id;
    struct evkeyvalq args;
    struct json_object *jsobj;

    if (rdb == NULL) {
        evhttp_send_error(req, 503, "database not connected");
        return;
    }
    uri = evhttp_decode_uri(req->uri);
    evhttp_parse_query(uri, &args);
    free(uri);

    id = (char *)evhttp_find_header(&args, "id");
    if (id == NULL) {
        evhttp_send_error(req, 400, "id is required");
        evhttp_clear_headers(&args);
        return;
    }
    
    jsobj = json_object_new_object();
    if (tcrdbtblout(rdb, id, sizeof(id))) {
        json_object_object_add(jsobj, "status", json_object_new_string("ok"));
    } else {
        db_status = tcrdbecode(rdb);
        db_error_to_json(db_status, jsobj);
    }

    finalize_json(req, evb, &args, jsobj);
}
Ejemplo n.º 7
0
//handles /ai?...
void handle_request_ai(struct evhttp_request *req, void *arg){
	global_data * global = (global_data *) arg;

	global->stats.requests++;

	request_t * aireq = new request_t();
	const char * ptr;
	struct evkeyvalq options;

	evhttp_parse_query(req->uri, &options);

	int depth = 2;
	Board board = Board(true); //start with an empty board, replacing it below if a one is supplied

	if((ptr = evhttp_find_header(&options, "l")))
		depth = atoi(ptr);
	
	if(depth < 0)	depth = 0;
	if(depth > 4)	depth = 4;

	if((ptr = evhttp_find_header(&options, "m")) && strlen(ptr) == 36)
		board = Board(ptr);

	aireq->req = req;
	aireq->boardstart = board;
	aireq->player = new PlayerNegamax3(depth);

	global->request->push(aireq);
	evhttp_clear_headers(&options);
}
Ejemplo n.º 8
0
int _get_int(struct evhttp_request *req, char *key, int def) {
	struct evkeyvalq    args;
	int ret;
	evhttp_parse_query(req->uri, &args);
	argtoi(&args, key, &ret, def);
	return ret;
} 
Ejemplo n.º 9
0
void box_cb(struct evhttp_request *req, struct evbuffer *evb, void *ctx)
{
    double lat, lng, miles, ulat, ulng, llat, llng;
    char *uri, *json;
    struct evkeyvalq args;
    struct json_object *jsobj;
    
    uri = evhttp_decode_uri(req->uri);
    evhttp_parse_query(uri, &args);
    free(uri);
    
    argtof(&args, "lat", &lat, 0);
    argtof(&args, "lng", &lng, 0);
    argtof(&args, "miles", &miles, 0);

    geo_box(lat, lng, miles, &ulat, &ulng, &llat, &llng);
    
    jsobj = json_object_new_object();
    json_object_object_add(jsobj, "ulat", json_object_new_double(ulat));
    json_object_object_add(jsobj, "ulng", json_object_new_double(ulng));
    json_object_object_add(jsobj, "llat", json_object_new_double(llat));
    json_object_object_add(jsobj, "llng", json_object_new_double(llng));

    finalize_json(req, evb, &args, jsobj);
}
/**
 *
 * @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;
}
Ejemplo n.º 11
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);
  }
}
Ejemplo n.º 12
0
void get_cb(struct evhttp_request *req, struct evbuffer *evb, void *ctx)
{
    const char *value, *name;
    char *uri, *json, *hash, *key; 
    struct evkeyvalq args;
    struct json_object *jsobj, *jsobj2, *jsobj3;
    TCMAP *cols;
    
    if (rdb == NULL) {
        evhttp_send_error(req, 503, "database not connected");
        return;
    }

    uri = evhttp_decode_uri(req->uri);
    evhttp_parse_query(uri, &args);
    free(uri);

    hash = (char *)evhttp_find_header(&args, "hash");
    key = (char *)evhttp_find_header(&args, "key");
    
    if (hash == NULL) {
        evhttp_send_error(req, 400, "hash is required");
        evhttp_clear_headers(&args);
        return;
    }
    
    jsobj = json_object_new_object();
    jsobj2 = json_object_new_object();
    cols = tcrdbtblget(rdb, hash, sizeof(hash));
    
    if (cols) {
        tcmapiterinit(cols);
        jsobj3 = json_object_new_object();
        
        
        if (key) {
            value = tcmapget2(cols, key);

            if (!value) {
                value = "";
            }
            
            json_object_object_add(jsobj2, key, json_object_new_string(value));
        } else {
            while ((name = tcmapiternext2(cols)) != NULL) {
                json_object_object_add(jsobj2, name, json_object_new_string(tcmapget2(cols, name)));
            }
        }
     
        json_object_object_add(jsobj, "status", json_object_new_string("ok"));
        json_object_object_add(jsobj, "results", jsobj2);
        
        tcmapdel(cols);
    } else {
        json_object_object_add(jsobj, "status", json_object_new_string("error"));
    }
   
    finalize_json(req, evb, &args, jsobj);
}
Ejemplo n.º 13
0
static void Request_parse_getvars(T R)
{
	struct evkeyval *val;
	R->GET = g_new0(struct evkeyvalq,1);
	evhttp_parse_query(R->uri, R->GET);
	TAILQ_FOREACH(val, R->GET, next)
		TRACE(TRACE_DEBUG,"GET: [%s]->[%s]", val->key, val->value);
}
Ejemplo n.º 14
0
void web_pipeline_remove(struct evhttp_request *req, void *arg) {
	moModule *module;
	moDataStream *ds;
	struct evkeyvalq headers;
	const char *uri;

	uri = evhttp_request_uri(req);
	if ( uri == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "unable to retreive uri");
	}

	evhttp_parse_query(uri, &headers);

	if ( evhttp_find_header(&headers, "objectname") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing objectname");
	}

	module = pipeline->getModuleById(evhttp_find_header(&headers, "objectname"));
	if ( module == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "object not found");
	}

	pipeline->stop();
	module->stop();

	// disconnect inputs
	if ( module->getInputCount() ) {
		for ( int i = 0; i < module->getInputCount(); i++ ) {
			ds = module->getInput(i);
			if ( ds == NULL )
				continue;
			ds->removeObserver(module);
		}
	}

	// disconnect output
	if ( module->getOutputCount() ) {
		for ( int i = 0; i < module->getOutputCount(); i++ ) {
			ds = module->getOutput(i);
			if ( ds == NULL )
				continue;
			ds->removeObservers();
		}
	}

	// remove element from pipeline
	pipeline->removeElement(module);

	delete module;

	web_message(req, "ok");
	evhttp_clear_headers(&headers);
}
Ejemplo n.º 15
0
void CHttpServer::http_handle_postdata(struct evhttp_request *req, void *arg)
{
	CHttpServer *pthis = (CHttpServer *)arg;
    	
    // 请求是用POST发送的,下面的evhttp_request_uri和evhttp_parse_query函数
	// 不能正确解析uri中的参数,Libevent库的BUG!
	char *decode_uri;
	struct evkeyvalq params;
	decode_uri = strdup((char *)evhttp_request_uri(req));
	evhttp_parse_query(decode_uri, &params);
	free(decode_uri);
    
	// POST
	int buffer_data_len;
	buffer_data_len = EVBUFFER_LENGTH(req->input_buffer);
	//char *post_data;
	if (buffer_data_len) {
		char *buffer_data = (char *) malloc(buffer_data_len + 1);
		memset(buffer_data, '\0', buffer_data_len + 1);
		memcpy(buffer_data, EVBUFFER_DATA(req->input_buffer), buffer_data_len);
		//post_data = (char *) EVBUFFER_DATA(req->input_buffer);
//printf("------------------------start---------------------------------------------\n");
//printf("%s\n", buffer_data);
//printf("------------------------end-----------------------------------------------\n");
		//if(NULL == buffer_data)
			//return;
		http_reponse(req, &params, 200, "OK");	
		// 转发给云评估系统
		size_t stat_code;
		char *uri = g_confvalue.url_path;
		stat_code = httpPostAsyn(uri, buffer_data, strlen(buffer_data)+1, NULL);	
		//logrun("http trans response code:[%d]", stat_code);
		// 缓存数据等待重发
		if (stat_code != 200) { //200:OK
#ifdef DEBUG
			printf("forward datas fail, datas to buffer.\n");
			//pthread_mutex_lock(&pthis->m_mutex);
			logbuf("%s", buffer_data);
			//pthread_mutex_unlock(&pthis->m_mutex);
#else
			logrun("forward datas fail, datas to buffer.");
			//pthread_mutex_lock(&pthis->m_mutex);
			logbuf("%s", buffer_data);
			//pthread_mutex_unlock(&pthis->m_mutex);
#endif
		}
		// 解析收到的json格式的OpenStack数据
		parse_openstack_data(arg, req, params, buffer_data);
		free(buffer_data);
	} else {
		logrun("rece post data nothing.");
		http_reponse(req, &params, 400, "ERROR");
	}
    
	return;
}
Ejemplo n.º 16
0
char * _get_chars (struct evhttp_request *req, char *key, char * def) {
	struct evkeyvalq args;
	char * ret;
	evhttp_parse_query(req->uri, &args);
	ret = (char *)evhttp_find_header(&args, key);
	if (ret == NULL) {
		return def;
	} 
	return ret;
}
Ejemplo n.º 17
0
void put_cb(struct evhttp_request *req, struct evbuffer *evb, void *ctx)
{
    char *uri, *id, *data, *json, *key, *value;
    double lat, lng;
    int x, y;
    char buf[16];
    struct evkeyvalq args;
    struct json_object *jsobj;
    TCMAP *cols;

    if (rdb == NULL) {
        evhttp_send_error(req, 503, "database not connected");
        return;
    }
    uri = evhttp_decode_uri(req->uri);
    evhttp_parse_query(uri, &args);
    free(uri);

    argtof(&args, "lat", &lat, 0);
    argtof(&args, "lng", &lng, 0);
    id = (char *)evhttp_find_header(&args, "id");
    data = (char *)evhttp_find_header(&args, "data");
    
    if (id == NULL) {
        evhttp_send_error(req, 400, "id is required");
        evhttp_clear_headers(&args);
        return;
    }
    
    x = (lat * 10000) + 1800000;
    y = (lng * 10000) + 1800000;
      
    cols = tcmapnew();
    tcmapput2(cols, "data", data);
    sprintf(buf, "%d", x);
    tcmapput2(cols, "x", buf);
    sprintf(buf, "%d", y);
    tcmapput2(cols, "y", buf);
    sprintf(buf, "%f", lat);
    tcmapput2(cols, "lat", buf);
    sprintf(buf, "%f", lng);
    tcmapput2(cols, "lng", buf);
    
    jsobj = json_object_new_object();
    if (tcrdbtblput(rdb, id, strlen(id), cols)) {
        json_object_object_add(jsobj, "status", json_object_new_string("ok"));
    } else {
        db_status = tcrdbecode(rdb);
        db_error_to_json(db_status, jsobj);
    }
    
    tcmapdel(cols);

    finalize_json(req, evb, &args, jsobj);
}
Ejemplo n.º 18
0
static void
http_parse_query_test(void)
{
	struct evkeyvalq headers;

	fprintf(stdout, "Testing HTTP query parsing: ");

	TAILQ_INIT(&headers);
	
	evhttp_parse_query("http://www.test.com/?q=test", &headers);
	if (validate_header(&headers, "q", "test") != 0)
		goto fail;
	evhttp_clear_headers(&headers);

	evhttp_parse_query("http://www.test.com/?q=test&foo=bar", &headers);
	if (validate_header(&headers, "q", "test") != 0)
		goto fail;
	if (validate_header(&headers, "foo", "bar") != 0)
		goto fail;
	evhttp_clear_headers(&headers);

	evhttp_parse_query("http://www.test.com/?q=test+foo", &headers);
	if (validate_header(&headers, "q", "test foo") != 0)
		goto fail;
	evhttp_clear_headers(&headers);

	evhttp_parse_query("http://www.test.com/?q=test%0Afoo", &headers);
	if (validate_header(&headers, "q", "test\nfoo") != 0)
		goto fail;
	evhttp_clear_headers(&headers);

	evhttp_parse_query("http://www.test.com/?q=test%0Dfoo", &headers);
	if (validate_header(&headers, "q", "test\rfoo") != 0)
		goto fail;
	evhttp_clear_headers(&headers);

	fprintf(stdout, "OK\n");
	return;
fail:
	fprintf(stdout, "FAILED\n");
	exit(1);
}
Ejemplo n.º 19
0
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;
}
Ejemplo n.º 20
0
void web_pipeline_stream(struct evhttp_request *req, void *arg) {
	struct timeval when = { 0, 20 };
	struct evkeyvalq headers;
	const char *uri;
	int	idx = 0;
	moModule *module = NULL;

	uri = evhttp_request_uri(req);
	evhttp_parse_query(uri, &headers);

	if ( evhttp_find_header(&headers, "objectname") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing objectname");
	}

	module = module_search(evhttp_find_header(&headers, "objectname"), pipeline);
	if ( module == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "object not found");
	}

	if ( evhttp_find_header(&headers, "index") != NULL )
		idx = atoi(evhttp_find_header(&headers, "index"));

	if ( idx < 0 || idx >= module->getOutputCount() ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "invalid index");
	}

	struct chunk_req_state *state = (struct chunk_req_state*)malloc(sizeof(struct chunk_req_state));

	memset(state, 0, sizeof(struct chunk_req_state));
	state->req = req;
	state->closed = false;
	state->stream = new otStreamModule();
	state->delay = 100;

	if ( evhttp_find_header(&headers, "scale") != NULL )
		state->stream->property("scale").set(evhttp_find_header(&headers, "scale"));

	if ( evhttp_find_header(&headers, "delay") != NULL )
		state->delay = atoi(evhttp_find_header(&headers, "delay"));

	state->stream->setInput(module->getOutput(idx));

	evhttp_add_header(req->output_headers, "Content-Type", "multipart/x-mixed-replace; boundary=mjpegstream");
	evhttp_send_reply_start(req, HTTP_OK, "Everything is fine");

	evhttp_connection_set_closecb(req->evcon, web_pipeline_stream_close, state);

	event_once(-1, EV_TIMEOUT, web_pipeline_stream_trickle, state, &when);

}
Ejemplo n.º 21
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);	
}
Ejemplo n.º 22
0
void web_pipeline_connect(struct evhttp_request *req, void *arg) {
	moModule *in, *out;
	int inidx = 0, outidx = 0;
	struct evkeyvalq headers;
	const char *uri;

	uri = evhttp_request_uri(req);
	if ( uri == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "unable to retreive uri");
	}

	evhttp_parse_query(uri, &headers);

	if ( evhttp_find_header(&headers, "out") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing out");
	}

	if ( evhttp_find_header(&headers, "in") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing in");
	}

	if ( evhttp_find_header(&headers, "outidx") != NULL )
		outidx = atoi(evhttp_find_header(&headers, "outidx"));
	if ( evhttp_find_header(&headers, "inidx") != NULL )
		inidx = atoi(evhttp_find_header(&headers, "inidx"));

	in = pipeline->getModuleById(evhttp_find_header(&headers, "in"));
	out = pipeline->getModuleById(evhttp_find_header(&headers, "out"));

	if ( in == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "in object not found");
	}

	if ( out == NULL && strcmp(evhttp_find_header(&headers, "out"), "NULL") != 0 ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "out object not found");
	}

	if ( strcmp(evhttp_find_header(&headers, "out"), "NULL") == 0 )
		in->setInput(NULL, inidx);
	else
		in->setInput(out->getOutput(outidx), inidx);

	evhttp_clear_headers(&headers);
	web_message(req, "ok");
}
Ejemplo n.º 23
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);
}
Ejemplo n.º 24
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);
}
Ejemplo n.º 25
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);
	}
Ejemplo n.º 26
0
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;
}
void
SearchapiServiceClientEvhttp::searchHandler( struct evhttp_request *req, 
                                             void *arg )
{
  SearchapiServiceClientEvhttp *instance = static_cast<SearchapiServiceClientEvhttp*>( arg );
  struct evbuffer *buf;
  std::string result;

  buf = evbuffer_new();
  if (buf) {
    struct evkeyvalq headers;
    TAILQ_INIT(&headers);
    std::cerr << std::string(req->uri) << std::endl;
    evhttp_parse_query(req->uri, &headers);

    std::string key = "q";
    std::string val = "";

    if (BBRpcClientEvhttp::find_header(&headers, key, val))
    {
      char *escaped_val = evhttp_htmlescape(val.c_str());
      std::cerr << escaped_val << std::endl;
      result = instance->search(escaped_val);
      evhttp_add_header(req->output_headers, "Content-type","application/x-javascript; charset=utf-8");
      std::stringstream result_size;
      result_size << result.size();
      evhttp_add_header(req->output_headers, "Content-Length", result_size.str().c_str());
      evbuffer_add_printf(buf, "%s", result.c_str());
      free(escaped_val);
    }
    else
    {
      std::cerr << "not find" << std::endl;
    }
    evhttp_clear_headers(&headers);
    evhttp_send_reply(req, HTTP_OK, "OK", buf);
  }
  else
  {
    std::cerr << "failed to create response buffer" << std::endl;
  }
}
Ejemplo n.º 28
0
void distance_cb(struct evhttp_request *req, struct evbuffer *evb, void *ctx)
{
    double lat1, lng1, lat2, lng2;
    char *uri, *json;
    struct evkeyvalq args;
    struct json_object *jsobj;
    
    uri = evhttp_decode_uri(req->uri);
    evhttp_parse_query(uri, &args);
    free(uri);
    
    argtof(&args, "lat1", &lat1, 0);
    argtof(&args, "lng1", &lng1, 0);
    argtof(&args, "lat2", &lat2, 0);
    argtof(&args, "lng2", &lng2, 0);

    jsobj = json_object_new_object();
    json_object_object_add(jsobj, "distance", json_object_new_double(geo_distance(lat1, lng1, lat2, lng2)));

    finalize_json(req, evb, &args, jsobj);
}
Ejemplo n.º 29
0
void web_factory_desribe(struct evhttp_request *req, void *arg) {
	std::map<std::string, moProperty*>::iterator it;
	cJSON *root, *mod, *properties, *io, *array;
	moDataStream *ds;
	moModule *module;
	struct evkeyvalq headers;
	const char *uri;

	uri = evhttp_request_uri(req);
	evhttp_parse_query(uri, &headers);

	if ( evhttp_find_header(&headers, "name") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing name");
	}

	module = moFactory::getInstance()->create(evhttp_find_header(&headers, "name"));
	if ( module == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "invalid name");
	}

	root = cJSON_CreateObject();
	cJSON_AddNumberToObject(root, "success", 1);
	cJSON_AddStringToObject(root, "message", "ok");
	cJSON_AddItemToObject(root, "describe", mod=cJSON_CreateObject());

	cJSON_AddStringToObject(mod, "name", module->getName().c_str());
	cJSON_AddStringToObject(mod, "description", module->getDescription().c_str());
	cJSON_AddStringToObject(mod, "author", module->getAuthor().c_str());
	cJSON_AddNumberToObject(mod, "running", module->isStarted() ? 1 : 0);
	cJSON_AddItemToObject(mod, "properties", properties=cJSON_CreateObject());

	for ( it = module->getProperties().begin(); it != module->getProperties().end(); it++ ) {
		cJSON_AddStringToObject(properties, it->first.c_str(),
				it->second->asString().c_str());
	}

	if ( module->getInputCount() ) {
		cJSON_AddItemToObject(mod, "inputs", array=cJSON_CreateArray());
		for ( int i = 0; i < module->getInputCount(); i++ ) {
			ds = module->getInput(i);
			cJSON_AddItemToArray(array, io=cJSON_CreateObject());
			cJSON_AddNumberToObject(io, "index", i);
			cJSON_AddStringToObject(io, "name", module->getInputInfos(i)->getName().c_str());
			cJSON_AddStringToObject(io, "type", module->getInputInfos(i)->getType().c_str());
		}
	}

	if ( module->getOutputCount() ) {
		cJSON_AddItemToObject(mod, "outputs", array=cJSON_CreateArray());
		for ( int i = 0; i < module->getOutputCount(); i++ ) {
			ds = module->getOutput(i);
			cJSON_AddItemToArray(array, io=cJSON_CreateObject());
			cJSON_AddNumberToObject(io, "index", i);
			cJSON_AddStringToObject(io, "name", module->getOutputInfos(i)->getName().c_str());
			cJSON_AddStringToObject(io, "type", module->getOutputInfos(i)->getType().c_str());
		}
	}

	delete module;

	evhttp_clear_headers(&headers);
	web_json(req, root);
}
Ejemplo n.º 30
0
static void
generic_handler(struct evhttp_request *req, void *arg)
{
  struct evkeyvalq args;
  thd_data *thd = arg;

  if (!loop) {
    event_base_loopexit(thd->base, NULL);
    return;
  }
  if (!req->uri) { return; }

  {
    char *uri = evhttp_decode_uri(req->uri);
    evhttp_parse_query(uri, &args);
    free(uri);
  }

  {
    struct evbuffer *res_buf;
    if (!(res_buf = evbuffer_new())) {
      err(1, "failed to create response buffer");
    }

    evhttp_add_header(req->output_headers, "Connection", "close");

    log_send(req->output_headers, res_buf, thd, &args);
    evhttp_send_reply(req, HTTP_OK, "OK", res_buf);
    evbuffer_free(res_buf);
    /* logging */
    {
      if (thd->log_base_path) {
        if (!thd->log_file) {
          time_t n;
          struct tm *t_st;
          char p[PATH_MAX + 1];

          time(&n);
          t_st = localtime(&n);

          snprintf(p, PATH_MAX, "%s%04d%02d%02d%02d%02d%02d-%02d",
            thd->log_base_path,
            t_st->tm_year + 1900, t_st->tm_mon + 1, t_st->tm_mday,
            t_st->tm_hour, t_st->tm_min, t_st->tm_sec, thd->thread_id);

          if (!(thd->log_file = fopen(p, "a"))) {
            print_error("cannot open log_file %s.", p);
          } else {
            thd->log_count = 0;
          }
        }
        if (thd->log_file) {
          fprintf(thd->log_file, "%s\n", req->uri);
          if (++thd->log_count >= LOG_SPLIT_LINES) {
            fclose(thd->log_file);
            thd->log_file = NULL;
          }
        }
      }
    }
  }
  evhttp_clear_headers(&args);
}