//#define MULTI_THREAD_SUPPORT 1
int httpserver_start(int port, int nthreads, int backlog) {
	int r, i;
	int nfd = httpserver_bindsocket(port, backlog);
	if (nfd < 0) return -1;

#ifdef MULTI_THREAD_SUPPORT
	pthread_t ths[nthreads];
	for (i=0; i<nthreads; i++) {
		struct event_base *base = event_init();
		if (base == NULL) return -1;
		struct evhttp *httpd = evhttp_new(base);
		if (httpd == NULL) return -1;
		r = evhttp_accept_socket(httpd, nfd);
		if (r != 0) return -1;
		 evhttp_set_gencb(httpd, httpserver_generic_handler, NULL);
		r = pthread_create(&ths[i], NULL, httpserver_dispatch, base);
		if (r != 0) return -1;
	}
	
	for (i=0; i<nthreads; i++) {
		pthread_join(ths[i], NULL);
	}
#else
	struct event_base *base = event_init();
	if (base == NULL) return -1;
	struct evhttp *httpd = evhttp_new(base);
	if (httpd == NULL) return -1;
	r = evhttp_accept_socket(httpd, nfd);
	evhttp_set_gencb(httpd, httpserver_generic_handler, NULL);
	httpserver_dispatch(base);
#endif
}
Exemple #2
0
int main(int argc, char **argv)
{
    setting = &_setting;
    sigset_t signal_mask;
    sigemptyset(&signal_mask);
    sigaddset(&signal_mask, SIGPIPE);
    pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);

    signal(SIGINT, clean_up);
    signal(SIGQUIT, clean_up);
    signal(SIGTERM, clean_up);

    parse_options(argc, argv);

    if (setting->daemon_mode) {
        daemonize();
    }
    redis_init(setting->redis_addr, setting->redis_port);
    event_init();
    config_init();

    g_httpd = evhttp_start(setting->listen_host, setting->listen_port);
    evhttp_set_gencb(g_httpd, request_handler, NULL);
    event_dispatch();

    return 0;
}
int ulEventHttpServerSetup(const char *address, unsigned short port, const char* path, data_processor_function data_processor) {
  struct evhttp* evh = NULL;
  debug("Setting up event-based http server listening at %s:%d on path: %s", address, port, path);

  evh = evhttp_new(eventbase);

  if(evh != NULL) {
    info("Event-based http server at %s:%d on path: %s has been setup", address, port, path);
  }
  else {
    error("Setup of event-based http server at %s:%d on path: %s FAILED", address, port, path);
    return UL_RETURN_FAIL;
  }

  if(evhttp_bind_socket(evh, address, port) != -1) {
    info("Event-based http server socket bind with %s:%d OK", address, port);
  }
  else {
    error("Bind of event-based http server with %s:%d FAILED", address, port);
    return UL_RETURN_FAIL;
  }

  //when a request for a generic path comes to the server, trigger the ulEventHttpServerProcessRequest
  //function and also pass to it a pointer to an external data_processor function, which is
  //able to handle the received data specifically
  evhttp_set_gencb(evh, ulEventHttpServerProcessRequest, data_processor);

  sprintf(input_http_path, "/%s", path);
  debug("Setting up static path to: %s", input_http_path);

  return UL_RETURN_OK;
}
void *CHttpServer::http_start_server(void *arg)
{
	CHttpServer *pthis = (CHttpServer *)arg;
	struct evhttp *httpd = NULL;
    	
	event_init();
	httpd = evhttp_start(pthis->m_http_addr, pthis->m_http_port);
	if (NULL == httpd) {
           printf("http server unable to listen on %s:%d\n\n", pthis->m_http_addr, pthis->m_http_port);
	   return NULL; 
    }
    evhttp_set_timeout(httpd, pthis->m_timeout);       
    evhttp_set_gencb(httpd, http_handle_postdata, arg);

#ifdef DEBUG
	printf("http_server start:%s:%d timeout:%u\n", 
			pthis->m_http_addr, 
			pthis->m_http_port, 
			pthis->m_timeout);
#else
	logrun("http_server start:%s:%d timeout:%u", 
			pthis->m_http_addr, 
			pthis->m_http_port, 
			pthis->m_timeout);
#endif
	event_dispatch();
	evhttp_free(httpd);
	
	return NULL;
}
 static void HHVM_METHOD(EventHttp, setDefaultCallback, const Object &cb, const Variant &arg) {
     EventHttpResourceData *resource_data = FETCH_RESOURCE(this_, EventHttpResourceData, s_event_http);
     cb.get()->incRefCount();
     resource_data->setDefaultCallback(cb.get());
     resource_data->setDefaultCallbackArg(arg);
     evhttp_set_gencb((evhttp_t *)resource_data->getInternalResourceData(), event_http_default_cb, (void *) resource_data);
 }
Exemple #6
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);
}
Exemple #7
0
int httpserver_start(int port, int backlog)  
{  
    int ret;  
    int fd = httpserver_bindsocket(port, backlog);  
    if (fd < 0)   
    {     
        return -1;  
        printf("httpserver_bindsocket error !\n");  
    }  
    struct event_base *base = event_init();  
    if (base == NULL)   
    {  
        printf("event_init error !\n");  
        return -1;        
    }  
    struct evhttp *httpd = evhttp_new(base);  
    if (httpd == NULL)   
    {  
        printf("enhttp_new error !\n");  
        return -1;  
    }  
    ret = evhttp_accept_socket(httpd, fd);  
    if (ret != 0)   
    {  
        printf("evhttp_accept_socket error \n");  
        return -1;  
    }  
    evhttp_set_gencb(httpd, httpserver_handler, NULL);  
    event_base_dispatch(base);  
    return 0;  
}  
Exemple #8
0
int main(int argc, char **argv)
{
	int retval;
	void *handle = NULL;
	short	http_port = 8081;
	// Binds on IPv4 & IPv6, refer to /proc/sys/net/ipv6/bindv6only
	char	*http_addr = "::";
	struct	evhttp *http_server = NULL;

	cweb_init();
	retval = init_pages();
	if (retval) {
		printf("[ERROR] loading of plugins failed.\n");
		return EXIT_FAILURE;
	}

	event_init();
	http_server = evhttp_start(http_addr, http_port);
	evhttp_set_gencb(http_server, cweb_request_handler, NULL);

	fprintf(stderr, "Server started on port %d\n", http_port);
	event_dispatch();

	return(0);
}
Exemple #9
0
int
main(int argc, char **argv)
{
  // initialize libraries
  struct evhttp *httpd;

  if (sigignore(SIGPIPE) == -1) {
    perror("failed to ignore SIGPIPE; sigaction");
    exit(EXIT_FAILURE);
  }

  host = argv[2];
  port = atoi(argv[3]);
  event_init();
  httpd = evhttp_start("0.0.0.0", atoi(argv[1]));
  if (httpd == NULL) {
    perror("evhttpd failed!");
    exit(1);
  }

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

  event_dispatch();
  /* Not reached in this code as it is now. */
  evhttp_free(httpd);

  return EXIT_SUCCESS;
}
Exemple #10
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;
}
Exemple #11
0
static void playlistcontainer_loaded(sp_playlistcontainer *pc, void *userdata) {
  syslog(LOG_DEBUG, "playlistcontainer_loaded\n");
  sp_session *session = userdata;
  struct state *state = sp_session_userdata(session);

  sp_playlistcontainer_remove_callbacks(pc, &playlistcontainer_callbacks, session);

  state->http = evhttp_new(state->event_base);
  evhttp_set_timeout(state->http, 60);
  evhttp_set_gencb(state->http, &handle_request, state);

  // Bind HTTP server
  int bind = evhttp_bind_socket(state->http, state->http_host,
                                state->http_port);

  if (bind == -1) {
    syslog(LOG_WARNING, "Could not bind HTTP server socket to %s:%d",
           state->http_host, state->http_port);
    sp_session_logout(session);
    return;
  }

  syslog(LOG_DEBUG, "HTTP server listening on %s:%d", state->http_host,
         state->http_port);
}
Exemple #12
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);
}
Exemple #13
0
static void StartEventHandler(KonohaContext *kctx, void *args)
{
	KNH_ASSERT(EVENTAPI eventContext == NULL);
	struct EventContext *eventContext = (struct EventContext *)PLATAPI malloc_i(sizeof(struct EventContext));
	bzero(eventContext, sizeof(struct EventContext));
	((KonohaFactory *)kctx->platApi)->EventModule.eventContext = eventContext;

	eventContext->safePointRef = (int *)&kctx->safepoint;

	eventContext->queue = (LocalQueue *)PLATAPI malloc_i(sizeof(LocalQueue));
	LocalQueue_Init(kctx, eventContext->queue);

	eventContext->httpContext = httpContext;

	pthread_mutex_init(&eventContext->lock, NULL);
	pthread_cond_init(&eventContext->cond, NULL);

	KNH_ASSERT(args != NULL);
	Ip *ip = (Ip *)args;
	struct event_base *base = event_base_new();
	struct evhttp *httpd = evhttp_new(base);
	KNH_ASSERT(evhttp_bind_socket(httpd, ip->host, ip->port) >= 0);
	evhttp_set_gencb(httpd, http_handler, (void *)eventContext);
	eventContext->base = base;
	eventContext->httpd = httpd;

	pthread_t t;
	pthread_create(&t, NULL, HttpEventListener, (void *)eventContext);
}
Exemple #14
0
LibEventServer::LibEventServer(const ServerOptions &options)
  : Server(options.m_address, options.m_port, options.m_numThreads),
    m_accept_sock(options.m_serverFD),
    m_accept_sock_ssl(options.m_sslFD),
    m_dispatcher(options.m_numThreads, RuntimeOption::ServerThreadRoundRobin,
                 RuntimeOption::ServerThreadDropCacheTimeoutSeconds,
                 RuntimeOption::ServerThreadDropStack,
                 this, RuntimeOption::ServerThreadJobLIFOSwitchThreshold,
                 RuntimeOption::ServerThreadJobMaxQueuingMilliSeconds,
                 kNumPriorities, Util::num_numa_nodes()),
    m_dispatcherThread(this, &LibEventServer::dispatch) {
  m_eventBase = event_base_new();
  m_server = evhttp_new(m_eventBase);
  m_server_ssl = nullptr;
  evhttp_set_connection_limit(m_server, RuntimeOption::ServerConnectionLimit);
  evhttp_set_gencb(m_server, on_request, this);
#ifdef EVHTTP_PORTABLE_READ_LIMITING
  evhttp_set_read_limit(m_server, RuntimeOption::RequestBodyReadLimit);
#endif
  m_responseQueue.create(m_eventBase);

  if (!options.m_takeoverFilename.empty()) {
    m_takeover_agent.reset(new TakeoverAgent(options.m_takeoverFilename));
  }
}
Exemple #15
0
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);
}
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);
}
Exemple #17
0
static void* thread_worker(void *arg) {
  struct args *args = (struct args*) arg;
  struct event_base *base = event_base_new();
  struct evhttp *evh = evhttp_new(base);
  evhttp_accept_socket(evh, args->fd);
  evhttp_set_gencb(evh, doit, (void *) evbuffer_new());
  event_base_dispatch(base);
}
Exemple #18
0
static void start_srv (struct event_base *base, gchar *in_dir)
{
    struct evhttp *http;

    http = evhttp_new (base);
    evhttp_bind_socket (http, "127.0.0.1", 8011);
    evhttp_set_gencb (http, on_srv_request, in_dir);
}
static void start_srv (struct event_base *base, gchar *in_dir)
{
    app->http_srv = evhttp_new (base);
    g_assert (app->http_srv);
    evhttp_bind_socket (app->http_srv, "127.0.0.1", 8011);
    evhttp_set_gencb (app->http_srv, on_srv_gen_request, in_dir);

    LOG_debug (HTTP_TEST, "SRV: started");
}
bool InitHTTPServer()
{
    if (!InitHTTPAllowList())
        return false;

    if (gArgs.GetBoolArg("-rpcssl", false)) {
        uiInterface.ThreadSafeMessageBox(
            "SSL mode for RPC (-rpcssl) is no longer supported.",
            "", CClientUIInterface::MSG_ERROR);
        return false;
    }

    // Redirect libevent's logging to our own log
    event_set_log_callback(&libevent_log_cb);
    // Update libevent's log handling. Returns false if our version of
    // libevent doesn't support debug logging, in which case we should
    // clear the BCLog::LIBEVENT flag.
    if (!UpdateHTTPServerLogging(g_logger->WillLogCategory(BCLog::LIBEVENT))) {
        g_logger->DisableCategory(BCLog::LIBEVENT);
    }

#ifdef WIN32
    evthread_use_windows_threads();
#else
    evthread_use_pthreads();
#endif

    raii_event_base base_ctr = obtain_event_base();

    /* Create a new evhttp object to handle requests. */
    raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
    struct evhttp* http = http_ctr.get();
    if (!http) {
        LogPrintf("couldn't create evhttp. Exiting.\n");
        return false;
    }

    evhttp_set_timeout(http, gArgs.GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
    evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
    evhttp_set_max_body_size(http, MAX_SIZE);
    evhttp_set_gencb(http, http_request_cb, nullptr);

    if (!HTTPBindAddresses(http)) {
        LogPrintf("Unable to bind any endpoint for RPC server\n");
        return false;
    }

    LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
    int workQueueDepth = std::max((long)gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
    LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);

    workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
    // transfer ownership to eventBase/HTTP via .release()
    eventBase = base_ctr.release();
    eventHTTP = http_ctr.release();
    return true;
}
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  ---------- */
LibEventServer::LibEventServer(const std::string &address, int port,
                               int thread, int timeoutSeconds)
  : Server(address, port, thread),
    m_accept_sock(-1),
    m_timeoutThreadData(thread, timeoutSeconds),
    m_timeoutThread(&m_timeoutThreadData, &TimeoutThread::run),
    m_dispatcher(thread, this),
    m_dispatcherThread(this, &LibEventServer::dispatch) {
  m_eventBase = event_base_new();
  m_server = evhttp_new(m_eventBase);
  evhttp_set_gencb(m_server, on_request, this);
  m_responseQueue.create(m_eventBase);
}
Exemple #23
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;
}
Exemple #24
0
void InterruptHTTPServer()
{
    LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
    if (eventHTTP) {
        // Unlisten sockets
        for (evhttp_bound_socket *socket : boundSockets) {
            evhttp_del_accept_socket(eventHTTP, socket);
        }
        // Reject requests on current connections
        evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL);
    }
    if (workQueue)
        workQueue->Interrupt();
}
Exemple #25
0
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;
}
HttpServer::HttpServer(std::string base_addr, int base_port) {
  base = NULL;
  base = event_init();
  internal_url = base_addr;
  internal_port = base_port;

  // Bind the address to the internal callback method
  struct evhttp *httpd;
  httpd = evhttp_new(base);
  if (httpd != NULL) {
    if (evhttp_bind_socket(httpd, internal_url.c_str(), internal_port) == 0) {
      evhttp_set_gencb(httpd, process_request, NULL);
    }
  }
}
bool HttpService::Init()
{
    bool ret = false;
    do
    {
        evthread_use_pthreads();
        base_ = event_base_new();
        if (!base_)
        {
            LOG_ERROR("create event base failed!");
            break;
        }

        dnsbase_ = evdns_base_new(base_, 1);
        if (!dnsbase_)
        {
            LOG_ERROR("create dnsbase failed!");
            break;
        }

        http_server_ = evhttp_new(base_);
        if (!http_server_)
        {
            LOG_ERROR("create evhttp failed!");
            break;
        }

        evhttp_set_allowed_methods(http_server_, 
            EVHTTP_REQ_CONNECT |
            EVHTTP_REQ_GET |
            EVHTTP_REQ_POST |
            EVHTTP_REQ_HEAD |
            EVHTTP_REQ_PUT |
            EVHTTP_REQ_DELETE);

        if (evhttp_accept_socket(http_server_, sock_) != 0)
        {
            LOG_ERROR("accept socket failed!");
            break;
        }

        evhttp_set_gencb(http_server_, HttpGenericCallback, this);
        ret = true;

    } while(0);

    return ret;
}
static void run_request_test (struct event_base *evbase, struct evdns_base *dns_base, TestID test_id)
{
    OutData *out;
    struct evbuffer *in_buf;
    char c = 'x';

    LOG_debug (HTTP_TEST, "===================== TEST ID : %d  =======================", test_id);
    out = g_new0 (OutData, 1);
    out->evbase = evbase;
    out->test_id = test_id;

    out->evhttp = evhttp_new (evbase);
    evhttp_bind_socket (out->evhttp, "127.0.0.1", 8080);
    evhttp_set_gencb (out->evhttp, on_request_gencb, out);
    
    //out->http = http_client_create (evbase, dns_base);
    in_buf = evbuffer_new ();

    http_client_set_cb_ctx (out->http, out);
    http_client_set_on_chunk_cb (out->http, on_input_data_cb);
    http_client_set_close_cb (out->http, on_http_close);


    //http_client_set_output_length (out->http, 1);
    //http_client_add_output_data (out->http, &c, 1);

    http_client_start_request_to_storage_url (out->http, Method_get, "/index.html", NULL, NULL);
    
    event_base_dispatch (evbase);
    
    http_client_destroy (out->http);

    LOG_debug (HTTP_TEST, "Resulting buff: %zd", evbuffer_get_length (in_buf));
    evbuffer_free (in_buf);

    g_free (out->first_line);
    g_free (out->header_line);
    evconnlistener_free (out->listener);
    evtimer_del (out->timeout);
    event_free (out->timeout);
    evbuffer_free (out->out_buf);
    evbuffer_free (out->in_file);

    g_free (out);
    LOG_debug (HTTP_TEST, "===================== END TEST ID : %d  =======================", test_id);

}
bool LibEventServer::enableSSL(void *sslCTX, int port) {
#ifdef _EVENT_USE_OPENSSL
  m_server_ssl = evhttp_new_openssl_ctx(m_eventBase, sslCTX);
  if (m_server_ssl == nullptr) {
    Logger::Error("evhttp_new_openssl_ctx failed");
    return false;
  }
  m_port_ssl = port;
  evhttp_set_connection_limit(m_server_ssl,
                              RuntimeOption::ServerConnectionLimit);
  evhttp_set_gencb(m_server_ssl, on_request, this);
  return true;
#else
  Logger::Error("A SSL enabled libevent is required");
  return false;
#endif
}
Exemple #30
0
int main(int argc, char **argv) {
	int cli;
	int sock = BindSocket(12345);
	struct config conf;
	conf.store = store_open("tracker.db");
	conf.max_peer_return=50;
	conf.min_interval=300;
	conf.max_peer_return=48;
	struct event_base *base = event_init();
	struct evhttp *httpd;
	httpd = evhttp_new(base);
	cli = evhttp_accept_socket(httpd, sock);
	evhttp_set_gencb(httpd, tracker, (void *)&conf);
	event_base_dispatch(base);

	return 0;
}