Пример #1
0
static int init_ping(pingtun_t *handle, struct ping_struct *ping,
		pingtun_ping_filter_e filter, event_callback_fn write_cb,
		event_callback_fn read_cb) {
	if (0 != pingtun_ping_init(&ping->ping, filter, handle->icmp_id)) {
		ERR("initializing ping socket failed.");
		return -1;
	}

	ping->rcv_ev = event_new(handle->base_ev, pingtun_ping_fd(ping->ping),
			EV_READ, read_cb, handle);
	if (NULL == ping->rcv_ev) {
		ERR("initializing event failed");
		return -1;
	}

	if (0 != event_priority_set(ping->rcv_ev, PINGTUN_PRIO_READ_NORMAL)) {
		ERR("event set priority failed");
		return -1;
	}
	
	ping->snd_ev = event_new(handle->base_ev, pingtun_ping_fd(ping->ping),
			EV_WRITE, write_cb, handle);
	if (NULL == ping->snd_ev) {
		ERR("initializing event failed");
		return -1;
	}
	
	if (0 != event_priority_set(ping->snd_ev, PINGTUN_PRIO_WRITE)) {
		ERR("event set priority failed");
		return -1;
	}

	return 0;
}
Пример #2
0
void workerLoop(struct worker* worker) {

  event_base_priority_init(worker->event_base, 2);

  //Seed event for each fd
  int i;
  for( i = 0; i < worker->nConnections; i++) {

    struct event* ev = event_new(worker->event_base, worker->connections[i]->sock, EV_WRITE|EV_PERSIST, sendCallback, worker);
    event_priority_set(ev, 1);
    event_add(ev, NULL);

    ev = event_new(worker->event_base, worker->connections[i]->sock, EV_READ|EV_PERSIST, receiveCallback, worker);
    event_priority_set(ev, 2);
    event_add(ev, NULL);

  }//End for i

  gettimeofday(&(worker->last_write_time), NULL);
  printf("starting receive base loop\n");
  int error = event_base_loop(worker->event_base, 0);

  if(error == -1) {
    printf("Error starting libevent\n");
  } else if(error == 1) {
    printf("No events registered with libevent\n");
  }

  printf("base loop done\n");

}//End workerLoop()
Пример #3
0
int
bufferevent_priority_set(struct bufferevent *bufev, int priority)
{
	if (event_priority_set(&bufev->ev_read, priority) == -1)
		return (-1);
	if (event_priority_set(&bufev->ev_write, priority) == -1)
		return (-1);

	return (0);
}
Пример #4
0
static void *
libevent_ctx_add(void *ctx, const verto_ev *ev, verto_ev_flag *flags)
{
    struct event *priv = NULL;
    struct timeval *timeout = NULL;
    struct timeval tv;
    int libeventflags = 0;

    if (*flags & VERTO_EV_FLAG_PERSIST)
        libeventflags |= EV_PERSIST;

    switch (verto_get_type(ev)) {
    case VERTO_EV_TYPE_IO:
        if (*flags & VERTO_EV_FLAG_IO_READ)
            libeventflags |= EV_READ;
        if (*flags & VERTO_EV_FLAG_IO_WRITE)
            libeventflags |= EV_WRITE;
        priv = event_new(ctx, verto_get_fd(ev), libeventflags,
                         libevent_callback, (void *) ev);
        break;
    case VERTO_EV_TYPE_TIMEOUT:
        timeout = &tv;
        tv.tv_sec = verto_get_interval(ev) / 1000;
        tv.tv_usec = verto_get_interval(ev) % 1000 * 1000;
        priv = event_new(ctx, -1, EV_TIMEOUT | libeventflags,
                         libevent_callback, (void *) ev);
        break;
    case VERTO_EV_TYPE_SIGNAL:
        priv = event_new(ctx, verto_get_signal(ev),
                         EV_SIGNAL | libeventflags,
                         libevent_callback, (void *) ev);
        break;
    case VERTO_EV_TYPE_IDLE:
    case VERTO_EV_TYPE_CHILD:
    default:
        return NULL; /* Not supported */
    }

    if (!priv)
        return NULL;

    if (*flags & VERTO_EV_FLAG_PRIORITY_HIGH)
        event_priority_set(priv, 0);
    else if (*flags & VERTO_EV_FLAG_PRIORITY_MEDIUM)
        event_priority_set(priv, 1);
    else if (*flags & VERTO_EV_FLAG_PRIORITY_LOW)
        event_priority_set(priv, 2);

    event_add(priv, timeout);
    return priv;
}
Пример #5
0
static int init_tun(pingtun_t *handle) {
	size_t mtu = 0;
	
	if (handle->flags.is_client) {
		mtu = pingtun_ping_capacity(handle->cping.ping);
	} else {
		mtu = pingtun_ping_capacity(handle->sping.ping);
	}

	if (0 != pingtun_tun_init(&handle->tun.tun, &handle->address,
				&handle->netmask, mtu)) {
		ERR("initializing tun device failed.");
		return -1;
	}

	handle->tun.read_ev = event_new(handle->base_ev,
			pingtun_tun_fd(handle->tun.tun), EV_READ, ptcb_tun_read, handle);
	if (NULL == handle->tun.read_ev) {
		ERR("initializing event failed");
		return -1;
	}
	
	if (0 != event_priority_set(handle->tun.read_ev, PINGTUN_PRIO_READ_NORMAL)) {
		ERR("event set priority failed");
		return -1;
	}

	handle->tun.write_ev = event_new(handle->base_ev,
			pingtun_tun_fd(handle->tun.tun), EV_WRITE, ptcb_tun_write, handle);
	if (NULL == handle->tun.write_ev) {
		ERR("initializing event failed");
		return -1;
	}
	
	if (0 != event_priority_set(handle->tun.write_ev, PINGTUN_PRIO_WRITE)) {
		ERR("event set priority failed");
		return -1;
	}

	if (handle->flags.is_client) {
		if (0 != event_add(handle->tun.read_ev, NULL)) {
			ERR("failed adding event");
			return -1;
		}
	}

	return 0;
}
Пример #6
0
int
evsig_init_(struct event_base *base)
{
	/*
	 * Our signal handler is going to write to one end of the socket
	 * pair to wake up our event loop.  The event loop then scans for
	 * signals that got delivered.
	 */
	if (evutil_make_internal_pipe_(base->sig.ev_signal_pair) == -1) {
#ifdef _WIN32
		/* Make this nonfatal on win32, where sometimes people
		   have localhost firewalled. */
		event_sock_warn(-1, "%s: socketpair", __func__);
#else
		event_sock_err(1, -1, "%s: socketpair", __func__);
#endif
		return -1;
	}

	if (base->sig.sh_old) {
		mm_free(base->sig.sh_old);
	}
	base->sig.sh_old = NULL;
	base->sig.sh_old_max = 0;

	event_assign(&base->sig.ev_signal, base, base->sig.ev_signal_pair[0],
		EV_READ | EV_PERSIST, evsig_cb, base);

	base->sig.ev_signal.ev_flags |= EVLIST_INTERNAL;
	event_priority_set(&base->sig.ev_signal, 0);

	base->evsigsel = &evsigops;

	return 0;
}
Пример #7
0
static void
t1func(evutil_socket_t fd, short what, void *arg)
{
    struct event *t1 = (struct event*)arg;
    struct event *t2;

    fprintf(stderr, "CAUGHT EVENT\n");
    fflush(stderr);
    event_del(t1);
    free(t1);
    loops++;
    if (loops < 10) {
        t2 = (struct event*)malloc(sizeof(struct event));
        if (event_assign(t2, base, -1, EV_WRITE, t1func, t2) < 0) {
            die("event_assign_term");
        }
        if (event_priority_set(t2, TERMPRI) < 0) {
            die("event_priority_set_term");
        }
        fprintf(stderr, "EVENT %d DEFINED\n", loops);
        fflush(stderr);
        event_active(t2, EV_WRITE, 1);
        fprintf(stderr, "EVENT %d ACTIVATED\n", loops);
        fflush(stderr);
    }
}
Пример #8
0
int
main(int argc, char **argv)
{
    struct event ev;
    struct event *t1;

    event_enable_debug_mode();

    fprintf(stderr, "Libevent %s\n", event_get_version());
    fflush(stderr);

    if (!(base = event_base_new()))
        die("event_base_new");
    if (event_base_priority_init(base, 8) < 0)
        die("event_base_priority_init");
    if (event_assign(&ev, base, SIGTERM, EV_SIGNAL|EV_PERSIST, cbfunc, NULL)<0)
        die("event_assign");
    if (event_priority_set(&ev, SIGPRI) < 0)
        die("event_priority_set");
    if (event_add(&ev, NULL) < 0)
        die("event_add");
    fprintf(stderr, "SIGNAL EVENT DEFINED\n");
    fflush(stderr);

    t1 = (struct event*)malloc(sizeof(struct event));
    if (event_assign(t1, base, -1, EV_WRITE, t1func, t1) < 0) {
        die("event_assign_term");
    }
    if (event_priority_set(t1, TERMPRI) < 0) {
        die("event_priority_set_term");
    }
    event_active(t1, EV_WRITE, 1);
    fprintf(stderr, "FIRST TERMINATION EVENT DEFINED\n");
    fflush(stderr);

    /*    event_dispatch(base); */

    while (run) {
        event_base_loop(base, EVLOOP_ONCE);
    }

    fprintf(stderr, "EXITED LOOP - FREEING BASE\n");
    fflush(stderr);
    event_base_free(base);
    return 0;
}
Пример #9
0
/* XXXX Should non-socket bufferevents support this? */
int
bufferevent_priority_set(struct bufferevent *bufev, int priority)
{
	int r = -1;

	BEV_LOCK(bufev);
	if (bufev->be_ops != &bufferevent_ops_socket)
		goto done;

	if (event_priority_set(&bufev->ev_read, priority) == -1)
		goto done;
	if (event_priority_set(&bufev->ev_write, priority) == -1)
		goto done;

	r = 0;
done:
	BEV_UNLOCK(bufev);
	return r;
}
Пример #10
0
struct event *wake_set(int fd, void(*fn)(int,short,void*), void *data, int prio)
{
	struct sockaddr_un addr;
	struct han *h = malloc(sizeof(*h));

	if (!h)
		return NULL;

	h->fn = fn;
	h->data = data;
	h->disable = suspend_open();
	h->sock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
	if (h->sock < 0 || h->disable < 0)
		goto abort;
	addr.sun_family = AF_UNIX;
	strcpy(addr.sun_path, "/run/suspend/registration");
	if (connect(h->sock, (struct sockaddr*)&addr, sizeof(addr)) != 0)
		goto abort;

	fcntl(h->sock, F_SETFL, fcntl(h->sock, F_GETFL, 0) | O_NONBLOCK);

	send_fd(h->sock, fd);

	event_set(&h->ev, fd, EV_READ|EV_PERSIST, wakeup_call, h);
	event_set(&h->sev, h->sock, EV_READ|EV_PERSIST, wakeup_sock, h);
	event_priority_set(&h->ev, prio);
	event_priority_set(&h->sev, prio+1);
	event_add(&h->ev, NULL);
	event_add(&h->sev, NULL);

	return &h->ev;

abort:
	suspend_close(h->disable);
	if (h->sock >= 0)
		close(h->sock);
	free(h);
	return NULL;
}
Пример #11
0
/* XXXX Should non-socket bufferevents support this? */
int
bufferevent_priority_set(struct bufferevent *bufev, int priority)
{
	int r = -1;
	struct bufferevent_private *bufev_p =
	    EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);

	BEV_LOCK(bufev);
	if (bufev->be_ops != &bufferevent_ops_socket)
		goto done;

	if (event_priority_set(&bufev->ev_read, priority) == -1)
		goto done;
	if (event_priority_set(&bufev->ev_write, priority) == -1)
		goto done;

	event_deferred_cb_set_priority_(&bufev_p->deferred, priority);

	r = 0;
done:
	BEV_UNLOCK(bufev);
	return r;
}
Пример #12
0
static void
ui_new(evutil_socket_t fd, short what, void *arg)
{
	int newfd;
	struct uiclient *client;

	if ((newfd = accept(fd, NULL, NULL)) == -1) {
		warn("%s: accept");
		return;
	}

	if ((client = calloc(1, sizeof(struct uiclient))) == NULL) {
		warn("%s: calloc", __func__);
		close(newfd);
		return;
	}

	client->fd = newfd;
	client->inbuf = evbuffer_new();
	client->outbuf = evbuffer_new();

	if (client->inbuf == NULL || client->outbuf == NULL)
		err(1, "%s: evbuffer_new");

	syslog(LOG_NOTICE, "%s: New ui connection on fd %d", __func__, newfd);

	client->ev_read = event_new(honeyd_base_ev, newfd, EV_READ, ui_handler, client);
	event_priority_set(client->ev_read, 0);
	event_add(client->ev_read, NULL);

	client->ev_write = event_new(honeyd_base_ev, newfd, EV_WRITE, ui_writer, client);
	event_priority_set(client->ev_write, 0);
	/* event_add(client->ev_write, NULL); -- is this missing? */

	ui_greeting(client);
	ui_write_prompt(client);
}
Пример #13
0
int CWorkThreadEvent::setTimer(unsigned int uiMS)
{
    if (Q_INIT_NUMBER == uiMS)
    {
        return Q_RTN_OK;
    }

    timeval tVal;

    evutil_timerclear(&tVal);
    if (uiMS >= 1000)
    {
        tVal.tv_sec = uiMS / 1000;
        tVal.tv_usec = (uiMS % 1000) * (1000);
    }
    else
    {
        tVal.tv_usec = (uiMS * 1000);
    }

    m_pEvent = event_new(getBase(), 
        -1, EV_PERSIST, workThreadTimerCB, &m_objSessionManager);
    if (NULL == m_pEvent)
    {
        Q_Printf("%s", "event_new error");

        return Q_RTN_FAILE;
    }

    (void)event_priority_set(m_pEvent, Priority_Hight);
    if (Q_RTN_OK != event_add(m_pEvent, &tVal))
    {
        Q_Printf("%s", "event_add error");

        event_free(m_pEvent);
        m_pEvent = NULL;

        return Q_RTN_FAILE;
    }

    m_objSessionManager.setTimer(uiMS);

    return Q_RTN_OK;
}
Пример #14
0
void
ui_init(void)
{
        struct stat st;
        struct sockaddr_un ifsun;
	int ui_socket;

        /* Don't overwrite a file */
        if (lstat(ui_file, &st) == 0) {
                if ((st.st_mode & S_IFMT) == S_IFREG) {
                        errno = EEXIST;
                        err(1, "%s: could not create FIFO: %s",
			    __func__, ui_file);
                }
	}

        /* No need to know about errors.  */
        unlink(ui_file);

        ui_socket = socket(AF_UNIX, SOCK_STREAM, 0);
        if (ui_socket == -1)
                err(1, "%s: socket", __func__);
        if (setsockopt(ui_socket, SOL_SOCKET, SO_REUSEADDR,
                       &ui_socket, sizeof (ui_socket)) == -1)
                err(1, "%s: setsockopt", __func__);

        memset(&ifsun, 0, sizeof (ifsun));
        ifsun.sun_family = AF_UNIX;
        strlcpy(ifsun.sun_path, ui_file, sizeof(ifsun.sun_path));
#ifdef HAVE_SUN_LEN
        ifsun.sun_len = strlen(ifsun.sun_path);
#endif /* HAVE_SUN_LEN */
        if (bind(ui_socket, (struct sockaddr *)&ifsun, sizeof (ifsun)) == -1)
                err(1, "%s: bind", __func__);

        if (listen(ui_socket, 5) == -1)
                err(1, "%s: listen, __func__");

	ev_accept = event_new(honeyd_base_ev, ui_socket, EV_READ|EV_PERSIST, ui_new, NULL);
	event_priority_set(ev_accept, 0);
	event_add(ev_accept, NULL);
}
Пример #15
0
//初始化base->sig成员
int
evsig_init(struct event_base *base)
{
	/*
	 * Our signal handler is going to write to one end of the socket
	 * pair to wake up our event loop.  The event loop then scans for
	 * signals that got delivered. //这感觉就是上一个函数的功能
	 */
	if (evutil_socketpair(
		    AF_UNIX, SOCK_STREAM, 0, base->sig.ev_signal_pair) == -1) {
#ifdef WIN32
		/* Make this nonfatal on win32, where sometimes people
		   have localhost firewalled. */
		event_sock_warn(-1, "%s: socketpair", __func__);
#else
		event_sock_err(1, -1, "%s: socketpair", __func__);
#endif
		return -1;
	}

	evutil_make_socket_closeonexec(base->sig.ev_signal_pair[0]);//两个都设置执行时关闭
	evutil_make_socket_closeonexec(base->sig.ev_signal_pair[1]);
	base->sig.sh_old = NULL; //?
	base->sig.sh_old_max = 0;

	evutil_make_socket_nonblocking(base->sig.ev_signal_pair[0]);//设置为非阻塞
	evutil_make_socket_nonblocking(base->sig.ev_signal_pair[1]);

	event_assign(&base->sig.ev_signal, base, base->sig.ev_signal_pair[1],//注册了上一个函数evsig_cb为回调函数
		EV_READ | EV_PERSIST, evsig_cb, base);

	base->sig.ev_signal.ev_flags |= EVLIST_INTERNAL;//sig为evsig_info类型,ev_signal为event类型。设置为内部,一直没搞懂是啥
	event_priority_set(&base->sig.ev_signal, 0);//初始优先级为0

	base->evsigsel = &evsigops;//设置信号处理的后端

	return 0;
}
Пример #16
0
static int init_echo_timer(pingtun_t *handle) {

	handle->echo_timer.interval.tv_sec = PING_TIMER_INTERVAL_MAX_SEC;
	handle->echo_timer.interval.tv_usec = PING_TIMER_INTERVAL_MAX_USEC;

	handle->echo_timer.ev = event_new(handle->base_ev, -1, EV_PERSIST,
			ptcb_echo_timer, handle);
	if (NULL == handle->echo_timer.ev) {
		ERR("initializing ping timer failed");
		return -1;
	}
	
	if (0 != event_priority_set(handle->echo_timer.ev, PINGTUN_PRIO_WRITE)) {
		ERR("event set priority failed");
		return -1;
	}

	if (0 != event_add(handle->echo_timer.ev, &(handle->echo_timer.interval))) {
		ERR("failed adding event");
		return -1;
	}

	return 0;
}
Пример #17
0
static int luaeventcallback_setpriority(lua_State* L) {
	lua_EventCallback* cb = luaL_checkudata(L, 1, EVENT_CALLBACK_TYPE);
	int priority = luaL_checkint(L, 2);
	event_priority_set(cb->ev, priority);
	return 0;
}
Пример #18
0
int
main(int argc, char *argv[]) {
	int ret = EX_OK;
	primwatch_t primwatch;
	const char *log_type;
	const char *log_facility;
	const char *log_prefix;
	char log_path[MAXPATHLEN];
	const char *pid_file_path;
	const char *cntrl_addr;
	const char *cntrl_port;
	int64_t verbose_level;

	if (logger_create()) {
		fprintf(stderr, "failed in create logger");
		ret = EX_OSERR;
	}
	if (primwatch_initialize(&primwatch)) {
		fprintf(stderr, "failed in initaizliae");
		ret = EX_OSERR;
		goto last;
	}
	parse_args(&primwatch, argc, argv);
	if (logger_set_foreground(primwatch.foreground)) {
		fprintf(stderr, "failed in create logger");
		ret = EX_OSERR;
	}
	if (config_manager_load(primwatch.config_manager, primwatch.config_file)) {
		LOG(LOG_LV_ERR, "failed in load config file %s", primwatch.config_file);
		ret = EX_DATAERR;
		goto last;
	}
	if (config_manager_get_string(primwatch.config_manager, &log_type , "logType", NULL)) {
		LOG(LOG_LV_ERR, "failed in get log type from config");
		ret = EX_DATAERR;
		goto last;
	}
	if (config_manager_get_string(primwatch.config_manager, &log_facility , "logFacility", NULL)) {
		LOG(LOG_LV_ERR, "failed in get log facility from config");
		ret = EX_DATAERR;
		goto last;
	}
	if (config_manager_get_string(primwatch.config_manager, &log_prefix , "logPath", NULL)) {
		LOG(LOG_LV_ERR, "failed in get log path from config");
		ret = EX_DATAERR;
		goto last;
	}
	if (config_manager_get_string(primwatch.config_manager, &pid_file_path , "pidFilePath", NULL)) {
		LOG(LOG_LV_ERR, "failed in get pid file path from config");
		ret = EX_DATAERR;
		goto last;
	}
	if (config_manager_get_string(primwatch.config_manager, &cntrl_addr , "controllerAddress", NULL)) {
		LOG(LOG_LV_ERR, "failed in get controller address from config");
		ret = EX_DATAERR;
		goto last;
	}
	if (config_manager_get_string(primwatch.config_manager, &cntrl_port , "controllerPort", NULL)) {
		LOG(LOG_LV_ERR, "failed in get controller port from config");
		ret = EX_DATAERR;
		goto last;
	}
	if (config_manager_get_long(primwatch.config_manager, &verbose_level , "verboseLevel", NULL)) {
		LOG(LOG_LV_ERR, "failed in get verbose level from config");
		ret = EX_DATAERR;
		goto last;
	}
	snprintf(log_path, sizeof(log_path), "%s.daemon", log_prefix);
	if (logger_open((log_level_t)verbose_level, log_type, PROGIDENT, LOG_PID, log_facility, log_path)) {
		LOG(LOG_LV_ERR, "failed in open log");
		ret = EX_OSERR;
		goto last;
	}
        if (!primwatch.foreground) {
		if (daemon(1,1)) {
			LOG(LOG_LV_ERR, "failed in daemon");
			ret = EX_OSERR;
			goto last;
		}
		setsid();
	}
	if (primwatch_event_initialize(&primwatch)) {
		fprintf(stderr, "failed in initaizliae");
		ret = EX_OSERR;
		goto last;
	}
	if (make_pidfile(pid_file_path)) {
		LOG(LOG_LV_ERR, "failed in create file of process id");
		ret = EX_OSERR;
		goto last;
	}
	if (watcher_polling_start(primwatch.watcher)) {
		LOG(LOG_LV_ERR, "failed in initial polling");
		ret = EX_OSERR;
		goto last;
	}
	if (controller_start(primwatch.controller, cntrl_addr, cntrl_port)) {
		LOG(LOG_LV_ERR, "failed in start controller");
		ret = EX_OSERR;
		goto last;
	}
	signal_set(&primwatch.sig_int_event, SIGINT, primwatch_terminate, &primwatch);
	event_priority_set(&primwatch.sig_int_event, DEFAULT_EVENT_PRIORITY + 30);
	event_base_set(primwatch.event_base, &primwatch.sig_int_event);
	signal_add(&primwatch.sig_int_event, NULL);
	signal_set(&primwatch.sig_term_event, SIGTERM, primwatch_terminate, &primwatch);
	event_priority_set(&primwatch.sig_term_event, DEFAULT_EVENT_PRIORITY + 30);
	event_base_set(primwatch.event_base, &primwatch.sig_term_event);
	signal_add(&primwatch.sig_term_event, NULL);
	signal_set(&primwatch.sig_hup_event, SIGHUP, primwatch_reload, &primwatch);
	event_priority_set(&primwatch.sig_hup_event, DEFAULT_EVENT_PRIORITY + 30);
	event_base_set(primwatch.event_base, &primwatch.sig_hup_event);
	signal_add(&primwatch.sig_hup_event, NULL);
	signal_set(&primwatch.sig_chld_event, SIGCHLD, primwatch_sigchild, &primwatch);
	event_priority_set(&primwatch.sig_chld_event, DEFAULT_EVENT_PRIORITY + 30);
	event_base_set(primwatch.event_base, &primwatch.sig_chld_event);
	signal_add(&primwatch.sig_chld_event, NULL);
	if (event_base_dispatch(primwatch.event_base) == -1) {
		LOG(LOG_LV_ERR, "failed in event base dispatch");
		ret = EX_OSERR;
		goto last;
	}
last:
	unlink(pid_file_path);
	logger_close();
	logger_destroy();
	primwatch_finalize(&primwatch);

	return ret;
}
Пример #19
0
int API
main (int argc, char *argv[], char *envp[])
{
  initalize_syslog ();
  struct state state;
  /* TODO(wad) EVENT_BASE_FLAG_PRECISE_TIMER | EVENT_BASE_FLAG_PRECISE_TIMER */
  struct event_base *base = event_base_new();
  if (!base)
    {
      fatal ("could not allocated new event base");
    }
  /* Add three priority levels:
   * 0 - time saving.  Must be done before any other events are handled.
   * 1 - network synchronization events
   * 2 - any other events (wake, platform, etc)
   */
  event_base_priority_init (base, MAX_EVENT_PRIORITIES);
  memset (&state, 0, sizeof (state));
  set_conf_defaults (&state.opts);
  parse_argv (&state.opts, argc, argv);
  check_conf (&state);
  load_conf (&state.opts);
  check_conf (&state);
  if (!state.opts.sources)
    add_source_to_conf (&state.opts, DEFAULT_HOST, DEFAULT_PORT, DEFAULT_PROXY);
  state.base = base;
  state.envp = envp;
  state.backoff = state.opts.wait_between_tries;
  /* TODO(wad) move this into setup_time_setter */
  /* grab a handle to /dev/rtc for time-setter. */
  if (state.opts.should_sync_hwclock &&
      platform->rtc_open(&state.hwclock))
    {
      pinfo ("can't open hwclock fd");
      state.opts.should_sync_hwclock = 0;
    }
  /* install the SIGCHLD handler for the setter and tlsdate */
  if (setup_sigchld_event (&state, 1))
    {
      error ("Failed to setup SIGCHLD event");
      goto out;
    }
  /* fork off the privileged helper */
  info ("spawning time setting helper . . .");
  if (setup_time_setter (&state))
    {
      error ("could not fork privileged coprocess");
      goto out;
    }
  /* release the hwclock now that the time-setter is running. */
  if (state.opts.should_sync_hwclock)
    {
      platform->rtc_close (&state.hwclock);
    }
  /* drop privileges before touching any untrusted data */
  drop_privs_to (state.opts.user, state.opts.group);
  /* register a signal handler to save time at shutdown */
  if (state.opts.should_save_disk)
    {
      struct event *event = event_new (base, SIGTERM, EV_SIGNAL|EV_PERSIST,
                                       action_sigterm, &state);
      if (!event)
        fatal ("Failed to create SIGTERM event");
      event_priority_set (event, PRI_SAVE);
      event_add (event, NULL);
    }
  if (state.opts.should_dbus && init_dbus (&state))
    {
      error ("Failed to initialize DBus");
      goto out;
    }
  /* Register the tlsdate event before any listeners could show up. */
  state.events[E_TLSDATE] = event_new (base, -1, EV_TIMEOUT,
                                       action_run_tlsdate, &state);
  if (!state.events[E_TLSDATE])
    {
      error ("Failed to create tlsdate event");
      goto out;
    }
  event_priority_set (state.events[E_TLSDATE], PRI_NET);
  /* The timeout and fd will be filled in per-call. */
  if (setup_tlsdate_status (&state))
    {
      error ("Failed to create tlsdate status event");
      goto out;
    }
  /* TODO(wad) Could use a timeout on this to catch setter death? */
  /* EV_READ is for truncation/EPIPE notification */
  state.events[E_SAVE] = event_new (base, state.setter_save_fd,
                                    EV_READ|EV_WRITE, action_sync_and_save,
                                    &state);
  if (!state.events[E_SAVE])
    {
      error ("Failed to create sync & save event");
      goto out;
    }
  event_priority_set (state.events[E_SAVE], PRI_SAVE);
  /* Start by grabbing the system time. */
  state.last_sync_type = SYNC_TYPE_RTC;
  state.last_time = time (NULL);
  /* If possible, grab disk time and check the two. */
  if (state.opts.should_load_disk)
    {
      time_t disk_time = state.last_time;
      if (!load_disk_timestamp (state.timestamp_path, &disk_time))
        {
          info ("disk timestamp available: yes");
          if (!is_sane_time (state.last_time) ||
              state.last_time < disk_time)
            {
              state.last_sync_type = SYNC_TYPE_DISK;
              state.last_time = disk_time;
            }
        }
      else
        {
          info ("disk timestamp available: no");
        }
    }
  if (!is_sane_time (state.last_time))
    {
      state.last_sync_type = SYNC_TYPE_BUILD;
      state.last_time = RECENT_COMPILE_DATE + 1;
    }
  /* Save and announce the initial time source. */
  trigger_event (&state, E_SAVE, -1);
  info ("initial time sync type: %s", sync_type_str (state.last_sync_type));
  /* Initialize platform specific loop behavior */
  if (platform_init_cros (&state))
    {
      error ("Failed to initialize platform code");
      goto out;
    }
  if (setup_event_route_up (&state))
    {
      error ("Failed to setup route up monitoring");
      goto out;
    }
  if (setup_event_timer_sync (&state))
    {
      error ("Failed to setup a timer event");
      goto out;
    }
  if (setup_event_timer_continuity (&state))
    {
      error ("Failed to setup continuity timer");
      goto out;
    }
  /* Add a forced sync event to the event list. */
  action_kickoff_time_sync (-1, EV_TIMEOUT, &state);
  info ("Entering dispatch . . .");
  event_base_dispatch (base);
  info ("tlsdated terminating gracefully");
out:
  return cleanup_main (&state);
}
Пример #20
0
struct timeval *
run_once(void)
{
	int *cp, i, space;
	static struct timeval ta, ts, te, tv;

	gettimeofday(&ta, NULL);

    // Set up event watches:
	for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2)
	{
        if (native) {
#if NATIVE
            //if (ev_is_active (&evio [i]))
            //  ev_io_stop (&evio [i]);

            ev_io_set (&io_blocks[i].io, cp [0], EV_READ);
            ev_io_start (EV_DEFAULT_UC_ &io_blocks[i].io);
            io_blocks[i].timer.repeat = 10. + drand48 ();
            ev_timer_again (EV_DEFAULT_UC_ &io_blocks[i].timer);
#else
            abort ();
#endif
        }
        else
        {
            event_set(&io_blocks[i].event, cp[0], EV_READ | EV_PERSIST, read_cb, &io_blocks[i]);
            if (set_prios) {
                event_priority_set(&io_blocks[i].event, drand48() * EV_MAXPRI);
            }
            if (timers) {
                tv.tv_sec  = 10.;
                tv.tv_usec = drand48() * 1e6;
            }
		    event_add(&io_blocks[i].event, timers ? &tv : 0);
        }
	}

	event_loop(EVLOOP_ONCE | EVLOOP_NONBLOCK);

	// Make the chosen number of descriptors active:
	fired = 0;
	space = num_pipes / num_active;
	space = space * 2;
	for (i = 0; i < num_active; i++, fired++) {
		write(pipes[i * space + 1], "e", 1);
	}

	count = 0;
	writes = num_writes - fired;
	{
	    int xcount = 0;
	    gettimeofday(&ts, NULL);
	    do {
	        event_loop(EVLOOP_ONCE | EVLOOP_NONBLOCK);
	        xcount++;
	    } while (count != num_writes);
	    gettimeofday(&te, NULL);

	    //if (xcount != count) fprintf(stderr, "Xcount: %d, Rcount: %d\n", xcount, count);
	}

	timersub(&te, &ta, &ta);
	timersub(&te, &ts, &ts);

	fprintf(stdout, "%8ld %8ld\n",
			ta.tv_sec * 1000000L + ta.tv_usec,
			ts.tv_sec * 1000000L + ts.tv_usec);

    cp = pipes;
	for (int j = 0; j < num_pipes; j++, cp += 2) {
        if (native) {
#if NATIVE
            ev_io_stop(EV_DEFAULT_UC_ &io_blocks[j].io);
#endif
        }
        else {
            event_del(&io_blocks[j].event);
            event_set(&io_blocks[j].event, cp[0], EV_READ | EV_PERSIST, read_cb, &io_blocks[j]);
        }
    }

	return (&te);
}
Пример #21
0
/*
 * lms_mux_setprio() modifies the priority in the mux of a socket
 *
 * s = socket
 * prio = the priority to set, between 1 and 5
 *
 */
void lms_mux_setprio(MSocket *s, short prio)
{
	event_priority_set(_lms_mux_revents[s->fd], prio);
	event_priority_set(_lms_mux_wevents[s->fd], prio);
}
Пример #22
0
/*
 * lms_mux_addfd() adds a file descriptor to the I/O multiplexer
 *
 * ms = the MSocket with the file descriptor to add to the I/O multiplexer (or (MSocket *)NULL if just fd is specified)
 * fd = the file descriptor to add to the I/O multiplexer (-1 if ms is specified)
 * t = the type (LMSTYPE_*)
 *
 */
int lms_mux_addfd(MSocket *ms, int fd, unsigned short t)
{
	struct event *re;
	struct event *we;
	int prio;

	if (ms)
	{
		fd = ms->fd;
		t = ms->type;
	}
	else if (fd < 0)
	{
		errno = EINVAL;
		return(-1);
	}

	re = (struct event *)malloc(sizeof(struct event));
	if (!re)
	{
		return(-1);
	}
	we = (struct event *)malloc(sizeof(struct event));
	if (!we)
	{
		free(re);
		return(-1);
	}

	if (ms)
	{
		if ((ms->type == LMSTYPE_LISTEN4) || (ms->type == LMSTYPE_LISTEN6))
		{
			prio = 2;
		}
		else if ((ms->type == LMSTYPE_STREAM4) || (ms->type == LMSTYPE_STREAM6))
		{
			prio = 3;
		}
		else if (ms->type == LMSTYPE_LOCALLISTEN)
		{
			prio = 1;
		}
		else if (ms->type == LMSTYPE_LOCALCLIENT)
		{
			prio = 3;
		}
		else
		{
			prio = 4;
		}
	}
	else
	{
		prio = 4;
	}

	event_set(re, fd, EV_READ|EV_PERSIST, _lms_mux_default_read, ms ? (void *)ms : (void *)NULL);
	event_set(we, fd, EV_WRITE|EV_PERSIST, _lms_mux_default_write, ms ? (void *)ms : (void *)NULL);
	event_base_set(lms_mux_evtb, re);
	event_base_set(lms_mux_evtb, we);
	event_priority_set(re, prio);
	event_priority_set(we, prio);
	_lms_mux_revents[fd] = re;
	_lms_mux_wevents[fd] = we;
	event_add(re, (struct timeval *)NULL);
	event_add(we, (struct timeval *)NULL);

	if (ms)
	{
		ms->flags |= LMSFLG_MUXACTIVE;
	}

	return(0);
}
Пример #23
0
int
main(int argc, char **argv)
{
    struct event_base *base;
    struct evconnlistener *listener;
    struct sockaddr_in sin;
    struct stat stat = {.pps = 0, .ts = 0};

    int port = 9876;

    if (argc > 1) {
        port = atoi(argv[1]);
    }
    if (port<=0 || port>65535) {
        puts("Invalid port");
        return 1;
    }

    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, &stat,
        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);
    event_base_priority_init(base, 4);

    struct timeval one_second = {1, 0};
    struct event *stats_ev = event_new(base, -1, EV_TIMEOUT|EV_PERSIST, on_stats, &stat);
    event_add(stats_ev, &one_second);
    event_priority_set(stats_ev, 0);

    struct event *sigterm_ev = evsignal_new(base, SIGTERM, handle_SIGTERM, base);
    evsignal_add(sigterm_ev, NULL);
    event_priority_set(sigterm_ev, 1);

    struct event *sigint_ev = evsignal_new(base, SIGINT, handle_SIGINT, base);
    evsignal_add(sigint_ev, NULL);
    event_priority_set(sigint_ev, 1);

    event_base_dispatch(base);

    event_free(stats_ev);
    event_free(sigterm_ev);
    event_free(sigint_ev);
    evconnlistener_free(listener);
    event_base_free(base);

    return 0;
}