예제 #1
0
bool CDNSManager::__init__()
{
    if (m_evbase && m_dnsbase)    return true;
    
    m_evbase = event_base_new();
    if (!m_evbase)
    {
        LOG_ERROR_STREAM << "Fail to call event_base_new().";
        return false;
    }

    m_dnsbase = evdns_base_new(m_evbase, 1);
    if (!m_dnsbase)
    {
        LOG_ERROR_STREAM << "Fail to call evdns_base_new().";
        return false;
    }
    
    return true;
}
예제 #2
0
void func(const std::string& commandStr)
{
	g_SubscribeMutex.lock();
	struct event_base *m_base = event_base_new();

	redisAsyncContext *m_redis = redisAsyncConnect("127.0.0.1", 6379);
	if (m_redis->err) {
		/* Let *c leak for now... */
		printf("Error: %s\n", m_redis->errstr);
	}
	redisAsyncCommand(m_redis,authCallback, (char*) "auth", "auth %s", "014006");

	redisLibeventAttach(m_redis, m_base);
	redisAsyncSetConnectCallback(m_redis, connectCallback);
	redisAsyncSetDisconnectCallback(m_redis, disconnectCallback);

	redisAsyncCommand(m_redis, subscribeCallback, (char*) "sub", commandStr.c_str());
	g_SubscribeMutex.unlock();
	event_base_dispatch(m_base);
}
예제 #3
0
int main(int argc,char **argv)
{
	struct event_base * base = event_base_new();
	struct sockaddr_in addr ;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(0);
	addr.sin_port = htons(3333);
	set_timer(base);
	struct evconnlistener * lev ;
	lev = evconnlistener_new_bind(base,accept_conn_cb,NULL,
		LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
		-1,(struct sockaddr*)&addr,sizeof(addr));

	evconnlistener_set_error_cb(lev,listener_error_cb);

	event_base_dispatch(base);
	evconnlistener_free(lev);
	event_base_free(base);
	return 0;
}
예제 #4
0
bool Master::StartMaster(int argc, char *argv[])
{
	if (0 != conf_para.InitPara(argc, argv))
		return false;

	std::cout << "Start Master" << std::endl;

	if (!m_worker.Init(this))
	{
		std::cerr<< "Master: Worker::Init()" << std::endl;
		return false;
	}

	nums_of_child = conf_para.MaxWorker;

	//创建一定数量的worker
	while (nums_of_child > 0)
	{
		switch (fork())
		{
			case -1:
				std::cerr<< "Master: StartMaster(): fork()" << std::endl;
				return false;
			case 0:
				m_worker.Run();
				return true;
			default:
				--nums_of_child;
				break;
		}
	}

	m_base = event_base_new();
	m_exit_event = evsignal_new(m_base, SIGINT, Master::MasterExitSignal, m_base);
	m_chld_event = evsignal_new(m_base, SIGCHLD, Master::MasterChldSignal, this);
	evsignal_add(m_exit_event, NULL);
	evsignal_add(m_chld_event, NULL);
	event_base_dispatch(m_base);

	return true;
}
예제 #5
0
int main(int argc, char *argv[])
{
    void *sighandle;
    struct sockaddr_in addr;
    server serv;

    if(argc<2)
        return 2;

    serv.base = event_base_new();
    assert(serv.base);

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    addr.sin_port = htons(atoi(argv[1]));

    serv.listener = evconnlistener_new_bind(serv.base, newconn, &serv,
                                            LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
                                            4, (struct sockaddr*)&addr, sizeof(addr));
    assert(serv.listener);

    evconnlistener_set_error_cb(serv.listener, listenerr);

    sighandle = setsighandle(serv.base);

    printf("Running\n");
    event_base_loop(serv.base, 0);
    printf("Stopping\n");

    evconnlistener_free(serv.listener);

    cancelsighandle(sighandle);

    event_base_free(serv.base);

    memset(&serv, 0, sizeof(serv));

    printf("Done\n");
    return 0;
}
int tcp_start_up(){

	WSADATA WSAData;

	struct event_base *base;
    struct evconnlistener *listener;
    struct sockaddr_in sin;

    int port = 22222;
	WSAStartup(0x101, &WSAData);
      
    base = event_base_new();
    if (!base) {
            puts("Couldn't open event base");
            return 1;
    }

    /* Clear the sockaddr before using it, in case there are extra
        * platform-specific fields that can mess us up. */
    memset(&sin, 0, sizeof(sin));
    /* This is an INET address */
    sin.sin_family = AF_INET;
    /* Listen on 0.0.0.0 */
    sin.sin_addr.s_addr = htonl(0);
    /* Listen on the given port. */
    sin.sin_port = htons(port);

    listener = evconnlistener_new_bind(base, accept_conn_cb, NULL,
        LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
        (struct sockaddr*)&sin, sizeof(sin));
    if (!listener) {
            perror("Couldn't create listener");
            return 1;
    }

    evconnlistener_set_error_cb(listener, accept_error_cb);
	printf("ready to dispatch...\n");
    event_base_dispatch(base);
	
    return 0;
}
예제 #7
0
파일: test-fdleak.c 프로젝트: sambuc/netbsd
/* Start the server listening on a random port and start the first client. */
static void
start_loop(void)
{
	struct event_base *base;
	struct evconnlistener *listener;
	struct sockaddr_storage ss;
	ev_socklen_t socklen = sizeof(ss);
	evutil_socket_t fd;

	base = event_base_new();
	if (base == NULL) {
		puts("Could not open event base!");
		exit(1);
	}

	listener = evconnlistener_new_bind(base, listener_accept_cb, NULL,
	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
	    -1, (struct sockaddr *)&saddr, sizeof(saddr));
	if (listener == NULL) {
		my_perror("Could not create listener!");
		exit(1);
	}
	fd = evconnlistener_get_fd(listener);
	if (fd < 0) {
		puts("Couldn't get fd from listener");
		exit(1);
	}
	if (getsockname(fd, (struct sockaddr *)&ss, &socklen) < 0) {
		my_perror("getsockname()");
		exit(1);
	}
	memcpy(&saddr, &ss, sizeof(saddr));
	if (saddr.sin_family != AF_INET) {
		puts("AF mismatch from getsockname().");
		exit(1);
	}

	start_client(base);

	event_base_dispatch(base);
}
void run(void)
{
    evutil_socket_t listener;
    struct sockaddr_in sin;
    struct event_base *base;
    struct event *listener_event;

    base = event_base_new();
    if (!base)
        return; /*XXXerr*/

    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = 0;
    sin.sin_port = htons(40713);

    listener = socket(AF_INET, SOCK_STREAM, 0);
    evutil_make_socket_nonblocking(listener);

#ifndef WIN32
    {
        int one = 1;
        setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    }
#endif

    if (bind(listener, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
        perror("bind");
        return;
    }

    if (listen(listener, 16)<0) {
        perror("listen");
        return;
    }

    listener_event = event_new(base, listener, EV_READ|EV_PERSIST, do_accept, (void*)base);
    /*XXX check it */
    event_add(listener_event, NULL);

    event_base_dispatch(base);
}
예제 #9
0
파일: time-test.c 프로젝트: 00datman/ompi
int
main(int argc, char **argv)
{
	struct event timeout;
	struct timeval tv;
	struct event_base *base;
	int flags;

#ifdef WIN32
	WORD wVersionRequested;
	WSADATA wsaData;

	wVersionRequested = MAKEWORD(2, 2);

	(void)WSAStartup(wVersionRequested, &wsaData);
#endif

	if (argc == 2 && !strcmp(argv[1], "-p")) {
		event_is_persistent = 1;
		flags = EV_PERSIST;
	} else {
		event_is_persistent = 0;
		flags = 0;
	}

	/* Initalize the event library */
	base = event_base_new();

	/* Initalize one event */
	event_assign(&timeout, base, -1, flags, timeout_cb, (void*) &timeout);

	evutil_timerclear(&tv);
	tv.tv_sec = 2;
	event_add(&timeout, &tv);

	evutil_gettimeofday(&lasttime, NULL);

	event_base_dispatch(base);

	return (0);
}
예제 #10
0
int main()
{
    struct Allocator* alloc = MallocAllocator_new(1<<20);

    struct Writer* logwriter = FileWriter_new(stdout, alloc);
    struct Log* logger = &(struct Log) { .writer = logwriter };

    struct event_base* eventBase = event_base_new();

    struct CryptoAuth* ca = CryptoAuth_new(NULL, alloc, NULL, eventBase, logger);
    uint8_t publicKey[32];
    CryptoAuth_getPublicKey(publicKey, ca);
    CryptoAuth_addUser(String_CONST("passwd"), 1, (void*)0x01, ca);

    struct SwitchCore* switchCore = SwitchCore_new(logger, alloc);
    struct Message* message;
    struct Interface iface = {
        .sendMessage = messageFromInterface,
        .senderContext = &message,
        .allocator = alloc
    };
    SwitchCore_setRouterInterface(&iface, switchCore);

    // These are unused.
    struct DHTModuleRegistry* registry = DHTModuleRegistry_new(alloc);
    struct RouterModule* rm =
        RouterModule_register(registry, alloc, publicKey, eventBase, logger, NULL);

    struct InterfaceController* ifController =
        DefaultInterfaceController_new(ca, switchCore, rm, logger, eventBase, NULL, alloc);

    ////////////////////////

    return reconnectionNewEndpointTest(ifController,
                                       publicKey,
                                       &message,
                                       alloc,
                                       eventBase,
                                       logger,
                                       &iface);
}
예제 #11
0
void init_server(int port) {
    fprintf(stderr, "Using port %d\n", port);

    clients = NULL;

    // Make it thread safe
    int err = evthread_use_pthreads();
    if (err != 0)
    {
        fprintf(stderr, "Unable to make libevent thread safe");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in sin;

    // Create a new event base
    base = event_base_new();
    if (!base)
    {
        fprintf(stderr, "Unable to open event base\n");
        exit(EXIT_FAILURE);
    }

    // Set up the socket
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = 0;
    sin.sin_port = htons(port);

    // Create a new listener
    listener = evconnlistener_new_bind(base, accept_connection, NULL,
            LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1,
            (struct sockaddr *) &sin, sizeof(sin));
    if (!listener)
    {
        perror("Unable to create listener");
        exit(EXIT_FAILURE);
    }

    evconnlistener_set_error_cb(listener, accept_error);
}
예제 #12
0
int main(int argc, char *argv[])
{
    struct evdns_base *evdns_base;

    if (options_parse(&app_context, argc, argv) != 0) {
        return 1;
    }
#ifdef _WIN32
    WSADATA wsa_data;
    WSAStartup(MAKEWORD(2, 2), &wsa_data);
#endif
    if ((app_context.event_loop = event_base_new()) == NULL) {
        perror("event_base_new");
        return 1;
    }
    if ((evdns_base = evdns_base_new(app_context.event_loop, 0)) == NULL) {
        perror("evdns_base");
        return 1;
    }
    evdns_base_set_option(evdns_base, "use-tcp", "on-tc");
    evdns_base_set_option(evdns_base, "randomize-case", "0");
    if (evdns_base_nameserver_ip_add(evdns_base,
                                     app_context.resolver_ip) != 0) {
        fprintf(stderr, "Unable to use [%s] as a resolver\n",
                app_context.resolver_ip);
        return 1;
    }
    if (app_context.want_ipv6 != 0) {
        evdns_base_resolve_ipv6(evdns_base, app_context.host_name,
                                DNS_QUERY_NO_SEARCH,
                                ipv6_query_cb, &app_context);
    } else {
        evdns_base_resolve_ipv4(evdns_base, app_context.host_name,
                                DNS_QUERY_NO_SEARCH,
                                ipv4_query_cb, &app_context);
    }
    event_base_dispatch(app_context.event_loop);
    event_base_free(app_context.event_loop);

    return 0;
}
예제 #13
0
LibEventServer::LibEventServer(const std::string &address, int port,
                               int thread, int timeoutSeconds)
  : Server(address, port, thread),
    m_accept_sock(-1),
    m_accept_sock_ssl(-1),
    m_timeoutThreadData(thread, timeoutSeconds),
    m_timeoutThread(&m_timeoutThreadData, &TimeoutThread::run),
    m_dispatcher(thread, RuntimeOption::ServerThreadRoundRobin,
                 RuntimeOption::ServerThreadDropCacheTimeoutSeconds,
                 this, RuntimeOption::ServerThreadJobLIFO),
    m_dispatcherThread(this, &LibEventServer::dispatch) {
  m_eventBase = event_base_new();
  m_server = evhttp_new(m_eventBase);
  m_server_ssl = NULL;
  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);
}
예제 #14
0
int main(){
	int fd = socket(AF_INET,SOCK_STREAM,0);
	struct sockaddr_in addr;
	memset(&addr,0,sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(5000);
	addr.sin_addr.s_addr = INADDR_ANY;
	int ret = bind(fd,(struct sockaddr*)&addr,sizeof(addr));
	assert(ret!=-1);
	ret = listen(fd,5);
	assert(ret!=-1);
	struct event_base* base = event_base_new();
	struct event* ev = event_new(base,fd,EV_READ|EV_PERSIST,on_accept,base);
	//struct event* ev = event_new(base,fd,EV_READ,on_accept,base);
	event_add(ev,NULL);
	event_base_dispatch(base);
	event_free(ev);
	event_base_free(base);
	libevent_global_shutdown();
	return 0;
}
예제 #15
0
파일: server.c 프로젝트: GangXu/pulsar
void
server_start(server *s) {
	int i;

	s->base = event_base_new();
	s->signal = event_new(s->base, SIGINT, EV_SIGNAL|EV_PERSIST, &server_sig_handler, s);
	event_add(s->signal, NULL);

	s->fd = server_setup_socket(s->cfg->ip, s->cfg->port);
	assert(s->fd != -1);

	/* start workers */
	for(i=0; i<s->cfg->workers; i++) {
		worker_start(s->w[i]);
	}

	event_base_dispatch(s->base);

	server_free(s);
	exit(EXIT_SUCCESS);
}
예제 #16
0
int main (int argc, char **argv)
{
	event_base* eb = event_base_new();
	bufferevent *be = bufferevent_socket_new(eb, -1, BEV_OPT_CLOSE_ON_FREE);
	bufferevent_setcb(be, read_cb, write_cb, event_cb, NULL);
	sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr("192.168.1.100");
	addr.sin_port = htons(7001);

	if (bufferevent_socket_connect(be, (sockaddr*)&addr, sizeof(addr)) < 0)
	{
		printf("connect error\n");
		bufferevent_free(be);
		return -1;
	}
	bufferevent_enable(be, EV_READ);
	event_base_dispatch(eb);
	return 0;
}
예제 #17
0
int main(int argc, char** argv)
{

  int listener = tcp_server_init(9999, 10);
  if( listener == -1 )
  {
    perror(" tcp_server_init error ");
    return -1;
  }

  struct event_base* base = event_base_new();

  //添加监听客户端请求连接事件
  struct event* ev_listen = event_new(base, listener, EV_READ | EV_PERSIST,accept_cb, base);
  event_add(ev_listen, NULL);
  event_base_dispatch(base);

  printf("服务器启动.....\n");

  return 0;
}
예제 #18
0
void feature_test ()
{
    /* supported async */
    const char ** methods = event_get_supported_methods(); 
    if (methods) {
        int i = 0;
        while(methods[i]) {
            printf ("method %d : <%s>\n", i+1, methods[i]);
            i++;
        }
    }

    /* get the default async method */
	base = event_base_new();
    const char * bb = event_base_get_method(base);
    printf("default method is <%s>\n", bb);     /* epoll */

	print_features(base);

	event_base_free(base);
}
예제 #19
0
int TcpClient(int & exit, void * arg)
{
	bufferevent *bev =NULL;

	base = event_base_new();

	printf("event_base_dispatch \n");

	{
		timer_param_t * param = new(timer_param_t);
		param->ev = evtimer_new(base, timercb_cli, param);
		param->tv.tv_sec = 0;
		param->tv.tv_usec = 2*1000*1000;
		param->timercb_arg =bev;
		evtimer_add(param->ev, &param->tv);
	}

	int rt =event_base_dispatch(base);
	printf("event_base_dispatch return %d \n", rt);
	return 0;
}
예제 #20
0
void setup_events(global_resources_struct *global_resources) {
	struct event_base *base = event_base_new();
	if (base == NULL) everror_and_exit("event_base_new");
	global_resources->bases.base = base;
	
	struct evdns_base *dns_base = evdns_base_new(base, EVDNS_BASE_INITIALIZE_NAMESERVERS);
	if (dns_base == NULL) everror_and_exit("evdns_base_new");
	if (evdns_base_set_option(dns_base, "randomize-case", "0")) everror_and_exit("evdns_base_set_option");
	global_resources->bases.dns_base = dns_base;
	
	struct event *int_signal_event = evsignal_new(base, INTERRUPT_SIGNAL, signal_cb, global_resources->bases.base);
	if (int_signal_event == NULL) everror_and_exit("evsignal_new");
	global_resources->int_signal_event = int_signal_event;
	if (event_add(int_signal_event, NULL)) everror_and_exit("event_add");
	
	struct event *server_event = event_new(base, global_resources->server_sockfd, EV_READ|EV_PERSIST,
			server_accept_cb, &global_resources->bases);
	if (server_event == NULL) everror_and_exit("event_new");
	global_resources->server_event = server_event;
	if (event_add(server_event, NULL)) everror_and_exit("event_add");
}
예제 #21
0
/**
 * setup the notification-fd of a event-thread
 *
 * all event-threads listen on the same notification pipe
 *
 * @see chassis_event_handle()
 */ 
int chassis_event_threads_init_thread(chassis_event_thread_t *thread, chassis *chas) {
    thread->event_base = event_base_new();
    thread->chas = chas;

    int fds[2];
    if (pipe(fds)) {
        int err;
        err = errno;
        g_log_dbproxy(g_error, "evutil_socketpair() failed: %s (%d)", 
                g_strerror(err),
                err);
    }
    thread->notify_receive_fd = fds[0];
    thread->notify_send_fd = fds[1];

    event_set(&(thread->notify_fd_event), thread->notify_receive_fd, EV_READ | EV_PERSIST, chassis_event_handle, thread);
    event_base_set(thread->event_base, &(thread->notify_fd_event));
    event_add(&(thread->notify_fd_event), NULL);

    return 0;
}
예제 #22
0
파일: webif.cpp 프로젝트: qdk0901/webif
int
main(int argc, char ** argv) {
    evbase_t * evbase = event_base_new();
    evhtp_t  * htp    = evhtp_new(evbase, NULL);
    
    evhtp_set_cb(htp, "/test", webif_test, NULL);
	evhtp_set_gencb(htp, webif_default, NULL);
	
#ifndef EVHTP_DISABLE_EVTHR
    evhtp_use_threads(htp, NULL, 8, NULL);
#endif
    evhtp_bind_socket(htp, "0.0.0.0", 8081, 2048);

    event_base_loop(evbase, 0);

    evhtp_unbind_socket(htp);
    evhtp_free(htp);
    event_base_free(evbase);

    return 0;
}
예제 #23
0
파일: rpc.c 프로젝트: dyustc/searaft
int main() {
    struct event_base *base = event_base_new();
    struct rpc_target dest = { HTTP, "127.0.0.1", 12321 };

    struct rpc_context *c = init_rpc(base);
    init_rpc_client(c);

    json_int_t i = 40;
    struct data_t param1 = { RPC_INT, &i, NULL, 0};
    const struct data_t* param[] = { &param1 };
    struct method_t m = {"test1", (struct data_t**)param, 1};
    int j = 42;
    rpc_call(c, &dest, &m, test1_cb, &j);

    event_base_dispatch(base);

    deinit_rpc(c);
    event_base_free(base);

    return 0;
}
예제 #24
0
void core::curl_handler::start()
{
    multi_handle_ = curl_multi_init();

    curl_multi_setopt(multi_handle_, CURLMOPT_SOCKETFUNCTION, socket_callback);
    curl_multi_setopt(multi_handle_, CURLMOPT_SOCKETDATA, this);

    curl_multi_setopt(multi_handle_, CURLMOPT_TIMERFUNCTION, timer_callback);
    curl_multi_setopt(multi_handle_, CURLMOPT_TIMERDATA, this);

    event_base_ = event_base_new();
    timer_event_ = evtimer_new(event_base_, event_timer_callback, this);
    start_task_event_ = event_new(event_base_, -1, EV_PERSIST, start_task_callback, this);
     
    keep_working_ = true;

    event_loop_thread_ = std::thread([this]()
    {
        event_base_loop(event_base_, EVLOOP_NO_EXIT_ON_EMPTY);
    });
}
예제 #25
0
Loop::Loop() :
	_id(0),
	_base(NULL),
	_thread(NULL),
	_frameEvent(NULL),
	_frameRound(0),
	_isStopping(false),
	_asyncPendingCount(0)
{
	s_mutex.lock();
	s_idGenerater++;
	_id = s_idGenerater;
	if (s_loops.empty())
	{
		Loop::init();
	}
	s_loops[_id] = this;
	s_mutex.unlock();

	_base = event_base_new();
}
예제 #26
0
BasicDelayedEventQueue::BasicDelayedEventQueue(DelayedEventQueueCallbacks* callbacks) {
	_callbacks = callbacks;
#ifndef _WIN32
	evthread_use_pthreads();
#else
	evthread_use_windows_threads();
#endif
	_eventLoop = event_base_new();

	// see here: https://github.com/named-data/ndn.cxx/blob/master/scheduler/scheduler.cc
	// and here: https://www.mail-archive.com/[email protected]/msg01676.html
	timeval tv;
	tv.tv_sec = 365 * 24 * 3600;
	tv.tv_usec = 0;
	_dummyEvent = evtimer_new(_eventLoop, dummyCallback, &_dummyEvent);
	evtimer_add(_dummyEvent, &tv);

	_thread = NULL;
	_isStarted = false;
	start();
}
예제 #27
0
파일: hello-world.c 프로젝트: TomCN7/Event
int
main(int argc, char **argv)
{
	struct event_base *base;
	struct evconnlistener *listener;

	struct sockaddr_in sin;
#ifdef _WIN32
	WSADATA wsa_data;
	WSAStartup(0x0201, &wsa_data);
#endif

	base = event_base_new();
	if (!base) {
		fprintf(stderr, "Could not initialize libevent!\n");
		return 1;
	}

	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(PORT);

	listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
	    LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
	    (struct sockaddr*)&sin,
	    sizeof(sin));

	if (!listener) {
		fprintf(stderr, "Could not create a listener!\n");
		return 1;
	}
    
	event_base_dispatch(base);

	evconnlistener_free(listener);
	event_base_free(base);

	printf("done\n");
	return 0;
}
예제 #28
0
파일: vpnns.c 프로젝트: cernekee/ocproxy
static void do_packet_loop(int vpn_fd, int tun_fd)
{
	struct packet_loop_ctx ctx;

	if (fcntl(vpn_fd, F_SETFL, O_RDWR | O_NONBLOCK) < 0)
		pdie("can't set O_NONBLOCK on VPN fd");
	if (fcntl(tun_fd, F_SETFL, O_RDWR | O_NONBLOCK) < 0)
		pdie("can't set O_NONBLOCK on tun fd");

	ctx.vpn_fd = vpn_fd;
	ctx.tun_fd = tun_fd;

	ctx.event_base = event_base_new();
	if (!ctx.event_base)
		die("can't initialize libevent\n");

	ctx.vpn_event = event_new(ctx.event_base, vpn_fd, EV_READ | EV_PERSIST,
				  &write_pkt, &ctx);
	ctx.tun_event = event_new(ctx.event_base, tun_fd, EV_READ | EV_PERSIST,
				  &write_pkt, &ctx);
	ctx.sig_event = event_new(ctx.event_base, SIGHUP, EV_SIGNAL,
				  &pkt_loop_signal, &ctx);

	if (!ctx.vpn_event || !ctx.tun_event || !ctx.sig_event)
		die("can't create event structs\n");
	if (event_add(ctx.vpn_event, NULL) ||
	    event_add(ctx.tun_event, NULL) ||
	    event_add(ctx.sig_event, NULL))
		die("can't register event structs\n");

	event_base_dispatch(ctx.event_base);

	event_del(ctx.sig_event);
	event_free(ctx.sig_event);
	event_del(ctx.tun_event);
	event_free(ctx.tun_event);
	event_del(ctx.vpn_event);
	event_free(ctx.vpn_event);
	event_base_free(ctx.event_base);
}
예제 #29
0
static void
test_fin_free_finalize(void *arg)
{
#ifdef EVENT__DISABLE_MM_REPLACEMENT
	tinytest_set_test_skipped_();
#else
	struct event_base *base = NULL;
	struct event *ev, *ev2;
	int ev_called = 0;
	int ev2_called = 0;

	(void)arg;

	event_set_mem_functions(tfff_malloc, tfff_realloc, tfff_free);

	base = event_base_new();

	ev = evtimer_new(base, timer_callback, &ev_called);
	ev2 = evtimer_new(base, timer_callback, &ev2_called);
	tfff_p1 = ev;
	tfff_p2 = ev2;
	event_free_finalize(0, ev, event_finalize_callback_1);
	event_finalize(0, ev2, event_finalize_callback_1);

	event_base_dispatch(base);

	tt_int_op(ev_called, ==, 100);
	tt_int_op(ev2_called, ==, 100);

	event_base_assert_ok_(base);
	tt_int_op(tfff_p1_freed, ==, 1);
	tt_int_op(tfff_p2_freed, ==, 0);

	event_free(ev2);

end:
	if (base)
		event_base_free(base);
#endif
}
예제 #30
0
static int
proxy_context_init(ProxyContext * const proxy_context, int argc, char *argv[])
{
    memset(proxy_context, 0, sizeof *proxy_context);
    proxy_context->event_loop = NULL;
    proxy_context->log_file = NULL;
    proxy_context->max_log_level = LOG_INFO;
    proxy_context->tcp_accept_timer = NULL;
    proxy_context->tcp_conn_listener = NULL;
    proxy_context->udp_listener_event = NULL;
    proxy_context->udp_proxy_resolver_event = NULL;
    proxy_context->udp_proxy_resolver_handle = -1;
    proxy_context->udp_listener_handle = -1;
    if (options_parse(&app_context, proxy_context, argc, argv) != 0) {
        return -1;
    }
#ifdef _WIN32
    WSADATA wsa_data;
    WSAStartup(MAKEWORD(2, 2), &wsa_data);
#endif
    if ((proxy_context->event_loop = event_base_new()) == NULL) {
        logger(NULL, LOG_ERR, "Unable to initialize the event loop");
        return -1;
    }
    if (sockaddr_from_ip_and_port(&proxy_context->resolver_sockaddr,
                                  &proxy_context->resolver_sockaddr_len,
                                  proxy_context->resolver_ip,
                                  DNS_DEFAULT_RESOLVER_PORT,
                                  "Unsupported resolver address") != 0) {
        return -1;
    }
    if (sockaddr_from_ip_and_port(&proxy_context->local_sockaddr,
                                  &proxy_context->local_sockaddr_len,
                                  proxy_context->local_ip,
                                  DNS_DEFAULT_LOCAL_PORT,
                                  "Unsupported local address") != 0) {
        return -1;
    }
    return 0;
}