int main(int argc, char **argv) { // Register signal and signal handler signal(SIGINT, &signal_callback_handler); int pid_file = open(zsearch::LOCK_FILE.c_str(), O_CREAT | O_RDWR, 0666); int rc = flock(pid_file, LOCK_EX | LOCK_NB); if (rc) { if (EWOULDBLOCK == errno) { std::cerr << "Only one instance of zsearch is allowed!" << std::endl; return -1; } } if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { return 1; } if (argc < 3) { fprintf(stdout, "Syntax: http-server <docroot> <destroyDb = 0/1>\n"); return 1; } bool destroyDb = false; string strDestroyDb = argv[2]; int iDestroyDb = ZUtil::getInt(strDestroyDb); if (iDestroyDb) { destroyDb = true; } struct evhttp *http; struct evhttp_bound_socket *handle; 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; } // The /dump URI will dump all requests to stdout and say 200 ok // evhttp_set_cb(http, "/dump", dump_request_cb, NULL); evhttp_set_cb(http, zsearch::server::SEARCH_PATH.c_str(), search_request_cb, NULL); evhttp_set_cb(http, zsearch::server::DOC_PATH.c_str(), doc_request_cb, NULL); evhttp_set_cb(http, zsearch::server::INDEX_PATH.c_str(), post_request_cb, NULL); // We want to accept arbitrary requests, so we need to set a "generic" evhttp_set_gencb(http, generic_request_cb, argv[1]); // Now we tell the evhttp what port to listen on handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", zsearch::server::PORT); if (!handle) { fprintf(stderr, "couldn't bind to port %d. Exiting.\n", zsearch::server::PORT); return 1; } // if we made it till here then we're go! // std::shared_ptr<ISetFactory> setFactory = make_shared<BasicSetFactory>(); std::shared_ptr<ISetFactory> setFactory = make_shared<SetFactory>(); std::shared_ptr<ITokenizer> tokenizer = std::make_shared<TokenizerImpl>(); shared_ptr<KVStore::IKVStore> storeKV = make_shared<KVStore::KVStoreLevelDb>(zsearch::LEVELDB_STORE, destroyDb); storeKV->Open(); shared_ptr<KVStore::IKVStore> engineDataStore = make_shared<KVStore::NameSpaceKVStore>('e', storeKV); shared_ptr<KVStore::IKVStore> fieldStore = make_shared<KVStore::NameSpaceKVStore>('f', storeKV); shared_ptr<KVStore::IKVStore> documentStore = make_shared<KVStore::NameSpaceKVStore>('d', storeKV); shared_ptr<KVStore::IKVStore> wordIndexStore = make_shared<KVStore::NameSpaceKVStore>('w', storeKV); shared_ptr<KVStore::IKVStore> invertedIndexStore = make_shared<KVStore::NameSpaceKVStore>('i', storeKV); engine = new Engine(engineDataStore, fieldStore, documentStore, wordIndexStore, invertedIndexStore, setFactory); engine->setMaxBatchSize(zsearch::MAX_BATCH_SIZE); printf("Listening on 0.0.0.0:%d\n", zsearch::server::PORT); event_base_dispatch(base); delete engine; return 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); }
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 ---------- */
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; }
void* CD_RunHTTPd (CDHTTPd* self) { self->event.handle = evhttp_bind_socket_with_handle(self->event.httpd, self->server->config->cache.httpd.connection.bind.ipv4, self->server->config->cache.httpd.connection.port); SLOG(self->server, LOG_NOTICE, "Started HTTPd at http://%s:%d", self->server->config->cache.httpd.connection.bind.ipv4, self->server->config->cache.httpd.connection.port); event_base_dispatch(self->event.base); return NULL; }
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; }
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; }
int main(int argc, char **argv) { struct event_base *base; struct evhttp *http; struct evhttp_bound_socket *handle; unsigned short port = DEFAULT_PORT; if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { return 1; } if (argc >= 2) { port = atoi(argv[1]); if (!port) { port = DEFAULT_PORT; } } base = event_base_new(); if (!base) { fprintf(stderr, "Couldn't create an event_base: exiting\n"); return 1; } http = evhttp_new(base); if (!http) { fprintf(stderr, "couldn't create evhttp. Exiting.\n"); return 1; } evhttp_set_gencb(http, send_document_cb, argv[1]); handle = evhttp_bind_socket_with_handle(http, "127.0.0.1", port); if (!handle) { fprintf(stderr, "couldn't bind to port %d. Exiting.\n", (int)port); return 1; } diplay_socket_information(handle); event_base_dispatch(base); return 0; }
static struct evhttp * http_setup(ev_uint16_t *pport) { struct evhttp *myhttp; ev_uint16_t port; struct evhttp_bound_socket *sock; myhttp = evhttp_new(NULL); if (!myhttp) event_errx(1, "Could not start web server"); /* Try a few different ports */ sock = evhttp_bind_socket_with_handle(myhttp, "127.0.0.1", 0); if (!sock) event_errx(1, "Couldn't open web port"); port = regress_get_socket_port(evhttp_bound_socket_get_fd(sock)); *pport = port; return (myhttp); }
int NFCHttpServer::InitServer(const unsigned short port) { mPort = port; //struct event_base *base; struct evhttp* http; struct evhttp_bound_socket* handle; #if NF_PLATFORM == NF_PLATFORM_WIN WSADATA WSAData; WSAStartup(0x101, &WSAData); #else if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) return (1); #endif base = event_base_new(); if (!base) { std::cout << "create event_base fail" << std::endl;; return 1; } http = evhttp_new(base); if (!http) { std::cout << "create evhttp fail" << std::endl;; return 1; } evhttp_set_gencb(http, listener_cb, (void*) this); handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", mPort); if (!handle) { std::cout << "bind port :" << mPort << " fail" << std::endl;; return 1; } return 0; }
/** Bind HTTP server to specified addresses */ static bool HTTPBindAddresses(struct evhttp* http) { int defaultPort = GetArg("-rpcport", BaseParams().RPCPort()); std::vector<std::pair<std::string, uint16_t> > endpoints; // Determine what addresses to bind to if (!IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs endpoints.push_back(std::make_pair("::1", defaultPort)); endpoints.push_back(std::make_pair("127.0.0.1", defaultPort)); if (IsArgSet("-rpcbind")) { LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n"); } } else if (mapMultiArgs.count("-rpcbind")) { // Specific bind address const std::vector<std::string>& vbind = mapMultiArgs.at("-rpcbind"); for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) { int port = defaultPort; std::string host; SplitHostPort(*i, port, host); endpoints.push_back(std::make_pair(host, port)); } } else { // No specific bind address specified, bind to any endpoints.push_back(std::make_pair("::", defaultPort)); endpoints.push_back(std::make_pair("0.0.0.0", defaultPort)); } // Bind addresses for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) { LogPrint("http", "Binding RPC on address %s port %i\n", i->first, i->second); evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second); if (bind_handle) { boundSockets.push_back(bind_handle); } else { LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second); } } return !boundSockets.empty(); }
int main(int argc, char **argv) { struct context ctx = {0}; struct event *signal_int; struct evhttp_bound_socket *handle; char listen_addr[256]; if (argc != 2) { printf("usage: statsrv STATS\n"); return -1; } if (stats_cl_create(&ctx.cl) != S_OK) { printf("Failed to allocate stats counter list\n"); return ERROR_FAIL; } if (stats_sample_create(&ctx.sample) != S_OK) { printf("Failed to allocate stats sample\n"); return ERROR_FAIL; } if (stats_sample_create(&ctx.prev_sample) != S_OK) { printf("Failed to allocate stats sample\n"); return ERROR_FAIL; } ctx.stats = open_stats(argv[1]); if (!ctx.stats) { printf("Failed to open stats %s\n", argv[1]); return ERROR_FAIL; } ctx.base = event_base_new(); if (!ctx.base) { printf("Could not allocate event base\n"); return 1; } /* add a handler for SIGINT */ signal_int = evsignal_new(ctx.base, SIGINT, sigint_cb, event_self_cbarg()); evsignal_add(signal_int,0); /* Create a new evhttp object to handle requests. */ ctx.http = evhttp_new(ctx.base); if (!ctx.http) { printf("could not create evhttp.\n"); return ERROR_FAIL; } evhttp_set_gencb(ctx.http, http_request_cb, &ctx); /* Now we tell the evhttp what port to listen on */ handle = evhttp_bind_socket_with_handle(ctx.http, "0.0.0.0", 8080); if (!handle) { printf("couldn't bind to http port %d.\n", (int)8080); return ERROR_FAIL; } if (http_get_address(handle, listen_addr, sizeof(listen_addr)) == S_OK) printf("http: listening at %s\n", listen_addr); event_base_dispatch(ctx.base); event_free(signal_int); #if 0 start_time = current_time(); while (!signal_received) { err = stats_get_sample(stats,cl,sample); if (err != S_OK) { printf("Error %08x (%s) getting sample\n",err,error_message(err)); } clear(); sample_time = TIME_DELTA_TO_NANOS(start_time, sample->sample_time); mvprintw(0,0,"SAMPLE @ %6lld.%03llds SEQ:%d\n", sample_time / 1000000000ll, (sample->sample_time % 1000000000ll) / 1000000ll, sample->sample_seq_no); n = 1; maxy = getmaxy(stdscr); col = 0; for (j = 0; j < cl->cl_count; j++) { counter_get_key(cl->cl_ctr[j],counter_name,MAX_COUNTER_KEY_LENGTH+1); mvprintw(n,col+0,"%s", counter_name); mvprintw(n,col+29,"%15lld", stats_sample_get_value(sample,j)); mvprintw(n,col+46,"%15lld", stats_sample_get_delta(sample,prev_sample,j)); if (++n == maxy) { col += 66; n = 1; } } refresh(); tmp = prev_sample; prev_sample = sample; sample = tmp; FD_ZERO(&fds); FD_SET(0,&fds); now = current_time(); tv.tv_sec = 0; tv.tv_usec = 1000000 - (now % 1000000000) / 1000; ret = select(1, &fds, NULL, NULL, &tv); if (ret == 1) { ch = getch(); if (ch == 'c' || ch == 'C') { stats_reset_counters(stats); } } } close_screen(); #endif if (ctx.base) event_base_free(ctx.base); if (ctx.http) evhttp_free(ctx.http); if (ctx.stats) { stats_close(ctx.stats); stats_free(ctx.stats); } if (ctx.cl) stats_cl_free(ctx.cl); if (ctx.sample) stats_sample_free(ctx.sample); if (ctx.prev_sample) stats_sample_free(ctx.prev_sample); return 0; }
void http_thread(void *asdf) { sigset_t sigs_to_block; struct http_config_t *lc; struct timeval http_timer_tv; http_timer_tv.tv_sec = 0; http_timer_tv.tv_usec = 200000; pthreads_profiling_reset("http"); sigemptyset(&sigs_to_block); sigaddset(&sigs_to_block, SIGALRM); sigaddset(&sigs_to_block, SIGINT); sigaddset(&sigs_to_block, SIGTERM); sigaddset(&sigs_to_block, SIGQUIT); sigaddset(&sigs_to_block, SIGHUP); sigaddset(&sigs_to_block, SIGURG); sigaddset(&sigs_to_block, SIGPIPE); sigaddset(&sigs_to_block, SIGUSR1); sigaddset(&sigs_to_block, SIGUSR2); pthread_sigmask(SIG_BLOCK, &sigs_to_block, NULL); /* start the http thread, which will start server threads */ hlog(LOG_INFO, "HTTP thread starting..."); /* we allocate a worker structure to be used within the http thread * for parsing incoming packets and passing them on to the dupecheck * thread. */ http_worker = worker_alloc(); http_worker->id = 80; /* we also need a client structure to be used with incoming * HTTP position uploads */ http_pseudoclient = pseudoclient_setup(80); http_reconfiguring = 1; while (!http_shutting_down) { if (http_reconfiguring) { http_reconfiguring = 0; // shut down existing instance http_server_free(); // do init #if 1 libbase = event_base_new(); // libevent 2.x #else libbase = event_init(); // libevent 1.x #endif // timer for the whole libevent, to catch shutdown signal ev_timer = event_new(libbase, -1, EV_TIMEOUT, http_timer, NULL); event_add(ev_timer, &http_timer_tv); for (lc = http_config; (lc); lc = lc->next) { hlog(LOG_INFO, "Binding HTTP %s socket %s:%d", lc->upload_port ? "upload" : "status", lc->host, lc->port); struct evhttp *srvr; struct evhttp_bound_socket *handle; if (lc->upload_port) { if (!srvr_upload) { srvr_upload = evhttp_new(libbase); http_srvr_defaults(srvr_upload); evhttp_set_allowed_methods(srvr_upload, EVHTTP_REQ_POST); /* uploads are POSTs, after all */ evhttp_set_gencb(srvr_upload, http_router, (void *)2); } srvr = srvr_upload; } else { if (!srvr_status) { srvr_status = evhttp_new(libbase); http_srvr_defaults(srvr_status); evhttp_set_gencb(srvr_status, http_router, (void *)1); } srvr = srvr_status; } handle = evhttp_bind_socket_with_handle(srvr, lc->host, lc->port); if (!handle) { hlog(LOG_ERR, "Failed to bind HTTP socket %s:%d: %s", lc->host, lc->port, strerror(errno)); // TODO: should exit? } } hlog(LOG_INFO, "HTTP thread ready."); } event_base_dispatch(libbase); } hlog(LOG_DEBUG, "HTTP thread shutting down..."); http_server_free(); /* free up the pseudo-client */ client_free(http_pseudoclient); http_pseudoclient = NULL; /* free up the pseudo-worker structure */ worker_free_buffers(http_worker); hfree(http_worker); http_worker = NULL; }
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; }
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); }
bool jw_httpsrv_create(struct event_base *evbase, jw_httpsrv *rethttpsrv, jw_err *err) { bool retval = false; jw_httpsrv httpsrv = jw_data_malloc(sizeof(struct _jw_httpsrv)); if (NULL == httpsrv) { JABBERWERX_ERROR(err, JW_ERR_NO_MEMORY); goto jw_httpsrv_create_done_label; } memset(httpsrv, 0, sizeof(struct _jw_httpsrv)); httpsrv->http = evhttp_new(evbase); if (NULL == httpsrv->http) { JABBERWERX_ERROR(err, JW_ERR_NO_MEMORY); goto jw_httpsrv_create_done_label; } httpsrv->next_body = evbuffer_new(); if (NULL == httpsrv->next_body) { JABBERWERX_ERROR(err, JW_ERR_NO_MEMORY); goto jw_httpsrv_create_done_label; } evhttp_set_gencb(httpsrv->http, _request_cb, httpsrv); struct evhttp_bound_socket *handle = evhttp_bind_socket_with_handle(httpsrv->http, "127.0.0.1", 0); if (NULL == handle) { jw_log(JW_LOG_WARN, "failed to bind http server to port"); JABBERWERX_ERROR(err, JW_ERR_INVALID_STATE); goto jw_httpsrv_create_done_label; } evutil_socket_t fd = evhttp_bound_socket_get_fd(handle); struct sockaddr_storage ss; ev_socklen_t socklen = sizeof(ss); memset(&ss, 0, sizeof(ss)); if (0 != getsockname(fd, (struct sockaddr *)&ss, &socklen)) { assert(false); } if (AF_INET == ss.ss_family) { httpsrv->port = ntohs(((struct sockaddr_in*)&ss)->sin_port); } else if (AF_INET6 == ss.ss_family) { httpsrv->port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port); } else { assert(false); } *rethttpsrv = httpsrv; jw_log(JW_LOG_VERBOSE, "successfully started httpsrv on 127.0.0.1:%u", httpsrv->port); retval = true; jw_httpsrv_create_done_label: if (!retval && httpsrv) { jw_httpsrv_destroy(httpsrv); } return retval; }
//Main int main(int argc, char *argv[]) { //Get args if (argc < 2) { fprintf(stderr, "Usage: %s <snapshot_file>\n", argv[0]); return 1; } snap_path = argv[1]; //Allocate memory fprintf(stderr, "Allocating arena with size %.2f MBytes ...\n", (float)m / CHAR_BIT / MEGA); Bloom = malloc( (m + ( CHAR_BIT - 1)) / CHAR_BIT ); // Ceil byte length: bytes = bits + 7 / 8 //Load or create snapshot file if (!access(snap_path, F_OK)) { fputs("Loading snapshot...\n", stderr); if (LoadSnap(Bloom, snap_path)) { fputs("Unable to load snapshot!\n", stderr); return -1; } fputs("Snapshot loaded.\n", stderr); } else { fputs("Initializing new file storage...\n", stderr); size_t shouldwrite = (m + (CHAR_BIT - 1)) / CHAR_BIT; memset(Bloom, 0, shouldwrite); if (SaveSnap(Bloom, snap_path)) { fputs("Unable to save initial snapshot!\n", stderr); return -1; } fputs("Initial snapshot written.\n", stderr); } void OnReq(struct evhttp_request *req, void *arg) { struct evbuffer *OutBuf = evhttp_request_get_output_buffer(req); if (!OutBuf) { evhttp_send_reply(req, HTTP_BADREQUEST, "Bad Request", OutBuf); return; } struct evkeyvalq *Headers = evhttp_request_get_output_headers(req); if (!Headers) { evhttp_send_reply(req, HTTP_INTERNAL, "Internal Error", OutBuf); return; } const struct evhttp_uri *HTTPURI = evhttp_request_get_evhttp_uri(req); if (!HTTPURI) { evhttp_send_reply(req, HTTP_BADREQUEST, "Bad Request", OutBuf); return; } const char *path = evhttp_uri_get_path(HTTPURI); if (!path) { evhttp_send_reply(req, HTTP_BADREQUEST, "Bad Request", OutBuf); } const char *query_string = evhttp_uri_get_query(HTTPURI); if (!query_string) { evhttp_send_reply(req, HTTP_BADREQUEST, "Element Required", OutBuf); return; } struct evkeyvalq params; evhttp_parse_query_str(query_string, ¶ms); const char *element = evhttp_find_header(¶ms, "e"); if (!element) { evhttp_clear_headers(¶ms); evhttp_send_reply(req, HTTP_BADREQUEST, "Element Required", OutBuf); return; } int i; const char* (*Operation)(bloom_cell *, size_t []) = NULL; for (i=0; i< sizeof HandlerTable/ sizeof HandlerTable[0] ; i++) if (strncmp(HandlerTable[i][0], path, STR_MAX) == 0) { Operation = HandlerTable[i][1]; break; } if (!Operation) { evhttp_clear_headers(¶ms); evhttp_send_reply(req, HTTP_NOTFOUND, "Not Found", OutBuf); return; } const char *response = Operation(Bloom, Hashes(element)); evhttp_add_header(Headers, MIME_TYPE); evbuffer_add_printf(OutBuf, response); evhttp_send_reply(req, HTTP_OK, "OK", OutBuf); evhttp_clear_headers(¶ms); }; if (!(base = event_base_new())) crash("Couldn't create an event_base: exiting\n", -1); if (!(http = evhttp_new(base))) crash("Couldn't create evhttp. Exiting.\n", -1); evhttp_set_gencb(http, OnReq, NULL); if (!(handle = evhttp_bind_socket_with_handle(http, BIND_ADDRESS, BIND_PORT))) crash("couldn't bind to port 8888. Exiting.\n", -1); if (signal(SIGINT, term_handler) == SIG_ERR) crash("Unable to set SIGINT handler!", -1); if (signal(SIGTERM, term_handler) == SIG_ERR) crash("Unable to set SIGTERM handler!", -1); if (signal(SIGCHLD, child_collector) == SIG_ERR) crash("Unable to set SIGCHLD handler!", -1); //This signal handled by event loop in order to avoid malloc deadlock if ((dump_event = evsignal_new(base, SIGUSR1, dump_handler, NULL)) == NULL) crash("Unable to create SIGUSR1 handler!", -1); else if (event_add(dump_event, NULL) == -1) crash("Unable to add SIGUSR1 handler!", -1); if (event_base_dispatch(base) == -1) crash("Failed to run message loop.\n", -1); fputs("Exiting...\n", stderr); SaveSnap(Bloom, snap_path); evhttp_del_accept_socket(http, handle); evhttp_free(http); event_free(dump_event); event_base_free(base); free(Bloom); return 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; }