示例#1
0
static struct evhttp *
http_setup(short *pport, struct event_base *base)
{
	int i;
	struct evhttp *myhttp;
	short port = -1;

	/* Try a few different ports */
	myhttp = evhttp_new(base);
	for (i = 0; i < 50; ++i) {
		if (evhttp_bind_socket(myhttp, "127.0.0.1", 8080 + i) != -1) {
			port = 8080 + i;
			break;
		}
	}

	if (port == -1)
		event_errx(1, "Could not start web server");

	/* Register a callback for certain types of requests */
	evhttp_set_cb(myhttp, "/test", http_basic_cb, NULL);
	evhttp_set_cb(myhttp, "/chunked", http_chunked_cb, NULL);
	evhttp_set_cb(myhttp, "/postit", http_post_cb, NULL);
	evhttp_set_cb(myhttp, "/largedelay", http_large_delay_cb, NULL);
	evhttp_set_cb(myhttp, "/", http_dispatcher_cb, NULL);

	*pport = port;
	return (myhttp);
}
示例#2
0
int
main (int argc, char **argv)
{
	struct event_base *base = event_base_new();
	struct evhttp *http = evhttp_new(base);
	int c;

	unsigned short port = 8080;
	while ((c = getopt(argc, argv, "p:l:")) != -1) {
		switch (c) {
		case 'p':
			port = atoi(optarg);
			break;
		case 'l':
			content_len = atol(optarg);
			if (content_len == 0) {
				fprintf(stderr, "Bad content length\n");
				exit(1);
			}
			break;
		default:
			fprintf(stderr, "Illegal argument \"%c\"\n", c);
			exit(1);
		}
	}

#ifndef WIN32
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
		return (1);
#endif

	content = malloc(content_len);
	if (content == NULL) {
		fprintf(stderr, "Cannot allocate content\n");
		exit(1);
	} else {
		int i = 0;
		for (i = 0; i < content_len; ++i)
			content[i] = (i & 255);
	}

	evhttp_set_cb(http, "/ind", http_basic_cb, NULL);
	fprintf(stderr, "/ind - basic content (memory copy)\n");

#ifdef _EVENT2_EVENT_H_
	evhttp_set_cb(http, "/ref", http_ref_cb, NULL);
	fprintf(stderr, "/ref - basic content (reference)\n");
#endif

	fprintf(stderr, "Serving %d bytes on port %d\n",
	    (int)content_len, port);

	evhttp_bind_socket(http, "0.0.0.0", port);

	event_base_dispatch(base);

	/* NOTREACHED */
	return (0);
}
示例#3
0
文件: avon.c 项目: AutonomyLab/avon
int av_register_model( const char* name, 
											 const char* prototype,
											 av_interface_t interface, 
											 const char* parent_name, 
											 void* handle )
{
  if( _av.verbose) 
	 printf( "[Avon] registering \"%s\" child of \"%s\"\n", name, parent_name );
  
  tree_insert_model( name, prototype, interface, parent_name );

  // now install callbacks for this node

  char buf[256];
  
	// PVA requests
  snprintf( buf, 256, "/%s/pva", name );
  evhttp_set_cb( _av.eh, buf, (evhttp_cb_t)handle_pva, handle );
	
	// geometry requests
  snprintf( buf, 256, "/%s/geom", name );
  evhttp_set_cb( _av.eh, buf, (evhttp_cb_t)handle_geom, handle );
  
	// data requests
  interface_handle_pair_t* ihp = malloc(sizeof(ihp));
  assert(ihp);
  ihp->interface = interface;
  ihp->handle = handle;
  
  snprintf( buf, 256, "/%s/data", name );
  evhttp_set_cb( _av.eh, buf, (evhttp_cb_t)handle_data, ihp );
	
	// everything requests (no property name)
	snprintf( buf, 256, "/%s", name );
  evhttp_set_cb( _av.eh, buf, (evhttp_cb_t)handle_summary, ihp );
	
/*   snprintf( buf, 256, "/%s/cmd", name ); */
/*   evhttp_set_cb( av->eh, buf, (evhttp_cb_t)handle_cmd[interface], ihp ); */
  
  snprintf( buf, 256, "/%s/cfg", name ); 
  evhttp_set_cb( _av.eh, buf, (evhttp_cb_t)handle_cfg, ihp );	 
  
	//print_table();

	//char* xdr = xdr_tree( NULL );
	//printf( "xdr: %s\n", xdr );
	//free(xdr);

	return 0; // ok
}
示例#4
0
文件: http.c 项目: pearsonalan/stats
int http_init(struct http* http, struct event_base *base, struct metrics *metrics)
{
    char workdir[256];
    char docroot[256];
    char listen_addr[256];

    memset(http, 0, sizeof(struct http));

    http->metrics = metrics;

    /* TODO: read port from config file */
    http->port = 4000;

    /* TODO: read docroot from config file */
    if (getcwd(workdir,sizeof(workdir)) == NULL)
    {
        printf("Could not get working directory\n");
        return ERROR_FAIL;
    }
    snprintf(docroot, sizeof(docroot), "%s/docroot", workdir);
    http->docroot = strdup(docroot);

    /* TODO: should also read a bind address */

    /* Create a new evhttp object to handle requests. */
    http->http = evhttp_new(base);
    if (!http->http)
    {
        printf("could not create evhttp.\n");
        return ERROR_FAIL;
    }

    evhttp_set_cb(http->http, "/metrics", http_metrics_request_cb, http);
    evhttp_set_cb(http->http, "/list", http_list_request_cb, http);

    evhttp_set_gencb(http->http, http_document_request_cb, http);

    /* Now we tell the evhttp what port to listen on */
    http->handle = evhttp_bind_socket_with_handle(http->http, "0.0.0.0", http->port);
    if (!http->handle)
    {
        printf("couldn't bind to http port %d.\n", (int)http->port);
        return ERROR_FAIL;
    }

    if (http_get_address(http, listen_addr, sizeof(listen_addr)) == S_OK)
        printf("http: listening at %s\n", listen_addr);

    return S_OK;
}
示例#5
0
int main(int argc, char** argv) {
  (void) signal(SIGINT, ex_program);
  event_init();
  server = evhttp_new(0);
  
  if (!server) {
    fprintf(stderr,"[ERROR]\tError creating the server\n");
    return 1;
  }
  int rc = evhttp_bind_socket(server, "127.0.0.1", 30080);

  if (rc) {
    fprintf(stderr, "[ERROR]\tError binding server to port!!!\n");
    return 1;
  }

  /* Add a handler to handle the request */
  /* default handler */
  evhttp_set_cb(server, "/HEST", generic_request_handler, NULL);
  evhttp_set_gencb(server, generic_request_handler, NULL);
  
  fprintf(stderr, "[INFO]\tThe server is totally waiting for real!!!\n");
  event_dispatch();  /* Brooom, brooom */

  return 0;
}
示例#6
0
int serve(int port) {
    struct event_base *base = event_base_new();
    if (!base) {
        puts("could not initialize event_base");
        abort();
    }

    struct evhttp *http = evhttp_new(base);
    if (!http) {
        puts("could not initialize evhttp");
        abort();
    }

    evhttp_set_cb(http, "/master", get_master, NULL); // master
    evhttp_set_gencb(http, get_master_pgn, NULL);     // master/pgn/{8}

    struct evhttp_bound_socket *socket =
        evhttp_bind_socket_with_handle(http, "127.0.0.1", port);
    if (!socket) {
        printf("could not bind socket to http://127.0.0.1:%d/\n", port);
        return 1;
    }

    printf("listening on http://127.0.0.1:%d/ ...\n", port);

    return event_base_dispatch(base);
}
示例#7
0
struct json_rpc_tt *json_rpc_tt_http_new(struct json_rpc *jr, struct evhttp *eh, char *uri)
{
	struct json_rpc_tt *jt = json_rpc_tt_new(jr);
	if (jt == NULL)
		return NULL;

	struct jrpc_http *jh = (struct jrpc_http *)malloc(sizeof(struct jrpc_http));
	if (jh == NULL) {
		free(jt);
		return NULL;
	}

	jh->uri = strdup(uri);
	if (jh->uri == NULL) {
		free(jt);
		free(jh);
		return NULL;
	}

	jh->eh = eh;

	jt->impl = jh;
	jt->write = tt_http_write;
	jt->free = http_free;

	evhttp_set_cb(eh, uri, json_rpc_call, jt);

	return jt;
}
示例#8
0
 static void HHVM_METHOD(EventHttp, setCallback, const String &path, const Object &cb, const Variant &arg) {
     EventHttpResourceData *resource_data = FETCH_RESOURCE(this_, EventHttpResourceData, s_event_http);        ;
     cb.get()->incRefCount();
     resource_data->setCallback(cb.get());
     resource_data->setCallbackArg(arg);
     evhttp_set_cb((evhttp_t *)resource_data->getInternalResourceData(), path.c_str(), event_http_cb, (void *) resource_data);
 }
示例#9
0
TEvhttpServer::TEvhttpServer(boost::shared_ptr<TAsyncBufferProcessor> processor, int port)
  : processor_(processor), eb_(NULL), eh_(NULL) {
  // Create event_base and evhttp.
  eb_ = event_base_new();
  if (eb_ == NULL) {
    throw TException("event_base_new failed");
  }
  eh_ = evhttp_new(eb_);
  if (eh_ == NULL) {
    event_base_free(eb_);
    throw TException("evhttp_new failed");
  }

  // Bind to port.
  int ret = evhttp_bind_socket(eh_, NULL, port);
  if (ret < 0) {
    evhttp_free(eh_);
    event_base_free(eb_);
    throw TException("evhttp_bind_socket failed");
  }

  // Register a handler.  If you use the other constructor,
  // you will want to do this yourself.
  // Don't forget to unregister before destorying this TEvhttpServer.
  evhttp_set_cb(eh_, "/", request, (void*)this);
}
int main (void) {
	struct event_base *ebase;
	struct evhttp *server;

	// Create a new event handler
	ebase = event_base_new ();;

	// Create a http server using that handler
	server = evhttp_new (ebase);

	// Limit serving GET requests
	evhttp_set_allowed_methods (server, EVHTTP_REQ_GET);

	// Set a test callback, /testing
	evhttp_set_cb (server, "/testing", testing, 0);

	// Set the callback for anything not recognized
	evhttp_set_gencb (server, notfound, 0);

	// Listen locally on port 32001
	if (evhttp_bind_socket (server, "127.0.0.1", 32001) != 0)
		errx (1, "Could not bind to 127.0.0.1:32001");

	// Start processing queries
	event_base_dispatch(ebase);

	// Free up stuff
	evhttp_free (server);

	event_base_free (ebase);
}
示例#11
0
SinoparserServer::SinoparserServer(std::string address, int port, Database& ndb) {

    db = ndb;

    struct event_base *base = event_init();
    struct evhttp *server = evhttp_new(base);
    int res = evhttp_bind_socket(server, address.c_str(), port);

    if (res != 0) {
        std::cout <<  "[ERROR] Could not start http server!" << std::endl;
        return;
    }
    db.debug();

    evhttp_set_gencb(server, http_callback_default, this);
    evhttp_set_cb(server, "/pinyin", http_pinyin_callback, this);
    evhttp_set_cb(server, "/jyutping", http_jyutping_callback, this);
    evhttp_set_cb(server, "/trad", http_trad_callback, this);
    evhttp_set_cb(server, "/simp", http_simp_callback, this);
    evhttp_set_cb(server, "/guess_script", http_guess_script_callback, this);
    evhttp_set_cb(server, "/change_script", http_change_script_callback, this);
    evhttp_set_cb(server, "/all", http_all_callback, this);

    event_base_dispatch(base);
}
int
task_http_proxy(void) {
    struct event_base *base;
    struct evhttp *http;
    struct evhttp_bound_socket *handle;

    unsigned short port = PORT;

    log_write(INFO, "http-server: http proxy initialize.\n");

    /* As you konw */
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        return (1);

    if (signal(SIGCHLD, sig_chld) == SIG_ERR)
        return (1);

    /* Create a new base evObject */
    base = event_base_new();
    if (!base) {
        log_write(ERROR, "http-server: Couldn't create an event_base: exiting\n");
        return 1;
    }

    /* Create a new evhttp object to handle requests. */
    http = evhttp_new(base);
    if (!http) {
        log_write(ERROR, "http-server: Couldn't create evhttp. Exiting.\n");
        return 1;
    }

    /*
     * The path /post support post method
     * Receive shell command by post body
     */
    evhttp_set_cb(http, "/post", post_command_cb, NULL);

    /* We want to accept arbitrary requests, so we need to set a "generic"
     * cb.  We can also add callbacks for specific paths. */
    evhttp_set_gencb(http, other_cb, NULL);

    /* Now we tell the evhttp what port to listen on */
    handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);

    if (!handle) {
        log_write(ERROR, "http-server: Couldn't bind to port %d. Exiting.\n", (int)port);
        return 1;
    }

    log_write(INFO, "http-server: http proxy initialized done.\n");
    event_base_dispatch(base);

    return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */
示例#13
0
int upnpc_event_subscribe(upnpc_device_t * p)
{
	char hostname[MAXHOSTNAMELEN+1];
	char hostname_port[MAXHOSTNAMELEN+1+6];
	unsigned short port;
	char * path;
	unsigned int scope_id;
	struct evhttp_request * req;
	struct evkeyvalq * headers;
	char callback_header[7+15+1+5+9+2+1];

	if(p->parent->http_server == NULL) {
		/* HTTP server to receive event notifications */
		p->parent->http_server = evhttp_new(p->parent->base);
		if(p->parent->http_server == NULL) {
			debug_printf("evhttp_new() FAILED\n");
			return -1;
		}
		evhttp_set_ext_method_cmp(p->parent->http_server, ext_methods_cb);
		evhttp_set_allowed_methods(p->parent->http_server, EVHTTP_REQ_NOTIFY);
		evhttp_set_cb(p->parent->http_server, "/evt_conn", upnpc_event_conn_req, p);
		if(evhttp_bind_socket(p->parent->http_server, p->parent->local_address, p->parent->local_port) < 0) {
			debug_printf("evhttp_bind_socket() FAILED\n");
			return -1;
		}
	}
	/*if(!parseURL(p->event_cif_url, hostname, &port, &path, &scope_id)) {*/
	if(!parseURL(p->event_conn_url, hostname, &port, &path, &scope_id)) {
		return -1;
	}
	if(port != 80)
		snprintf(hostname_port, sizeof(hostname_port), "%s:%hu", hostname, port);
	else
		strncpy(hostname_port, hostname, sizeof(hostname_port));
	if(p->soap_conn == NULL) {
		p->soap_conn = evhttp_connection_base_new(p->parent->base, NULL, hostname, port);
	}
	evhttp_connection_set_ext_method_cmp(p->soap_conn, ext_methods_cb);
	req = evhttp_request_new(upnpc_subscribe_response, p);
	headers = evhttp_request_get_output_headers(req);
	/*buffer = evhttp_request_get_output_buffer(req);*/
	evhttp_add_header(headers, "Host", hostname_port);
	/*evhttp_add_header(headers, "User-Agent", "***");*/
	snprintf(callback_header, sizeof(callback_header), "<http://%s:%hu/evt_conn>", p->parent->local_address, p->parent->local_port);
	evhttp_add_header(headers, "Callback", callback_header);
	evhttp_add_header(headers, "NT", "upnp:event");
	/*evhttp_add_header(headers, "NTS", "");*/
	evhttp_add_header(headers, "Timeout", "3600");
	/*evbuffer_add(buffer, body, body_len);*/
	evhttp_make_request(p->soap_conn, req, EVHTTP_REQ_SUBSCRIBE, path);
	p->state |= UPNPC_DEVICE_SOAP_REQ;
	return 0;
}
示例#14
0
int main(int argc, char **argv)
{
	struct evhttp *httpd;

	event_init();
	httpd = evhttp_start(argv[argc-2], atoi(argv[argc-1]));
	evhttp_set_cb(httpd, "/request_sys/", sys_handler, NULL); 
/* Set a callback for all other requests. */
	evhttp_set_gencb(httpd, notfound_hander, NULL);
event_dispatch();    /* Not reached in this code as it is now. */
	evhttp_free(httpd);    
	return 0;
}
示例#15
0
文件: rpc.c 项目: dyustc/searaft
int init_rpc_server(struct rpc_context *rpc_context, const struct rpc_target *dest) {
    //should check dest->proto and do http handling only when proto=HTTP
    rpc_context->http = evhttp_new(rpc_context->base);
    if(!rpc_context->http) {
        return 1;
    }
    evhttp_set_cb(rpc_context->http, "/rpc", server_rpc_cb, rpc_context);

    rpc_context->handle = evhttp_bind_socket_with_handle(
        rpc_context->http, dest->host, dest->port);
    if(!rpc_context->handle) {
        evhttp_free(rpc_context->http);
        return 1;
    }

    return 0;
}
示例#16
0
int main(int argc,char** argv){

	evbase = event_base_new(); 
	if(!evbase){ 
		fprintf(stderr, "create evbase error!\n");
		exit(0); 
	}

	// 创建http server实例
	ev_ssl = evhttp_new(evbase);
	if(!ev_ssl){ 
		exit(0); 
	}

	// openssl 初始化 
	SSL_library_init(); 
	ERR_load_crypto_strings(); 
	SSL_load_error_strings(); 
	OpenSSL_add_all_algorithms();

	if (SSLeay() != OPENSSL_VERSION_NUMBER){ 
	
	}

	ev_ssl->ctx = get_ssl_ctx(certfile_url.c_str(),keyfile_url.c_str()); 
	ev_ssl->ssl_cb = bufferevent_openssl_socket_new;

	std::string ev_ssl_ip="192.168.1.10"; int ev_ssl_port = 8080;

	// evhttp_bind_socket_with_handle这个函数在原基础上追加一个参数,标示http server知否支持ssl(0:不支持 1:支持) 
	struct evhttp_bound_socket *ssl_handle = evhttp_bind_socket_with_handle(ev_ssl, ev_ssl_ip.c_str(), ev_ssl_port,1); 
	if(!ssl_handle){ 
		exit(0); 
	}
	
	struct evconnlistener *ssl_listener = evhttp_bound_socket_get_listener(ssl_handle); 
	evconnlistener_set_error_cb(ssl_listener, ssl_accept_error_cb);

	evhttp_set_cb(ev_ssl, "/ping", ping_handler, NULL);

	event_base_dispatch(evbase);

	evhttp_free(ev_ssl); event_base_free(evbase);

	return 0; 
}
示例#17
0
文件: main.c 项目: wangkangluo1/vim
int
main(int argc, char **argv)
{
        struct evhttp *httpd;

        event_init();
        httpd = evhttp_start("0.0.0.0", 8080);

        /* Set a callback for requests to "/". */
        evhttp_set_cb(httpd, "/", root_handler, NULL);

        /* Set a callback for all other requests. */
        evhttp_set_gencb(httpd, generic_handler, NULL);

        event_dispatch();

        /* Not reached in this code as it is now. */

        evhttp_free(httpd);

        return 0;
}
示例#18
0
文件: HTTPd.c 项目: Youx/craftd
CDHTTPd*
CD_CreateHTTPd (CDServer* server)
{
    CDHTTPd* self = CD_malloc(sizeof(CDHTTPd));

    if (pthread_attr_init(&self->attributes) != 0) {
        CD_abort("pthread attribute failed to initialize");
    }

    if (pthread_attr_setdetachstate(&self->attributes, PTHREAD_CREATE_DETACHED) != 0) {
        CD_abort("pthread attribute failed to set in detach state");
    }

    self->server      = server;
    self->event.base  = event_base_new();
    self->event.httpd = evhttp_new(self->event.base);

    evhttp_set_cb(self->event.httpd, "/rpc/json", (void (*)(struct evhttp_request*, void*)) cd_JSONRequest, server);
    evhttp_set_gencb(self->event.httpd, (void (*)(struct evhttp_request*, void*)) cd_StaticRequest, server);

    return self;
}
示例#19
0
int main(int argc, char **argv)
{
    init_app(argc, argv, "osd");

    event_init();

    char *hdd_cfg = cfg_getstr("HDD_CONF_FILENAME", "etc/hdd.conf");
    hdd_init(hdd_cfg);

    char *self_host = cfg_getstr("OSD2CLIENT_LISTEN_HOST", "*");
    int self_port = cfg_getint32("OSD2CLIENT_LISTEN_PORT", 9527);
    rpc_client_setup(self_host, self_port, MACHINE_OSD);

    struct evhttp *httpd;

    char *listen_host = cfg_getstr("OSD2CLIENT_LISTEN_HOST", "*");
    int port = cfg_getint32("OSD2CLIENT_LISTEN_PORT", 9527);

    httpd = evhttp_start(listen_host, port);
    if (httpd == NULL) {
        logging(LOG_ERROR, "start server error %m");
        exit(1);
    } else {
        printf("Start osd at %s:%d\n", listen_host, port);
    }
    evhttp_set_cb(httpd, "/shutdown", shutdown_handler, NULL);
    evhttp_set_gencb(httpd, gen_handler, NULL);


    struct timeval five_seconds = {2,0};
    struct event *update_clustermap_event= event_new(NULL, -1, EV_PERSIST, update_clustermap_from_cmgr_on_timer_cb, NULL);
    event_add(update_clustermap_event, &five_seconds);

    event_dispatch();

    evhttp_free(httpd);
    return 0;
}
示例#20
0
StatSrv *stat_srv_create (Application *app)
{
    StatSrv *stat_srv;
    
    stat_srv = g_new0 (StatSrv, 1);
    stat_srv->app = app;
    stat_srv->q_op_history = g_queue_new ();
    stat_srv->boot_time = time (NULL);

    // stats server is disabled
    if (!conf_get_boolean (application_get_conf (stat_srv->app), "statistics.enabled")) {
        return stat_srv;
    }

    stat_srv->http = evhttp_new (application_get_evbase (app));
    if (!stat_srv->http) {
        LOG_err (STAT_LOG, "Failed to create statistics server !");
        return NULL;
    }

    // bind
    if (evhttp_bind_socket (stat_srv->http, 
        conf_get_string (application_get_conf (stat_srv->app), "statistics.host"),
        conf_get_int (application_get_conf (stat_srv->app), "statistics.port")) == -1) {
        LOG_err (STAT_LOG, "Failed to bind statistics server to  %s:%d",
            conf_get_string (application_get_conf (stat_srv->app), "statistics.host"),
            conf_get_int (application_get_conf (stat_srv->app), "statistics.port")
        );
        return NULL;
    }

    // install handlers
    evhttp_set_cb (stat_srv->http, conf_get_string (application_get_conf (stat_srv->app), "statistics.stats_path"), stat_srv_on_stats_cb, stat_srv);
    evhttp_set_gencb (stat_srv->http, stat_srv_on_gen_cb, stat_srv);

    return stat_srv;
}
示例#21
0
int main(int argc, char* argv[])
{
	welcome();
	init(argc, argv);

	ServerConfig::max_channels = conf->get_num("front.max_channels");
	ServerConfig::max_subscribers_per_channel = conf->get_num("front.max_subscribers_per_channel");
	ServerConfig::channel_buffer_size = conf->get_num("front.channel_buffer_size");
	ServerConfig::channel_timeout = conf->get_num("front.channel_timeout");
	ServerConfig::polling_timeout = conf->get_num("front.polling_timeout");
	if (ServerConfig::polling_timeout <= 0){
		log_fatal("Invalid polling_timeout!");
		exit(0);
	}
	if (ServerConfig::channel_timeout <= 0){
		ServerConfig::channel_timeout = (int)(0.5 * ServerConfig::polling_timeout);
	}

	ServerConfig::polling_idles = ServerConfig::polling_timeout / CHANNEL_CHECK_INTERVAL;
	ServerConfig::channel_idles = ServerConfig::channel_timeout / CHANNEL_CHECK_INTERVAL;

	log_info("ServerConfig::max_channels =%d", ServerConfig::max_channels);
	log_info("ServerConfig::max_subscribers_per_channel=%d", ServerConfig::max_subscribers_per_channel);
	log_info("ServerConfig::polling_timeout=%d", ServerConfig::polling_timeout);
	log_info("ServerConfig::polling_idles =%d", ServerConfig::polling_idles);
	log_info("ServerConfig::channel_buffer_size=%d", ServerConfig::channel_buffer_size);
	log_info("ServerConfig::channel_timeout=%d", ServerConfig::channel_timeout);
	log_info("ServerConfig::channel_idles =%d", ServerConfig::channel_idles);
	serv = new Server();
	ip_filter = new IpFilter();


	{
		// /pub?cname=abc&content=hi
		// content must be json encoded string without leading quote and trailing quote
		// TODO: multi_pub
		evhttp_set_cb(admin_http, "/pub", pub_handler, NULL);
		// pub raw content(not json encoded)
		evhttp_set_cb(admin_http, "/push", push_handler, NULL);
		// 分配通道, 返回通道的id和token
		// /sign?cname=abc[&expires=60]
		// wait 60 seconds to expire before any sub
		evhttp_set_cb(admin_http, "/sign", sign_handler, NULL);
		// 销毁通道
		// /close?cname=abc
		evhttp_set_cb(admin_http, "/close", close_handler, NULL);
		// 销毁通道
		// /clear?cname=abc
		evhttp_set_cb(admin_http, "/clear", clear_handler, NULL);
		// 获取通道的信息
		// /info?[cname=abc], or TODO: /info?cname=a,b,c
		evhttp_set_cb(admin_http, "/info", info_handler, NULL);
		// 判断通道是否处于被订阅状态(所有订阅者断开连接一定时间后, 通道才转为空闲状态)
		// /check?cname=abc, or TODO: /check?cname=a,b,c
		evhttp_set_cb(admin_http, "/check", check_handler, NULL);

		// 订阅通道的状态变化信息, 如创建通道(第一个订阅者连接时), 关闭通道.
		// 通过 endless chunk 返回.
		evhttp_set_cb(admin_http, "/psub", psub_handler, NULL);

		std::string admin_ip;
		int admin_port = 0;
		parse_ip_port(conf->get_str("admin.listen"), &admin_ip, &admin_port);
		struct evhttp_bound_socket *handle;
		handle = evhttp_bind_socket_with_handle(admin_http, admin_ip.c_str(), admin_port);
		if (!handle){
			log_fatal("bind admin_port %d error! %s", admin_port, strerror(errno));
			exit(0);
		}
		log_info("admin server listen on %s:%d", admin_ip.c_str(), admin_port);

		struct evconnlistener *listener = evhttp_bound_socket_get_listener(handle);
		evconnlistener_set_error_cb(listener, accept_error_cb);
		// TODO: modify libevent, add evhttp_set_accept_cb()
	}

	// init admin ip_filter
	{
		Config *cc = (Config *)conf->get("admin");
		if (cc != NULL){
			std::vector<Config *> *children = &cc->children;
			std::vector<Config *>::iterator it;
			for (it = children->begin(); it != children->end(); it++){
				if ((*it)->key != "allow"){
					continue;
				}
				const char *ip = (*it)->str();
				log_info("    allow %s", ip);
				ip_filter->add_allow(ip);
			}
		}
	}

	{
		Config *cc = (Config *)conf->get("admin");
		if (cc != NULL){
			std::vector<Config *> *children = &cc->children;
			std::vector<Config *>::iterator it;
			for (it = children->begin(); it != children->end(); it++){
				if ((*it)->key != "deny"){
					continue;
				}
				const char *ip = (*it)->str();
				log_info("    deny %s", ip);
				ip_filter->add_deny(ip);
			}
		}
	}

	{
		// /sub?cname=abc&cb=jsonp&token=&seq=123&noop=123
		evhttp_set_cb(front_http, "/sub", poll_handler, NULL);
		evhttp_set_cb(front_http, "/poll", poll_handler, NULL);
		// forever iframe
		evhttp_set_cb(front_http, "/iframe", iframe_handler, NULL);
		// http endless chunk
		evhttp_set_cb(front_http, "/stream", stream_handler, NULL);
		// /ping?cb=jsonp
		evhttp_set_cb(front_http, "/ping", ping_handler, NULL);

		std::string front_ip;
		int front_port = 0;
		parse_ip_port(conf->get_str("front.listen"), &front_ip, &front_port);
		for (int i = 0; i < MAX_BIND_PORTS; i++){
			int port = front_port + i;

			struct evhttp_bound_socket *handle;
			handle = evhttp_bind_socket_with_handle(front_http, front_ip.c_str(), port);
			if (!handle){
				log_fatal("bind front_port %d error! %s", port, strerror(errno));
				exit(0);
			}
			log_info("front server listen on %s:%d", front_ip.c_str(), port);

			struct evconnlistener *listener = evhttp_bound_socket_get_listener(handle);
			evconnlistener_set_error_cb(listener, accept_error_cb);
		}

		std::string auth = conf->get_str("front.auth");
		log_info("    auth %s", auth.c_str());
		log_info("    max_channels %d", ServerConfig::max_channels);
		log_info("    max_subscribers_per_channel %d", ServerConfig::max_subscribers_per_channel);
		log_info("    channel_buffer_size %d", ServerConfig::channel_buffer_size);
		log_info("    channel_timeout %d", ServerConfig::channel_timeout);
		log_info("    polling_timeout %d", ServerConfig::polling_timeout);
		if (auth == "token"){
			serv->auth = Server::AUTH_TOKEN;
		}
	}

	//write_pidfile();
	log_info("chatserv started");
	event_base_dispatch(evbase);
	//remove_pidfile();

	event_free(timer_event);
	event_free(sigint_event);
	event_free(sigterm_event);
	evhttp_free(admin_http);
	evhttp_free(front_http);
	event_base_free(evbase);

	delete serv;
	delete conf;
	log_info("chatserv exit");

	return 0;
}
示例#22
0
文件: xBlog.cpp 项目: iomato/xblog
void xBlog::SetRouteTable(evhttp * http)
{
    evhttp_set_cb(http, "/download",     xBlogPage::DownloadCallback, this);        // 测试
    evhttp_set_cb(http, "/post",         xBlogPage::PostRequestCallback, this);     // 请求文章
    evhttp_set_cb(http, "/guestbook",    xBlogPage::GuestbookCallback, this);       // 查看-留言
    evhttp_set_cb(http, "/postmessage",  xBlogPage::GuestPostCallback, this);       // 添加-评论留言
    evhttp_set_cb(http, "/catalog",      xBlogPage::CatalogRequestCallback, this);  // 分类
    evhttp_set_cb(http, "/",             xBlogPage::IndexRequestCallback, this);    // 首页
    evhttp_set_cb(http, "/page",         xBlogPage::PageRequestCallback, this);     // 页面

    // 管理后台功能
    evhttp_set_cb(http, "/admin",        xBlogPage::AdminCallback, this);            // 管理后台
    evhttp_set_cb(http, "/checklogin",   xBlogPage::AdminCheckLoginCallback, this);  // 权限验证
    evhttp_set_cb(http, "/shell",        xBlogPage::AdminShellCallback, this);       // 测试
    evhttp_set_cb(http, "/status",       xBlogPage::AdminStatusCallback, this);      // 测试
    evhttp_set_cb(http, "/postmanager",  xBlogPage::AdminPostManagerCallback, this); // 文章管理
    evhttp_set_cb(http, "/siteconfig",   xBlogPage::AdminSiteConfigCallback, this);  // 网站配置参数管理
    evhttp_set_cb(http, "/links",        xBlogPage::AdminLinksCallback, this);       // 链接管理
    evhttp_set_cb(http, "/catalogset",   xBlogPage::AdminCatalogCallback, this);     // 链接管理
    evhttp_set_cb(http, "/comments",     xBlogPage::AdminCommentsCallback, this);    // 留言评论管理
    evhttp_set_cb(http, "/system",       xBlogPage::AdminSystemCallback, this);      // 系统配置
    evhttp_set_cb(http, "/user",         xBlogPage::AdminUserCallback, this);        // 系统配置

    evhttp_set_timeout(http, Config::GetInstance()->xBlogAppConfig.HttpdTimeOut);

    evhttp_set_gencb(http, xBlogPage::SendDocumentCallback, this);
}
示例#23
0
int
main(int argc, char **argv)
{
	struct event_base *base;
	struct evhttp *http;
	struct evhttp_bound_socket *handle;

	unsigned short port = atoi(argv[1]);
#ifdef WIN32
	WSADATA WSAData;
	WSAStartup(0x101, &WSAData);
#else
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
		return (1);
#endif
	base = event_base_new();
	if (!base) {
		fprintf(stderr, "Couldn't create an event_base: exiting\n");
		return 1;
	}

	/* Create a new evhttp object to handle requests. */
	http = evhttp_new(base);
	if (!http) {
		fprintf(stderr, "couldn't create evhttp. Exiting.\n");
		return 1;
	}

	evhttp_set_cb(http, "/s2cover", s2cover_request_cb, NULL);
	evhttp_set_cb(http, "/s2info", s2info_request_cb, NULL);
	evhttp_set_cb(http, "/fetch", fetch_request_cb, NULL);

	/* Now we tell the evhttp what port to listen on */
	handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
	if (!handle) {
		fprintf(stderr, "couldn't bind to port %d. Exiting.\n",
		    (int)port);
		return 1;
	}

	{
		/* Extract and display the address we're listening on. */
		struct sockaddr_storage ss;
		evutil_socket_t fd;
		ev_socklen_t socklen = sizeof(ss);
		char addrbuf[128];
		void *inaddr;
		const char *addr;
		int got_port = -1;
		fd = evhttp_bound_socket_get_fd(handle);
		memset(&ss, 0, sizeof(ss));
		if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
			perror("getsockname() failed");
			return 1;
		}
		if (ss.ss_family == AF_INET) {
			got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
			inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
		} else if (ss.ss_family == AF_INET6) {
			got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
			inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
		} else {
			fprintf(stderr, "Weird address family %d\n",
			    ss.ss_family);
			return 1;
		}
		addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
		    sizeof(addrbuf));
		if (addr) {
			printf("HI Listening on %s:%d\n", addr, got_port);
			evutil_snprintf(uri_root, sizeof(uri_root),
			    "http://%s:%d",addr,got_port);
		} else {
			fprintf(stderr, "evutil_inet_ntop failed\n");
			return 1;
		}
	}

	event_base_dispatch(base);

	return 0;
}
示例#24
0
int main(int argc, char** argv)
{
    struct event_base* base;
    struct evhttp* http;
    struct evhttp_bound_socket* handle;

    unsigned short port = 15520;

    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        return (1);

    base = event_base_new();
    if (!base) {
        fprintf(stderr, "Couldn't create an event_base: exiting\n");
        return 1;
    }

    http = evhttp_new(base);
    evhttp_set_cb(http, "/led/blink", led_blink, NULL);
    handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);

    //TODO: factor out thread
    std::thread cmdThread([&]() {
        //TODO, the locking is to broad at the moment
        //  during executing a command the queue is locked
        //  and therefore no new commands can be added
        //  copy the command and callback and release the lock
        //  would be a solution

        std::unique_lock<std::mutex> lock(cs_queue);
        while (!stopThread) {
            while (!notified) {  // loop to avoid spurious wakeups
                queueCondVar.wait(lock);
            }
            while (!cmdQueue.empty()) {
                std::string cmdOut;
                t_cmdCB cmdCB = cmdQueue.front();
                std::string cmd = std::get<0>(cmdCB);
                std::string password = std::get<1>(cmdCB);

                if (!password.empty())
                {
                    std::string base64str;
                    std::string unencryptedJson;
                    try
                    {
                        DBB::encryptAndEncodeCommand(cmd, password, base64str);
                        if (!DBB::sendCommand(base64str, cmdOut))
                            unencryptedJson = "sending command failed";
                        else
                            DBB::decryptAndDecodeCommand(cmdOut, password, unencryptedJson);
                    }
                    catch (const std::exception& ex) {
                        unencryptedJson = "response decryption failed: "+cmdOut;
                    }

                    cmdOut = unencryptedJson;
                }
                else
                {
                    DBB::sendCommand(cmd, cmdOut);
                }
                std::get<2>(cmdCB)(cmdOut);
                cmdQueue.pop();
            }
            notified = false;
        }
    });

    //create a thread for the http handling
    std::thread usbCheckThread([&]() {
        while(1)
        {
            //check devices
            if (!DBB::isConnectionOpen())
            {
                if (DBB::openConnection())
                {
#ifdef DBB_ENABLE_QT
                //TODO, check if this requires locking
                if (widget)
                    widget->deviceStateHasChanged(true);
#endif
                }
                else
                {
#ifdef DBB_ENABLE_QT
                if (widget)
                    widget->deviceStateHasChanged(false);
#endif
                }
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        }
    });

    ECC_Start();

#ifdef DBB_ENABLE_QT
#if QT_VERSION > 0x050100
    // Generate high-dpi pixmaps
    QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

    //create a thread for the http handling
    std::thread httpThread([&]() {
        event_base_dispatch(base);
    });

    QApplication app(argc, argv);

    widget = new DBBDaemonGui(0);
    widget->show();
    app.exec();
#else
    //directly start libevents main run loop
    event_base_dispatch(base);
#endif

    ECC_Stop();
    exit(1);
}
示例#25
0
文件: httpd.c 项目: aol/thrasher
int
webserver_init(void)
{
    struct evhttp  *httpd;
    httpd = evhttp_new(base);

    evutil_gettimeofday(&start_time, NULL);

    if (httpd == NULL)
        return -1;

    if (evhttp_bind_socket(httpd, bind_addr, server_port) == -1)
        return -1;

#ifdef WITH_GEOIP
    if (gi) 
        geoip_header = "<th>Country</th>";
    else
        geoip_header = "";
#else
    geoip_header = "";
#endif

    evhttp_set_cb(httpd, "/holddowns", httpd_put_holddowns, NULL);
    evhttp_set_cb(httpd, "/holddowns.html", httpd_put_holddowns_html, NULL);
    evhttp_set_cb(httpd, "/config", httpd_put_config, NULL);
    evhttp_set_cb(httpd, "/config.html", httpd_put_config, (void *)1);
    evhttp_set_cb(httpd, "/connections", httpd_put_connections, NULL);
    evhttp_set_cb(httpd, "/connections.html", httpd_put_connections_html, NULL);
    evhttp_set_cb(httpd, "/addrs", httpd_put_addrs, NULL);
    evhttp_set_cb(httpd, "/addrs.html", httpd_put_addrs_html, NULL);
    evhttp_set_cb(httpd, "/uris", httpd_put_uris, NULL);
    evhttp_set_cb(httpd, "/uris.html", httpd_put_uris_html, NULL);
    evhttp_set_cb(httpd, "/hosts", httpd_put_hosts, NULL);
    evhttp_set_cb(httpd, "/hosts.html", httpd_put_hosts_html, NULL);
    evhttp_set_cb(httpd, "/favicon.ico", httpd_put_favicon, NULL);
    evhttp_set_cb(httpd, "/action", httpd_action, NULL);
    evhttp_set_gencb(httpd, httpd_driver, NULL);
    return 0;
}
示例#26
0
int main(int argc, char **argv){
	unsigned int i;
	char * ptr;

	unsigned int numthreads;

	global_data * global = new global_data;

	global->stats.starttime = get_now();

//2 queues
	global->request  = new tqueue<request_t>();
	global->response = new tqueue<request_t>();

//thread stuff
	pthread_t thread[MAX_THREADS];
	thread_data_t threaddata[MAX_THREADS];

//http server stuff
	struct evhttp *http;
	struct event updateEvent;


//notification fds
	int fds[2];

	srand(time(NULL));

	//defaults
	char port_def[] = "80";
	char hostname_def[] = "0.0.0.0";
	char threads_def[] = "3";
	char static_source_def[] = "pentagoo/";

	//Argument Pointers
	char *port_arg = port_def;
	char *hostname_arg = hostname_def;
	char *threads_arg = threads_def;
	char *static_source = static_source_def;


//Parse command line options
	for (i = 1; i < (unsigned int)argc; i++) {
		ptr = argv[i];
		if(strcmp(ptr, "--help") == 0){
			printf("Usage:\n"
				"\t--help        Show this help\n"
				"\t-l            Location for the web frontend [%s]\n"
				"\t-p            Port Number [%s]\n"
				"\t-h            Hostname [%s]\n"
				"\t-t            Number of threads [%s]\n\n",
				static_source_def, port_def, hostname_def, threads_def);
			exit(255);
		}else if (strcmp(ptr, "-p") == 0)
			port_arg = ptr = argv[++i];
		else if (strcmp(ptr, "-h") == 0)
			hostname_arg = ptr = argv[++i];
		else if (strcmp(ptr, "-t") == 0)
			threads_arg = ptr = argv[++i];
		else if (strcmp(ptr, "-l") == 0)
			static_source = ptr = argv[++i];
	}


	global->static_source = static_source;

	numthreads = atoi(threads_arg);
	if(numthreads < 1)
		numthreads = 1;

	if(numthreads > MAX_THREADS){
		printf("Invalid number of threads '%s', setting to max threads %i\n", threads_arg, MAX_THREADS);
		numthreads = MAX_THREADS;
	}

//initialize update notification pipe
	socketpair(AF_UNIX, SOCK_STREAM, 0, fds);

	global->pushfd = fds[0];
	global->popfd = fds[1];


	printf("Starting %u computation threads\n", numthreads);

	for(i = 0; i < numthreads; i++){
		threaddata[i].threadid = i;
		threaddata[i].state = 1;
		threaddata[i].global = global;
		
		pthread_create(&thread[i], NULL, (void* (*)(void*)) requestRunner, (void*) &threaddata[i]);
	}


//init the event lib
	event_init();


	printf("Listening on %s:%s\n", hostname_arg, port_arg);

//start the http server
	http = evhttp_start(hostname_arg, atoi(port_arg));
	if(http == NULL) {
		printf("Couldn't start server on %s:%s\n", hostname_arg, port_arg);
		return 1;
	}


//Register a callback for requests
	evhttp_set_gencb(http, handle_http_static, global); //the generic catch all callback, used to serve static files
	evhttp_set_cb(http, "/ai",              handle_request_ai,       global); //my nice url
	evhttp_set_cb(http, "/pentagoo_ai.php", handle_request_ai,       global); //hijack the pentagoo url

	evhttp_set_cb(http, "/stats",    handle_request_stats,    global);

	event_set(& updateEvent, global->popfd, EV_READ|EV_PERSIST, handle_queue_response, global);
	event_add(& updateEvent, 0);


	printf("Starting event loop\n");

	event_dispatch();


	printf("Exiting\n");

	global->request->nonblock();
	for(i = 0; i < numthreads; i++)
		pthread_join(thread[i], NULL);

	return 0;
}
示例#27
0
文件: main.cpp 项目: Lukasa/chronos
int main(int argc, char** argv)
{
  // Initialize cURL before creating threads
  curl_global_init(CURL_GLOBAL_DEFAULT);

  // Set up our exception signal handler for asserts and segfaults.
  signal(SIGABRT, exception_handler);
  signal(SIGSEGV, exception_handler);

  // Initialize the global configuration.
  __globals = new Globals();
  __globals->update_config();

  // Create components
  TimerStore *store = new TimerStore();
  Replicator* controller_rep = new Replicator();
  Replicator* handler_rep = new Replicator();
  HTTPCallback* callback = new HTTPCallback();
  TimerHandler* handler = new TimerHandler(store, handler_rep, callback);
  Controller* controller = new Controller(controller_rep, handler);

  // Create an event reactor.
  struct event_base* base = event_base_new();
  if (!base) {
    std::cerr << "Couldn't create an event_base: exiting" << std::endl;
    return 1;
  }

  // Create an HTTP server instance.
  struct evhttp* http = evhttp_new(base);
  if (!http) {
    std::cerr << "Couldn't create evhttp: exiting" << std::endl;
    return 1;
  }

  // Register a callback for the "/ping" path.
  evhttp_set_cb(http, "/ping", Controller::controller_ping_cb, NULL);

  // Register a callback for the "/timers" path, we have to do this with the
  // generic callback as libevent doesn't support regex paths.
  evhttp_set_gencb(http, Controller::controller_cb, controller);

  // Bind to the correct port
  std::string bind_address;
  int bind_port;
  __globals->get_bind_address(bind_address);
  __globals->get_bind_port(bind_port);
  evhttp_bind_socket(http, bind_address.c_str(), bind_port);

  // Start the reactor, this blocks the current thread
  event_base_dispatch(base);

  // Event loop is completed, terminate.
  //
  // After this point nothing will use __globals so it's safe to delete
  // it here.
  delete __globals; __globals = NULL;
  curl_global_cleanup();

  return 0;
}
示例#28
0
文件: movid.cpp 项目: AChurikov/Movid
int main(int argc, char **argv) {
	int ret;

	ret = parse_options(&argc, &argv);
	if ( ret >= 0 )
		return ret;

	moFactory::init();

	signal(SIGTERM, signal_term);
	signal(SIGINT, signal_term);

	if ( config_pipelinefn != "" ) {
		pipeline = pipeline_parse_file(config_pipelinefn);
		if ( pipeline == NULL ) {
			return 2;
		}
	} else if ( config_httpserver == false ) {
		std::cerr << "ERROR : no pipeline or webserver to start!" << std::endl;
		return 3;
	}

	// no default pipeline ? create one !
	if ( pipeline == NULL )
		pipeline = new moPipeline();

	if ( config_httpserver ) {
		#ifdef WIN32
			WORD wVersionRequested;
			WSADATA wsaData;
			int	err;
			wVersionRequested = MAKEWORD( 2, 2 );
			err = WSAStartup( wVersionRequested, &wsaData );
		#else
			signal(SIGPIPE, SIG_IGN);
		#endif

		base = event_init();
		server = evhttp_new(NULL);

		evhttp_bind_socket(server, "127.0.0.1", 7500);

		evhttp_set_cb(server, "/", web_index, NULL);
		evhttp_set_cb(server, "/factory/list", web_factory_list, NULL);
		evhttp_set_cb(server, "/factory/describe", web_factory_desribe, NULL);
		evhttp_set_cb(server, "/pipeline/create", web_pipeline_create, NULL);
		evhttp_set_cb(server, "/pipeline/remove", web_pipeline_remove, NULL);
		evhttp_set_cb(server, "/pipeline/status", web_pipeline_status, NULL);
		evhttp_set_cb(server, "/pipeline/connect", web_pipeline_connect, NULL);
		evhttp_set_cb(server, "/pipeline/set", web_pipeline_set, NULL);
		evhttp_set_cb(server, "/pipeline/get", web_pipeline_get, NULL);
		evhttp_set_cb(server, "/pipeline/stream", web_pipeline_stream, NULL);
		evhttp_set_cb(server, "/pipeline/start", web_pipeline_start, NULL);
		evhttp_set_cb(server, "/pipeline/stop", web_pipeline_stop, NULL);
		evhttp_set_cb(server, "/pipeline/quit", web_pipeline_quit, NULL);
		evhttp_set_cb(server, "/pipeline/dump", web_pipeline_dump, NULL);

		evhttp_set_gencb(server, web_file, NULL);
	}

	while ( want_quit == false ) {
		// FIXME remove this hack !!!
		cvWaitKey(config_delay);

		// update pipeline
		if ( pipeline->isStarted() ) {
			pipeline->poll();

			// check for error in pipeline
			while ( pipeline->haveError() ) {
				std::cerr << "Pipeline error: " << pipeline->getLastError() << std::endl;
				if ( test_mode )
					want_quit = true;
			}
		}

		// got a server, update
		if ( server != NULL )
			event_base_loop(base, EVLOOP_ONCE|EVLOOP_NONBLOCK);
	}

	if ( server != NULL )
		evhttp_free(server);
	if ( base != NULL )
		event_base_free(base);

	delete pipeline;

	moFactory::cleanup();
}
示例#29
0
int
main(int argc, char **argv)
{
	struct event_config *cfg = ld_event_config_new();
	struct event_base *base;
	struct evhttp *http;
	int i;
	int c;
	int use_iocp = 0;
	unsigned short port = 8080;
	char *endptr = NULL;

#ifdef _WIN32
	WSADATA WSAData;
	WSAStartup(0x101, &WSAData);
#else
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
		return (1);
#endif

	for (i = 1; i < argc; ++i) {
		if (*argv[i] != '-')
			continue;

		c = argv[i][1];

		if ((c == 'p' || c == 'l') && i + 1 >= argc) {
			fprintf(stderr, "-%c requires argument.\n", c);
			exit(1);
		}

		switch (c) {
		case 'p':
			if (i+1 >= argc || !argv[i+1]) {
				fprintf(stderr, "Missing port\n");
				exit(1);
			}
			port = (int)strtol(argv[i+1], &endptr, 10);
			if (*endptr != '\0') {
				fprintf(stderr, "Bad port\n");
				exit(1);
			}
			break;
		case 'l':
			if (i+1 >= argc || !argv[i+1]) {
				fprintf(stderr, "Missing content length\n");
				exit(1);
			}
			content_len = (size_t)strtol(argv[i+1], &endptr, 10);
			if (*endptr != '\0' || content_len == 0) {
				fprintf(stderr, "Bad content length\n");
				exit(1);
			}
			break;
#ifdef _WIN32
		case 'i':
			use_iocp = 1;
			evthread_use_windows_threads();
			ld_event_config_set_flag(cfg,EVENT_BASE_FLAG_STARTUP_IOCP);
			break;
#endif
		default:
			fprintf(stderr, "Illegal argument \"%c\"\n", c);
			exit(1);
		}
	}

	base = ld_event_base_new_with_config(cfg);
	if (!base) {
		fprintf(stderr, "creating event_base failed. Exiting.\n");
		return 1;
	}

	http = evhttp_new(base);

	content = malloc(content_len);
	if (content == NULL) {
		fprintf(stderr, "Cannot allocate content\n");
		exit(1);
	} else {
		int i = 0;
		for (i = 0; i < (int)content_len; ++i)
			content[i] = (i & 255);
	}

	evhttp_set_cb(http, "/ind", http_basic_cb, NULL);
	fprintf(stderr, "/ind - basic content (memory copy)\n");

	evhttp_set_cb(http, "/ref", http_ref_cb, NULL);
	fprintf(stderr, "/ref - basic content (reference)\n");

	fprintf(stderr, "Serving %d bytes on port %d using %s\n",
	    (int)content_len, port,
	    use_iocp? "IOCP" : ld_event_base_get_method(base));

	evhttp_bind_socket(http, "0.0.0.0", port);

	if (use_iocp) {
		struct timeval tv={99999999,0};
		ld_event_base_loopexit(base, &tv);
	}
	ld_event_base_dispatch(base);

	/* NOTREACHED */
	return (0);
}
示例#30
0
文件: info.c 项目: gnuhurd/gnuhurd
void register_info_json(const char* url)
{
    evhttp_set_cb(http_server, url, do_info, 0);
}