Example #1
0
int main (int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;

    int remote_num = 0;
    char *remote_host[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    opterr = 0;

    while ((c = getopt (argc, argv, "f:s:p:l:k:t:m:i:c:b:uv")) != -1)
    {
        switch (c)
        {
        case 's':
            remote_host[remote_num++] = optarg;
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'u':
            udprelay = 1;
            break;
        case 'v':
            verbose = 1;
            break;
        }
    }

    if (opterr)
    {
        usage();
        exit(EXIT_FAILURE);
    }

    if (conf_path != NULL)
    {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0)
        {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++)
            {
                remote_host[i] = conf->remote_host[i];
            }
        }
        if (remote_port == NULL) remote_port = conf->remote_port;
        if (local_port == NULL) local_port = conf->local_port;
        if (password == NULL) password = conf->password;
        if (method == NULL) method = conf->method;
        if (timeout == NULL) timeout = conf->timeout;
    }

    if (remote_num == 0 || remote_port == NULL ||
            local_port == NULL || password == NULL)
    {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) timeout = "10";

    if (local_addr == NULL) local_addr = "0.0.0.0";

    if (pid_flags)
    {
        demonize(pid_path);
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    // Setup keys
    LOGD("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port);
    if (listenfd < 0)
    {
        FATAL("bind() error..");
    }
    if (listen(listenfd, SOMAXCONN) == -1)
    {
        FATAL("listen() error.");
    }
    setnonblocking(listenfd);
    LOGD("server listening at port %s.", local_port);

    // Setup proxy context
    struct listen_ctx listen_ctx;
    listen_ctx.remote_num = remote_num;
    listen_ctx.remote_host = malloc(sizeof(char *) * remote_num);
    while (remote_num > 0)
    {
        int index = --remote_num;
        listen_ctx.remote_host[index] = remote_host[index];
    }
    listen_ctx.remote_port = remote_port;
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.fd = listenfd;
    listen_ctx.iface = iface;
    listen_ctx.method = m;

    struct ev_loop *loop = ev_default_loop(0);
    if (!loop)
    {
        FATAL("ev_loop error.");
    }
    ev_io_init (&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start (loop, &listen_ctx.io);

    // Setup UDP
    if (udprelay)
    {
        LOGD("udprelay enabled.");
        udprelay_init(local_addr, local_port, remote_host[0], remote_port, m, iface);
    }

    ev_run (loop, 0);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    return 0;
}
Example #2
0
File: main.c Project: osxi/i3bgbar
int main(int argc, char **argv) {
    int opt;
    int option_index = 0;
    char *socket_path = getenv("I3SOCK");
    char *i3_default_sock_path = "/tmp/i3-ipc.sock";

    /* Initialize the standard config to use 0 as default */
    memset(&config, '\0', sizeof(config_t));

    static struct option long_opt[] = {
        { "socket",               required_argument, 0, 's' },
        { "bar_id",               required_argument, 0, 'b' },
        { "help",                 no_argument,       0, 'h' },
        { "version",              no_argument,       0, 'v' },
        { NULL,                   0,                 0, 0}
    };

    while ((opt = getopt_long(argc, argv, "b:s:hv", long_opt, &option_index)) != -1) {
        switch (opt) {
            case 's':
                socket_path = expand_path(optarg);
                break;
            case 'v':
                printf("i3bar version " I3_VERSION " © 2010-2014 Axel Wagner and contributors\n");
                exit(EXIT_SUCCESS);
                break;
            case 'b':
                config.bar_id = sstrdup(optarg);
                break;
            default:
                print_usage(argv[0]);
                exit(EXIT_SUCCESS);
                break;
        }
    }

    if (!config.bar_id) {
        /* TODO: maybe we want -f which will automatically ask i3 for the first
         * configured bar (and error out if there are too many)? */
        ELOG("No bar_id passed. Please let i3 start i3bar or specify --bar_id\n");
        exit(EXIT_FAILURE);
    }

    main_loop = ev_default_loop(0);

    char *atom_sock_path = init_xcb_early();

    if (socket_path == NULL) {
        socket_path = atom_sock_path;
    }

    if (socket_path == NULL) {
        ELOG("No Socket Path Specified, default to %s\n", i3_default_sock_path);
        socket_path = expand_path(i3_default_sock_path);
    }

    init_outputs();
    if (init_connection(socket_path)) {
        /* Request the bar configuration. When it arrives, we fill the config array. */
        i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_BAR_CONFIG, config.bar_id);
    }

    /* We listen to SIGTERM/QUIT/INT and try to exit cleanly, by stopping the main-loop.
     * We only need those watchers on the stack, so putting them on the stack saves us
     * some calls to free() */
    ev_signal *sig_term = smalloc(sizeof(ev_signal));
    ev_signal *sig_int = smalloc(sizeof(ev_signal));
    ev_signal *sig_hup = smalloc(sizeof(ev_signal));

    ev_signal_init(sig_term, &sig_cb, SIGTERM);
    ev_signal_init(sig_int, &sig_cb, SIGINT);
    ev_signal_init(sig_hup, &sig_cb, SIGHUP);

    ev_signal_start(main_loop, sig_term);
    ev_signal_start(main_loop, sig_int);
    ev_signal_start(main_loop, sig_hup);

    /* From here on everything should run smooth for itself, just start listening for
     * events. We stop simply stop the event-loop, when we are finished */
    ev_loop(main_loop, 0);

    kill_child();

    FREE(l_statusline_buffer);
    FREE(r_statusline_buffer);

    clean_xcb();
    ev_default_destroy();

    free_workspaces();

    return 0;
}
Example #3
0
int main(int argc, char **argv) {
    ws_server_t serv;
    ws_quickstart(&serv, "127.0.0.1", 8080, reply);
	ev_loop (ev_default_loop(0), 0);
	return 0;
}
Example #4
0
int main (int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;

    int remote_num = 0;
    ss_addr_t remote_addr[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    int option_index = 0;
    static struct option long_options[] = {
        {"fast-open", no_argument, 0,  0 },
        {0,           0,           0,  0 }
    };

    opterr = 0;

    while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:a:uv",
                            long_options, &option_index)) != -1)
    {
        switch (c)
        {
        case 0:
          if (option_index == 0)
          {
#ifdef TCP_FASTOPEN
              fast_open = 1;
              LOGD("using tcp fast open");
#else
              LOGE("tcp fast open is not supported by this environment");
#endif
          }
          break;
        case 's':
            remote_addr[remote_num].host = optarg;
            remote_addr[remote_num++].port = NULL;
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'a':
            user = optarg;
            break;
        case 'u':
            udprelay = 1;
            break;
        case 'v':
            verbose = 1;
            break;
        }
    }

    if (opterr)
    {
        usage();
        exit(EXIT_FAILURE);
    }

    if (conf_path != NULL)
    {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0)
        {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++)
            {
                remote_addr[i] = conf->remote_addr[i];
            }
        }
        if (remote_port == NULL) remote_port = conf->remote_port;
        if (local_addr == NULL) local_addr = conf->local_addr;
        if (local_port == NULL) local_port = conf->local_port;
        if (password == NULL) password = conf->password;
        if (method == NULL) method = conf->method;
        if (timeout == NULL) timeout = conf->timeout;
        if (fast_open == 0) fast_open = conf->fast_open;
    }

    if (remote_num == 0 || remote_port == NULL ||
            local_port == NULL || password == NULL)
    {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) timeout = "10";

    if (local_addr == NULL) local_addr = "0.0.0.0";

    if (pid_flags)
    {
        USE_SYSLOG(argv[0]);
        demonize(pid_path);
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    // Setup keys
    LOGD("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port);
    if (listenfd < 0)
    {
        FATAL("bind() error..");
    }
    if (listen(listenfd, SOMAXCONN) == -1)
    {
        FATAL("listen() error.");
    }
    setnonblocking(listenfd);
    LOGD("server listening at port %s.", local_port);

    // Setup proxy context
    struct listen_ctx listen_ctx;
    listen_ctx.remote_num = remote_num;
    listen_ctx.remote_addr = malloc(sizeof(ss_addr_t) * remote_num);
    while (remote_num > 0)
    {
        int index = --remote_num;
        if (remote_addr[index].port == NULL) remote_addr[index].port = remote_port;
        listen_ctx.remote_addr[index] = remote_addr[index];
    }
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.fd = listenfd;
    listen_ctx.iface = iface;
    listen_ctx.method = m;

    struct ev_loop *loop = ev_default_loop(0);
    if (!loop)
    {
        FATAL("ev_loop error.");
    }
    ev_io_init (&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start (loop, &listen_ctx.io);

    // Setup UDP
    if (udprelay)
    {
        LOGD("udprelay enabled.");
        udprelay_init(local_addr, local_port, remote_addr[0].host, remote_addr[0].port, m, listen_ctx.timeout, iface);
    }

    // setuid
    if (user != NULL)
        run_as(user);

    ev_run (loop, 0);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    return 0;
}
Example #5
0
int
main (int argc, char **argv)
{
  struct ev_loop *loop;
  struct timeval  tv[2];

  char  dirname[10];
  char *shmdata;
  int   rundir, rundirs[NUM_PROCS], sharedir;
  int   pagesize;
  int   i, j;

  // use the default event loop unless you have special needs
  loop = ev_default_loop (EVBACKEND_EPOLL); //EVFLAG_AUTO);
 
  rundir   = get_rundir();
  pagesize = getpagesize();
  
  // Prepare shared data directory
  if ((mkdirat(rundir, SHARE_DIR_NAME, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) != 0) {
    fprintf(stderr, "could not make share directory: %s\n", strerror(errno));
    return -1;
  }
  if ((sharedir = openat(rundir, SHARE_DIR_NAME, O_DIRECTORY)) < 0) {
    fprintf(stderr, "could not open share directory: %s\n", strerror(errno));
    return -1;
  }

  // Prepare worker rundirs
  for (i=0; i<NUM_PROCS; ++i) {
    sprintf(dirname, "%d", i);
    if ((mkdirat(rundir, dirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) != 0) {
      fprintf(stderr, "worker %d: could not make runtime directory: %s\n", i, strerror(errno));
      return -1;
    }
    if ((rundirs[i] = openat(rundir, dirname, O_DIRECTORY)) < 0) {
      fprintf(stderr, "worker %d: could not open runtime directory: %s\n", i, strerror(errno));
      return -1;
    }

    if ((mkfifoat(rundirs[i], "inputfile", S_IRUSR | S_IWUSR)) != 0) {
      fprintf(stderr, "%s: could not create FIFO: %s\n", "inputfile", strerror(errno));
    }
  }

  // Memory map some data;
  for (j=0; j<NUM_SHMS; ++j) {
    // Maybe just use ids for shared SHM names
    shms[j] = openat(sharedir, "dbfile", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    ftruncate(shms[j], pagesize);
    shmdata = mmap((caddr_t)0, pagesize, PROT_WRITE, MAP_SHARED, shms[j], 0);
    strcpy(shmdata, "Very important DB data.");
    
    // Now "share" it
    for (i=0; i<NUM_PROCS; ++i) {
      linkat(sharedir, "dbfile", rundirs[i], "dbfile", 0);
    }
  }

  //ev_set_timeout_collect_interval (loop, 0.0001);
  //ev_set_io_collect_interval (loop, 0.0001);

  // Start children
  for (i=0; i<NUM_PROCS; ++i) {
    pid_t pid = fork();
    if (pid == 0) {
      // Child
      fchdir(rundirs[i]);
      if (execle(argv[1], gnu_basename(argv[1]), "outputfile", "dbfile", "inputfile", NULL, NULL)) {
	fputs("Could not exec: ", stderr);
	fputs(strerror(errno), stderr);
	fputc('\n', stderr);
	exit(EXIT_FAILURE);
      }
    }
    else if (pid > 0) {
      // Parent
    }
  }

  // Initialize watchers
  for (i=0; i<NUM_PROCS; ++i) {
    ev_io *wio = &input_watcher[i];

    fifos[i] = openat(rundirs[i], "inputfile", O_WRONLY);
    wio->data = (void*)i;
    ev_io_init(wio, input_cb, fifos[i], EV_WRITE);
    ev_io_start(loop, wio);
  }
  
  ev_child *wchld = &child_watcher;
  ev_child_init(wchld, child_cb, 0, 1);
  ev_child_start(loop, wchld);

  // now wait for events to arrive
  gettimeofday(tv+0, NULL);
  ev_loop (loop, 0);
  gettimeofday(tv+1, NULL);
  
  // unloop was called, so exit
  long t = (tv[1].tv_sec - tv[0].tv_sec) * 1000000
           + (tv[1].tv_usec - tv[0].tv_usec);

  printf("\nTime taken: %lfs (%lfms average)\n\n",
      ((double)t) / 1000000.0,
      ((double)t) * NUM_PROCS / NUM_JOBS);

  // Hang up
  /*
  puts("Closing pipes...");
  for (i=0; i<NUM_PROCS; ++i) {
    close(fifos[i]);
  }
  */

  puts("Waiting for children processes to terminate...");
  pid_t pid;
  do {
    pid = wait(NULL);
    if(pid == -1 && errno != ECHILD) {
      perror("Error during wait()");
      abort();
    }
  } while (pid > 0);

  // Cleanup shms
  puts("Cleaning SHMs...");
  for (j=0; j<NUM_SHMS; ++j) {
    ftruncate(shms[j], 0);
    close(shms[i]);
  }

  // Finally...
  puts("Done.");
  return 0;
}
Example #6
0
int main(int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;

    int remote_num = 0;
    ss_addr_t remote_addr[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    opterr = 0;

    while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:c:b:a:")) != -1) {
        switch (c) {
        case 's':
            remote_addr[remote_num].host = optarg;
            remote_addr[remote_num++].port = NULL;
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'a':
            user = optarg;
            break;
        }
    }

    if (opterr) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (conf_path != NULL) {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0) {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++) {
                remote_addr[i] = conf->remote_addr[i];
            }
        }
        if (remote_port == NULL) {
            remote_port = conf->remote_port;
        }
        if (local_addr == NULL) {
            local_addr = conf->local_addr;
        }
        if (local_port == NULL) {
            local_port = conf->local_port;
        }
        if (password == NULL) {
            password = conf->password;
        }
        if (method == NULL) {
            method = conf->method;
        }
        if (timeout == NULL) {
            timeout = conf->timeout;
        }
    }

    if (remote_num == 0 || remote_port == NULL ||
        local_port == NULL || password == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) {
        timeout = "10";
    }

    if (local_addr == NULL) {
        local_addr = "0.0.0.0";
    }

    if (pid_flags) {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);

    // Setup keys
    LOGD("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port);
    if (listenfd < 0) {
        FATAL("bind() error..");
    }
    if (listen(listenfd, SOMAXCONN) == -1) {
        FATAL("listen() error.");
    }
    setnonblocking(listenfd);
    LOGD("server listening at port %s.", local_port);

    // Setup proxy context
    struct listen_ctx listen_ctx;
    listen_ctx.remote_num = remote_num;
    listen_ctx.remote_addr = malloc(sizeof(ss_addr_t) * remote_num);
    while (remote_num > 0) {
        int index = --remote_num;
        if (remote_addr[index].port == NULL) {
            remote_addr[index].port = remote_port;
        }
        listen_ctx.remote_addr[index] = remote_addr[index];
    }
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.fd = listenfd;
    listen_ctx.method = m;

    struct ev_loop *loop = ev_default_loop(0);
    if (!loop) {
        FATAL("ev_loop error.");
    }
    ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start(loop, &listen_ctx.io);

    // setuid
    if (user != NULL) {
        run_as(user);
    }

    ev_run(loop, 0);

    return 0;
}
Example #7
0
void crawl(arguments *arg) {
    // Add Ctrl+c handling
    done = 0;
    signal(SIGINT, finish);

    global_info global;
    memset(&global, 0, sizeof(global_info));
    char search_name[SEARCH_NAME_LEN];
    memset(search_name, '\0', SEARCH_NAME_LEN * sizeof(char));

    /* Init before looping starts */
    global.out_name = arg->out_file;
    if (0 == (global.out = fopen(global.out_name, "w+"))) {
        orcerror("%s (%d) %s\n", strerror(errno), errno, global.out_name);
        exit(EXIT_FAILURE);
    }

    global.job_max = arg->max_events;
    global.loop = ev_default_loop(0);
    global.multi = curl_multi_init();
    ev_timer_init(&(global.timer_event), socket_action_timer_cb, 0., 0.);
    global.timer_event.data = &global;
    curl_multi_setopt(global.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
    curl_multi_setopt(global.multi, CURLMOPT_TIMERDATA, &global);
    curl_multi_setopt(global.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
    curl_multi_setopt(global.multi, CURLMOPT_SOCKETDATA, &global);
    bintree_init(&(global.url_tree), bintree_streq, free_tree);

    global.input.search_name = search_name;
    global.input.search_name_len = SEARCH_NAME_LEN;
    global.input.excludes = arg->excludes;
    global.input.excludes_len = arg->excludes_len;

    if (!find_search_name(arg->url, search_name , SEARCH_NAME_LEN))
    {
        orcerror("not a valid domain name or ip in: %s\n", arg->url);
        exit(EXIT_FAILURE);
    }
    orcoutc(orc_reset, orc_blue, "Target %s\n", global.input.search_name);

    add_first_call(arg, &global);

    struct timeval start;
    struct timeval stop;

    /* Lets find some urls */
    gettimeofday(&start, 0);
    ev_loop(global.loop, 0);
    gettimeofday(&stop, 0);

    print_stats(&global, &start, &stop);

    /* Cleanups after looping */
    fclose(global.out);
    free_array_of_charptr_incl(&(global.input.ret), global.input.ret_len);
    bintree_free(&(global.url_tree));
    curl_multi_cleanup(global.multi);

    char *url_item = 0;
    int i = 0;
    while (0 != (url_item = url_get(&global))) {
        free(url_item);
        i++;
    }
    orcout(orcm_debug, "Freed %d url items.\n", i);
}
int main(int argc, char *argv[])
{
    char *ctrlchnlname = NULL;
    vnode_client_cmdiotype_t iotype = VCMD_IO_FD;
    ev_timer cmdreq;
    extern const char *__progname;
#ifdef FORWARD_SIGNALS
    int i;
    struct sigaction sig_action = {
        .sa_handler = sighandler,
    };
#endif	/* FORWARD_SIGNALS */
    char *def_argv[2] = { VCMD_DEFAULT_CMD, 0 };

    if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO) &&
            isatty(STDERR_FILENO) && getpgrp() == tcgetpgrp(STDOUT_FILENO))
        iotype = VCMD_IO_PTY;

    /* Parse command line argument list */
    for (;;)
    {
        int opt;

        if ((opt = getopt_long(argc, argv, "c:hiIqvV", longopts, NULL)) == -1)
            break;

        switch (opt)
        {
        case 'c':
            ctrlchnlname = optarg;
            break;

        case 'i':
            iotype = VCMD_IO_PTY;
            break;

        case 'I':
            iotype = VCMD_IO_FD;
            break;

        case 'q':
            iotype = VCMD_IO_NONE;
            break;

        case 'v':
            verbose++;
            break;

        case 'V':
            printf("%s version %s\n", __progname, CORE_VERSION);
            exit(0);

        case 'h':
        /* pass through */
        default:
            usage(0, NULL);
        }
    }

    argc -= optind;
    argv += optind;

    if (ctrlchnlname == NULL)
        usage(1, "no control channel name given");

    if (!argc)
    {
        argc = 1;
        argv = def_argv;
    }

    if (argc >= VNODE_ARGMAX)
        usage(1, "too many command arguments");

    if (atexit(cleanup))
        ERR(1, "atexit() failed");

#ifdef FORWARD_SIGNALS
    for (i = 1; i < _NSIG; i++)
        if (sigaction(i, &sig_action, NULL))
            if (verbose && i != SIGKILL && i != SIGSTOP)
                WARN("sigaction() failed for %d", i);
#endif	/* FORWARD_SIGNALS */

    vcmd.cmdio = vnode_open_clientcmdio(iotype);
    if (!vcmd.cmdio)
        ERR(1, "vnode_open_clientcmdio() failed");

    vcmd.argc = argc;
    vcmd.argv = argv;
    vcmd.cmdstatus = 255;

    switch (vcmd.cmdio->iotype)
    {
    case VCMD_IO_NONE:
        break;

    case VCMD_IO_FD:
        SET_STDIOFD(vcmd.cmdio, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO);
        break;

    case VCMD_IO_PTY:
    {
        struct sigaction sigwinch_action = {
            .sa_handler = sigwinch_handler,
        };

        if (sigaction(SIGWINCH, &sigwinch_action, NULL))
            WARN("sigaction() failed for SIGWINCH");

        sigwinch_handler(SIGWINCH);

        if (termioraw(STDOUT_FILENO, &saveattr))
            WARNX("termioraw() failed");
        else
            saveattr_set = 1;
    }
    break;

    default:
        ERR(1, "unsupported i/o type: %u", vcmd.cmdio->iotype);
        break;
    }

    vcmd.client = vnode_client(ev_default_loop(0), ctrlchnlname,
                               vcmd_ioerrorcb, &vcmd);
    if (!vcmd.client)
        ERR(1, "vnode_client() failed");

    cmdreq.data = &vcmd;
    ev_timer_init(&cmdreq, vcmd_cmdreqcb, 0, 0);
    ev_timer_start(vcmd.client->loop, &cmdreq);

    ev_loop(vcmd.client->loop, 0);

    vnode_delclient(vcmd.client);

    exit(vcmd.cmdstatus);
}
Example #9
0
int main(int argc, char *argv[]) {
    static struct option long_options[] = {
        {"getmonitors_reply", required_argument, 0, 0},
        {0, 0, 0, 0},
    };
    char *options_string = "";
    int opt;
    int option_index = 0;

    while ((opt = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
        switch (opt) {
            case 0:
                if (strcmp(long_options[option_index].name, "getmonitors_reply") == 0) {
                    must_read_reply(optarg);
                }
                break;
            default:
                exit(EXIT_FAILURE);
        }
    }

    if (optind >= argc) {
        errx(EXIT_FAILURE, "syntax: %s [options] <command>\n", argv[0]);
    }

    int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (fd == -1) {
        err(EXIT_FAILURE, "socket(AF_UNIX)");
    }

    if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
        warn("Could not set FD_CLOEXEC");
    }

    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(struct sockaddr_un));
    addr.sun_family = AF_UNIX;
    int i;
    bool bound = false;
    for (i = 0; i < 100; i++) {
        /* XXX: The path to X11 sockets differs on some platforms (e.g. Trusted
         * Solaris, HPUX), but since libxcb doesn’t provide a function to
         * generate the path, we’ll just have to hard-code it for now. */
        snprintf(addr.sun_path, sizeof(addr.sun_path), "/tmp/.X11-unix/X%d", i);

        if (bind(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) {
            warn("bind(%s)", addr.sun_path);
        } else {
            bound = true;
            /* Let the user know bind() was successful, so that they know the
             * error messages can be disregarded. */
            fprintf(stderr, "Successfuly bound to %s\n", addr.sun_path);
            sun_path = sstrdup(addr.sun_path);
            break;
        }
    }

    if (!bound) {
        err(EXIT_FAILURE, "bind()");
    }

    atexit(cleanup_socket);

    /* This program will be started for each testcase which requires it, so we
     * expect precisely one connection. */
    if (listen(fd, 1) == -1) {
        err(EXIT_FAILURE, "listen()");
    }

    pid_t child = fork();
    if (child == -1) {
        err(EXIT_FAILURE, "fork()");
    }
    if (child == 0) {
        char *display;
        sasprintf(&display, ":%d", i);
        setenv("DISPLAY", display, 1);
        free(display);

        char **child_args = argv + optind;
        execvp(child_args[0], child_args);
        err(EXIT_FAILURE, "exec()");
    }

    struct ev_loop *loop = ev_default_loop(0);

    ev_child cw;
    ev_child_init(&cw, child_cb, child, 0);
    ev_child_start(loop, &cw);

    ev_io watcher;
    ev_io_init(&watcher, uds_connection_cb, fd, EV_READ);
    ev_io_start(loop, &watcher);

    ev_run(loop, 0);
}
Example #10
0
int main() {
	#if defined _WIN32
	WORD w_version_requested;
	WSADATA wsa_data;
	int err;
	w_version_requested = MAKEWORD(2, 2);

	err = WSAStartup(w_version_requested, &wsa_data);
	if (err != 0) {
		printf("WSAStartup failed with error: %d\n", err);
		return 1;
	}
	#endif

	EV_A = ev_default_loop(0);
	if (EV_A == NULL) {
		printf("ev_default_loop failed!\n");
		goto error;
	}
	
	struct addrinfo hints;
	struct addrinfo *res;
	char bol_reuseaddr = 1;

	// Get address info
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;
	int int_status = getaddrinfo(NULL, "8080", &hints, &res);
	if (int_status != 0) {
		wprintf(L"getaddrinfo failed: %d (%s)\n", int_status, gai_strerror(int_status));
		goto error;
	}

	// Get socket to bind
	int_sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
	if (int_sock == INVALID_SOCKET) {
		printf("Failed to create socket: %s (%d)\n", strerror(errno), errno);
		goto error;
	}

	if (setsockopt(int_sock, SOL_SOCKET, SO_REUSEADDR, &bol_reuseaddr, sizeof(int)) == -1) {
		printf("setsockopt failed: %s (%d)\n", strerror(errno), errno);
		goto error;
	}

	if (bind(int_sock, res->ai_addr, res->ai_addrlen) == -1) {
		printf("bind failed: %s (%d)\n", strerror(errno), errno);
		goto error;
	}

	freeaddrinfo(res);

	if (listen(int_sock, 10) == -1) {
		printf("listen failed: %s (%d)\n", strerror(errno), errno);
		goto error;
	}
	
	int int_ret;
	if ((int_ret = setnonblock(int_sock)) != 0) {
		printf("setnonblock failed: %d\n", int_ret);
		goto error;
	}

	#if defined _WIN32
	int fd = _open_osfhandle(int_sock, 0);
	ev_io_init(&server_io, server_cb, fd, EV_READ);
	#else
	ev_io_init(&server_io, server_cb, int_sock, EV_READ);
	#endif
	ev_io_start(EV_A, &server_io);

	ev_run(EV_A, 0);

	#if defined _WIN32
	_close(fd);
	#else
	close(int_sock);
	#endif

	#if defined _WIN32
	WSACleanup();
	#endif
	return 0;
error:
	#if defined _WIN32
	WSACleanup();
	#endif
	return 1;
}
Example #11
0
int main(int argc, char** argv) {
    dmn_init_log("gdnsd_extmon_helper", true);

    // start up syslog IFF it appears the daemon
    //   was *not* started via "startfg".  Regular
    //   start/restart would have /dev/null'd the
    //   standard descriptors before forking us off.
    if(!isatty(0))
        dmn_start_syslog();

    // Bail out early if we don't have the right argument
    //   count, and try to tell the user not to run us
    //   if stderr happens to be hooked up to a terminal
    if(argc != 5) {
        fprintf(stderr, "This binary is not for human execution!\n");
        abort();
    }

    // open stderr logging connection using passed fd
    dmn_log_set_alt_stderr(atoi(argv[2]));

    // regardless, we seal off stdin now.  We don't need it,
    //   and this way we don't have to deal with it when
    //   execv()-ing child commands later.
    if(!freopen("/dev/null", "r", stdin))
        dmn_log_fatal("Cannot open /dev/null: %s", dmn_strerror(errno));

    if(!strcmp(argv[1], "Y"))
        dmn_set_debug(true);
    else if(!strcmp(argv[1], "N"))
        dmn_set_debug(false);
    else
        log_fatal("Invalid debug argument on cmdline: '%s'!", argv[1]);

    // these are the main communication pipes to the daemon/plugin
    plugin_read_fd = atoi(argv[3]);
    plugin_write_fd = atoi(argv[4]);

    if(plugin_read_fd < 3 || plugin_read_fd > 1000
        || plugin_write_fd < 3 || plugin_write_fd > 1000)
        log_fatal("Invalid pipe descriptors!");

    // CLOEXEC the direct lines to the main plugin/daemon,
    //   so that child scripts can't screw with them.
    if(fcntl(plugin_read_fd, F_SETFD, FD_CLOEXEC))
        log_fatal("Failed to set FD_CLOEXEC on plugin read fd: %s", dmn_strerror(errno));
    if(fcntl(plugin_write_fd, F_SETFD, FD_CLOEXEC))
        log_fatal("Failed to set FD_CLOEXEC on plugin write fd: %s", dmn_strerror(errno));

    if(emc_read_exact(plugin_read_fd, "HELO"))
        log_fatal("Failed to read HELO from plugin");
    if(emc_write_string(plugin_write_fd, "HELO_ACK", 8))
        log_fatal("Failed to write HELO_ACK to plugin");

    uint8_t ccount_buf[7];
    if(emc_read_nbytes(plugin_read_fd, 7, ccount_buf)
        || strncmp((char*)ccount_buf, "CMDS:", 5))
        log_fatal("Failed to read command count from plugin");
    num_mons = ((unsigned)ccount_buf[5] << 8) + ccount_buf[6];
    if(!num_mons)
        log_fatal("Received command count of zero from plugin");
    mons = calloc(num_mons, sizeof(mon_t));

    if(emc_write_string(plugin_write_fd, "CMDS_ACK", 8))
        log_fatal("Failed to write CMDS_ACK to plugin");

    // Note, it's merely a happy coincidence that our mons[]
    //   indices exactly match cmd->idx numbers.  Always use
    //   the cmd->idx numbers as the official index when talking
    //   to the main daemon!
    for(unsigned i = 0; i < num_mons; i++) {
        mons[i].cmd = emc_read_command(plugin_read_fd);
        if(!mons[i].cmd)
            log_fatal("Failed to read command %u from plugin", i);
        if(i != mons[i].cmd->idx)
            log_fatal("BUG: plugin index issues, %u vs %u", i, mons[i].cmd->idx);
        if(emc_write_string(plugin_write_fd, "CMD_ACK", 7))
            log_fatal("Failed to write CMD_ACK for command %u to plugin", i);
    }

    if(emc_read_exact(plugin_read_fd, "END_CMDS"))
        log_fatal("Failed to read END_CMDS from plugin");
    if(emc_write_string(plugin_write_fd, "END_CMDS_ACK", 12))
        log_fatal("Failed to write END_CMDS_ACK to plugin");

    // done with the serial setup, close the readpipe and go nonblocking on write for eventloop...
    close(plugin_read_fd);
    if(unlikely(fcntl(plugin_write_fd, F_SETFL, (fcntl(plugin_write_fd, F_GETFL, 0)) | O_NONBLOCK) == -1))
        log_fatal("Failed to set O_NONBLOCK on pipe: %s", logf_errno());

    // init results-sending queue
    sendq_init();

    // Set up libev error callback
    ev_set_syserr_cb(&syserr_for_ev);

    // Construct the default loop for the main thread
    struct ev_loop* def_loop = ev_default_loop(EVFLAG_AUTO);
    if(!def_loop) log_fatal("Could not initialize the default libev loop");
    ev_set_timeout_collect_interval(def_loop, 0.1);
    ev_set_io_collect_interval(def_loop, 0.01);

    // set up primary read/write watchers on the pipe to the daemon's plugin
    plugin_read_watcher = malloc(sizeof(ev_io));
    plugin_write_watcher = malloc(sizeof(ev_io));
    ev_io_init(plugin_write_watcher, plugin_write_cb, plugin_write_fd, EV_WRITE);
    ev_set_priority(plugin_write_watcher, 1);

    // set up interval watchers for each monitor, initially for immediate firing
    //   for the daemon's monitoring init cycle, then repeating every interval.
    for(unsigned i = 0; i < num_mons; i++) {
        mon_t* this_mon = &mons[i];
        this_mon->interval_timer = malloc(sizeof(ev_timer));
        ev_timer_init(this_mon->interval_timer, mon_interval_cb, 0., this_mon->cmd->interval);
        this_mon->interval_timer->data = this_mon;
        ev_set_priority(this_mon->interval_timer, 0);
        ev_timer_start(def_loop, this_mon->interval_timer);

        // initialize the other watchers in the mon_t here as well,
        //   but do not start them (the interval callback starts them each interval)
        this_mon->cmd_timeout = malloc(sizeof(ev_timer));
        ev_timer_init(this_mon->cmd_timeout, mon_timeout_cb, 0, 0);
        ev_set_priority(this_mon->cmd_timeout, -1);
        this_mon->cmd_timeout->data = this_mon;

        this_mon->child_watcher = malloc(sizeof(ev_child));
        ev_child_init(this_mon->child_watcher, mon_child_cb, 0, 0);
        this_mon->child_watcher->data = this_mon;
    }

    log_info("gdnsd_extmon_helper running");

    // shut off stderr output from here out...
    dmn_log_close_alt_stderr();

    ev_run(def_loop, 0);
    log_info("gdnsd_extmon_helper terminating");

    // kill -9 on any extant child procs
    for(unsigned i = 0; i < num_mons; i++)
        if(mons[i].cmd_pid)
            kill(mons[i].cmd_pid, SIGKILL);

    // Bye!
    exit(0);
}
Example #12
0
int main(int argc, char **argv) {
	GOptionContext *context;
	GError *error = NULL;
	gint res;

	context = g_option_context_new("<application> [app arguments]");
	g_option_context_add_main_entries(context, entries, NULL);
	g_option_context_set_summary(context, PACKAGE_DESC);

	if (!g_option_context_parse (context, &argc, &argv, &error)) {
		g_printerr("Option parsing failed: %s\n", error->message);
		return -1;
	}

	if (opts.show_version) {
		g_printerr(PACKAGE_DESC);
		g_printerr("\nBuild-Date: " __DATE__ " " __TIME__ "\n");
		return 0;
	}

	if (!opts.app || !opts.app[0]) {
		g_printerr("Missing application\n");
		return -2;
	}

	if (opts.forks < 1) {
		g_printerr("Invalid forks argument: %i\n", opts.forks);
		return -3;
	}

	if (opts.retry < 1) {
		g_printerr("Invalid retry argument: %i\n", opts.retry);
		return -4;
	}

	if (opts.retry_timeout_ms < 0) {
		g_printerr("Invalid timeout argument: %i\n", opts.retry_timeout_ms);
		return -5;
	}

	data *d = g_slice_new0(data);
	d->children = (child*) g_slice_alloc0(sizeof(child) * opts.forks);
	d->running = 0;
	d->shutdown = FALSE;
	d->return_status = 0;
	d->loop = ev_default_loop(0);

#define WATCH_SIG(x) do { ev_signal_init(&d->sig##x, forward_sig_cb, SIG##x); d->sig##x.data = d; ev_signal_start(d->loop, &d->sig##x); ev_unref(d->loop); } while (0)
#define WATCH_TERM_SIG(x) do { ev_signal_init(&d->sig##x, terminate_forward_sig_cb, SIG##x); d->sig##x.data = d; ev_signal_start(d->loop, &d->sig##x); ev_unref(d->loop); } while (0)
#define UNWATCH_SIG(x) do { ev_ref(d->loop); ev_signal_stop(d->loop, &d->sig##x); } while (0)

	WATCH_TERM_SIG(HUP);
	WATCH_TERM_SIG(INT);
	WATCH_TERM_SIG(QUIT);
	WATCH_TERM_SIG(TERM);
	WATCH_TERM_SIG(USR1);
	WATCH_SIG(USR2);

	for (gint i = 0; i < opts.forks; i++) {
		d->children[i].d = d;
		d->children[i].id = i;
		d->children[i].pid = -1;
		d->children[i].tries = 0;
		d->children[i].watcher.data = &d->children[i];
		ev_child_init(&d->children[i].watcher, child_died, -1, 0);

		spawn(&d->children[i]);
	}

	ev_loop(d->loop, 0);

	res = d->return_status;

	g_slice_free1(sizeof(child) * opts.forks, d->children);
	g_slice_free(data, d);

	UNWATCH_SIG(HUP);
	UNWATCH_SIG(INT);
	UNWATCH_SIG(QUIT);
	UNWATCH_SIG(TERM);
	UNWATCH_SIG(USR1);
	UNWATCH_SIG(USR2);

	return res;
}
Example #13
0
verto_ctx *
verto_default_libev(void)
{
    return verto_convert_libev(ev_default_loop(EVFLAG_AUTO));
}
Example #14
0
int main(int argc, char **argv)
{
    ev_stat cfg;
    if (argc == 1) {
        printf("no cfg\n");
        return 0;
    }
    if (argc == 2) {
        daemon(0, 0);
    }
    cfg_path = strdup(argv[1]);
    cfg_init(cfg_path);
    ev_stat_init (&cfg, cfg_cb, cfg_path, 2.);
    signal(SIGPIPE, SIG_IGN);
    struct ev_loop *loop = ev_default_loop (0);
    work_loop = ev_loop_new(0);
    int listen_fd;
    struct sockaddr_in listen_addr; 
    int reuseaddr_on = 1;
   
    pthread_mutex_init(&lock, NULL);
    thread_create(work, NULL);
    listen_fd = socket(AF_INET, SOCK_STREAM, 0); 
    if (listen_fd < 0) {
        perror("listen failed");
        return -1;
    }
    if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_on,
            sizeof(reuseaddr_on)) == -1)
    {
        perror("setsockopt failed");
        return -1;
    }
    memset(&listen_addr, 0, sizeof(listen_addr));
    listen_addr.sin_family = AF_INET;
    listen_addr.sin_addr.s_addr = INADDR_ANY;
    listen_addr.sin_port = htons(SERVER_PORT);
    if (bind(listen_fd, (struct sockaddr *)&listen_addr,
            sizeof(listen_addr)) < 0)
    {
        perror("bind failed");
        return -1;
    }
    if (listen(listen_fd, 128) < 0)
    {
        perror("listen failed");
        return -1;
    }
    if (setnonblock(listen_fd) < 0)
    {
        perror("failed to set server socket to non-blocking");
        return -1;
    }
	 
    ev_io ev_accept;
    ev_io_init(&ev_accept, accept_cb, listen_fd, EV_READ);
    ev_io_start(loop, &ev_accept);
    if (cfg_path != NULL)
        ev_stat_start (loop, &cfg);
    ev_loop (loop, 0);
    return 0;
}
Example #15
0
int main(int argc, char *argv[])
{
	int c;
	const char *config_file = DEFAULT_CONFIG;
	const char *adm_socket = DEFAULT_ADM_SOCKET;
	int verbose = 0;
	static struct ev_loop *loop;
	static struct ev_signal signal_watcher;
	pid_t pid;

	while ((c = getopt(argc, argv, "a:c:dhp:Vv")) != -1) {
		switch (c) {
		case 'a':
			adm_socket = optarg;
			break;
		case 'c':
			config_file = optarg;
			break;
		case 'd':
			pingu_daemonize++;
			break;
		case 'h':
			return usage(basename(argv[0]));
		case 'p':
			pid_file = optarg;
			break;
		case 'V':
			print_version(basename(argv[0]));
			return 0;
		case 'v':
			verbose++;
			break;
		}
	}

	argc -= optind;
	argv += optind;

	log_init("pingu", verbose);

	pid = get_running_pid();
	if (pid)
		errx(1, "appears to be running already (pid %i)", pid);

	loop = ev_default_loop(0);

	if (pingu_conf_parse(config_file) < 0)
		return 1;

	if (pingu_iface_init(loop) < 0)
		return 1;

	if (pingu_host_init(loop) < 0)
		return 1;

	if (pingu_adm_init(loop, adm_socket) < 0)
		return 1;

	if (pingu_daemonize) {
		if (daemonize() == -1)
			return 1;
	}

	kernel_init(loop);
	ev_signal_init(&signal_watcher, sigint_cb, SIGINT);
	ev_signal_start(loop, &signal_watcher);

	ev_run(loop, 0);
	log_info("Shutting down");
	pingu_iface_cleanup(loop);
	pingu_host_cleanup();
	kernel_close();
	ev_loop_destroy(loop);
	return 0;
}
Example #16
0
File: lem.c Project: halfd/lem
int
main(int argc, char *argv[])
{
#if EV_MULTIPLICITY
	lem_loop = ev_default_loop(LEM_LOOPFLAGS);
	if (lem_loop == NULL) {
#else
	if (!ev_default_loop(LEM_LOOPFLAGS)) {
#endif
		lem_log_error("lem: error initializing event loop");
		return EXIT_FAILURE;
	}

	if (setsignal(SIGPIPE, SIG_IGN, 0)
#if !EV_CHILD_ENABLE
	    || setsignal(SIGCHLD, SIG_DFL, SA_NOCLDSTOP | SA_NOCLDWAIT)
#endif
	   )
		goto error;

	/* create main Lua state */
	L = luaL_newstate();
	if (L == NULL) {
		lem_log_error("lem: error initializing Lua state");
		goto error;
	}
	luaL_openlibs(L);

	/* push thread table */
	lua_newtable(L);

	/* initialize runqueue */
	ev_idle_init(&rq.w, runqueue_pop);
	ev_idle_start(LEM_ &rq.w);
	rq.queue = lem_xmalloc(LEM_INITIAL_QUEUESIZE
			* sizeof(struct lem_runqueue_slot));
	rq.first = rq.last = 0;
	rq.mask = LEM_INITIAL_QUEUESIZE - 1;

	/* initialize threadpool */
	if (pool_init()) {
		lem_log_error("lem: error initializing threadpool");
		goto error;
	}

	/* load file */
	if (queue_file(argc, argv, 1))
		goto error;

	/* start the mainloop */
	ev_loop(LEM_ 0);
	lem_debug("event loop exited");

	/* if there is an error message left on L print it */
	if (lua_type(L, -1) == LUA_TSTRING)
		lem_log_error("lem: %s", lua_tostring(L, -1));

	/* shutdown Lua */
	lua_close(L);

	/* free runqueue */
	free(rq.queue);

	/* destroy loop */
#if EV_MULTIPLICITY
	ev_loop_destroy(lem_loop);
#else
	ev_default_destroy();
#endif
	lem_debug("Bye %s", exit_status == EXIT_SUCCESS ? "o/" : ":(");
	return exit_status;

error:
	if (L)
		lua_close(L);
	if (rq.queue)
		free(rq.queue);
#if EV_MULTIPLICITY
	ev_loop_destroy(lem_loop);
#else
	ev_default_destroy();
#endif
	return EXIT_FAILURE;
}
/**
 * Initializes the networking interfaces
 * @arg config Takes the statsite_proxy server configuration
 * @arg netconf Output. The configuration for the networking stack.
 * @arg proxy Pointer to proxy for routing metrics via consistent hashing
 */
int init_networking(statsite_proxy_config *config, statsite_proxy_networking **netconf_out, proxy *proxy) {
    // Make the netconf structure
    statsite_proxy_networking *netconf = calloc(1, sizeof(struct statsite_proxy_networking));

    // Initialize
    netconf->events = NULL;
    netconf->config = config;
    netconf->proxy = proxy;
    netconf->should_run = 1;
    netconf->thread = NULL;

    /**
     * Check if we can use kqueue instead of select.
     * By default, libev will not use kqueue since it only
     * works for sockets, which is all we need.
     */
    int ev_mode = EVFLAG_AUTO;
    if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE) {
        ev_mode = EVBACKEND_KQUEUE;
    }

    if (!ev_default_loop (ev_mode)) {
        syslog(LOG_CRIT, "Failed to initialize libev!");
        free(netconf);
        return 1;
    }

    // Setup proxy connections
    int proxy_res = setup_proxy_connections(netconf);
    if (proxy_res != 0) {
    	// free proxy connections stuff
    	free(netconf);
    	return 1;
    }

    // Setup the TCP listener
    int res = setup_tcp_listener(netconf);
    if (res != 0) {
        free(netconf);
        return 1;
    }

    // Setup the UDP listener
    res = setup_udp_listener(netconf);
    if (res != 0) {
        ev_io_stop(&netconf->tcp_client);
        close(netconf->tcp_client.fd);
        free(netconf);
        return 1;
    }

    // Setup the async handler
    ev_async_init(&netconf->loop_async, handle_async_event);
    ev_async_start(&netconf->loop_async);

    // Prepare the conn handlers
    init_conn_handler(config);

    // Success!
    *netconf_out = netconf;
    return 0;
}
Example #18
0
File: ev.cpp Project: AmkG/snap
	void poll(CentralIOToDo todo) {
		getall(todo);
		ev_loop(ev_default_loop(0), EVLOOP_NONBLOCK);
	}
Example #19
0
int evapi_run_dispatcher(char *laddr, int lport)
{
	int evapi_srv_sock;
	struct sockaddr_in evapi_srv_addr;
	struct ev_loop *loop;
	struct hostent *h = NULL;
	struct ev_io io_server;
	struct ev_io io_notify;

	LM_DBG("starting dispatcher processing\n");

	memset(_evapi_clients, 0, sizeof(evapi_client_t) * EVAPI_MAX_CLIENTS);

	loop = ev_default_loop(0);

	if(loop==NULL) {
		LM_ERR("cannot get libev loop\n");
		return -1;
	}

    h = gethostbyname(laddr);
    if (h == NULL || (h->h_addrtype != AF_INET && h->h_addrtype != AF_INET6)) {
    	LM_ERR("cannot resolve local server address [%s]\n", laddr);
        return -1;
    }
    if(h->h_addrtype == AF_INET) {
    	evapi_srv_sock = socket(PF_INET, SOCK_STREAM, 0);
	} else {
		evapi_srv_sock = socket(PF_INET6, SOCK_STREAM, 0);
	}
	if( evapi_srv_sock < 0 )
	{
		LM_ERR("cannot create server socket (family %d)\n", h->h_addrtype);
		return -1;
	}
	/* set non-blocking flag */
	fcntl(evapi_srv_sock, F_SETFL, fcntl(evapi_srv_sock, F_GETFL) | O_NONBLOCK);

	bzero(&evapi_srv_addr, sizeof(evapi_srv_addr));
	evapi_srv_addr.sin_family = h->h_addrtype;
	evapi_srv_addr.sin_port   = htons((short)lport);
	evapi_srv_addr.sin_addr  = *(struct in_addr*)h->h_addr;

	if (bind(evapi_srv_sock, (struct sockaddr*)&evapi_srv_addr,
				sizeof(evapi_srv_addr)) < 0) {
		LM_ERR("cannot bind to local address and port [%s:%d]\n", laddr, lport);
		close(evapi_srv_sock);
		return -1;
	}
	if (listen(evapi_srv_sock, 4) < 0) {
		LM_ERR("listen error\n");
		close(evapi_srv_sock);
		return -1;
	}
	ev_io_init(&io_server, evapi_accept_client, evapi_srv_sock, EV_READ);
	ev_io_start(loop, &io_server);
	ev_io_init(&io_notify, evapi_recv_notify, _evapi_notify_sockets[0], EV_READ);
	ev_io_start(loop, &io_notify);

	while(1) {
		ev_loop (loop, 0);
	}

	return 0;
}
Example #20
0
File: ev.cpp Project: AmkG/snap
	void wait(CentralIOToDo todo) {
		getall(todo);
		ev_loop(ev_default_loop(0), EVLOOP_ONESHOT);
	}
Example #21
0
int main(int argc, char *argv[])
{
  // read options

  char *dir = NULL;
  short badarg = 0;

  int opt; while ((opt = getopt(argc, argv, "d:")) != -1)
  {
    if (opt == 'd') dir = optarg;
    else badarg = 1;
  }

  if (badarg) { print_usage(); return 1; }

  // change dir

  dir = flon_path(argv[0], dir);

  if (chdir(dir) != 0)
  {
    fgaj_r("couldn't chdir to %s", dir);
    return 1;
  }

  fgaj_i("-d %s", dir);

  // load configuration

  if (flon_configure(".") != 0)
  {
    fgaj_r("couldn't read %s/etc/flon.json, cannot start", dir);
    return 1;
  }

  free(dir);

  // set up logging

  flon_setup_logging("dispatcher");

  // scan once

  scan_dir();

  // load timers

  flon_load_timers();

  // then, ev...

  struct ev_loop *l = ev_default_loop(0);

  // watch var/spool/dis/

  ev_stat est;
  ev_stat_init(&est, spool_cb, "var/spool/dis/", 0.);
  ev_stat_start(l, &est);

  // check from time to time too

  ev_periodic epe;
  ev_periodic_init(&epe, trigger_cb, 0., .35, trigger_reschedule_cb);
  ev_periodic_start(l, &epe);

  //ev_timer eti;
  //ev_timer_init(&eti, do_something_when_loop_ready_cb, 0., 0.);
  //ev_timer_start(l, &eti);

  ev_signal esi;
  ev_signal_init(&esi, sighup_cb, SIGHUP);
  ev_signal_start(l, &esi);

  // loop

  //fgaj_i("about to ev_loop...");

  ev_loop(l, 0);

  fgaj_r("something went wrong");
}
Example #22
0
Loop::Loop(int opts) : event_ids(0), options_(opts), owner(false) {
    base = ev_default_loop(options_);

    /* @todo Should fail here if default returns NULL */
}
Example #23
0
File: atest.c Project: ccrome/atest
int main(int argc, char * const argv[]) {

    int result,i,r;
    int opt_index;
    int opt_rate = -1;
    int opt_channels = -1;
    int opt_period = 0;
    int opt_duration = 0;
    int opt_assert = 0;
    int opt_invalid_log_size = 0;
    const char *opt_device = NULL;
    const char *opt_config = NULL;
    const char *opt_priority = NULL;
    struct alsa_config config;

    struct ev_io stdin_watcher;
    struct ev_timer duration_timer;

    loop = ev_default_loop(0);

    while (1) {
        if ((result = getopt_long( argc, argv, "+r:c:p:D:C:P:d:aI:", options, &opt_index )) == EOF) break;
        switch (result) {
        case '?':
            usage();
            break;
        case 'r':
            opt_rate = atoi(optarg);
            break;
        case 'c':
            opt_channels = atoi(optarg);
            break;
        case 'p':
            opt_period = atoi(optarg);
            break;
        case 'd':
            opt_duration = atoi(optarg);
            break;
        case 'D':
            opt_device = optarg;
            break;
        case 'C':
            opt_config = optarg;
            break;
        case 'P':
            opt_priority = optarg;
            break;
        case 'a':
            opt_assert = 1;
            break;
        case 'I':
            opt_invalid_log_size = atoi(optarg);
            break;
        }
    }

    /* generate the config */
    alsa_config_init( &config, opt_config );
    if (opt_rate > 0) config.rate = opt_rate;
    if (opt_channels > 0) config.channels = opt_channels;
    if (opt_period > 0) config.period = opt_period;
    if (opt_device) { strncpy( config.device, opt_device, sizeof(config.device)-1 ); config.device[ sizeof(config.device)-1 ] = '\0'; }
    if (opt_priority) { strncpy( config.priority, opt_priority, sizeof(config.priority)-1 ); config.priority[ sizeof(config.priority)-1 ] = '\0'; }

    /* check if the config is valid */
    if (config.device[0] == '\0') {
        printf("Undefined device.\n");
        exit(1);
    }

    dbg("dev: '%s'", config.device);

#define MAX_TESTS 2
    struct test *tests[MAX_TESTS];
    int tests_count = 0;

    /* build the tests objects */
    argc -= optind;
    argv += optind;

    while (argc) {
        struct test *t = NULL;
        if (!strcmp( argv[0], "play" )) {
            struct playback_create_opts opts = {0};
            optind = 1;
            while (1) {
                if ((result = getopt( argc, argv, "+x:r:" )) == EOF) break;
                switch (result) {
                case '?':
                    printf("invalid option '%s' for test 'play'\n", optarg);
                    usage();
                    break;
                case 'x':
                    opts.xrun = atoi(optarg);
                    break;
                case 'r':
                    if (sscanf(optarg, "%d,%d", &opts.restart_play_time, &opts.restart_pause_time) != 2) {
                        printf("invalid value '%s' for test 'play' option '-r'\n", optarg);
                        usage();
                    }
                    dbg("%d,%d", opts.restart_play_time, opts.restart_pause_time);
                    break;
                }
            }
            argc -= optind-1;
            argv += optind-1;
            t = playback_create( &config, &opts );
            if (!t) {
                err("failed to create a playback test");
                exit(1);
            }
        } else if (!strcmp( argv[0], "capture" )) {
            struct capture_create_opts opts = {0};
            optind = 1;
            while (1) {
                if ((result = getopt( argc, argv, "+x:r:" )) == EOF) break;
                switch (result) {
                case '?':
                    printf("invalid option '%s' for test 'capture'\n", optarg);
                    usage();
                    break;
                case 'x':
                    opts.xrun = atoi(optarg);
                    break;
                case 'r':
                    if (sscanf(optarg, "%d,%d", &opts.restart_play_time, &opts.restart_pause_time) != 2) {
                        printf("invalid value '%s' for test 'capture' option '-r'\n", optarg);
                        usage();
                    }
                    dbg("%d,%d", opts.restart_play_time, opts.restart_pause_time);
                    break;
                }
            }
            argc -= optind-1;
            argv += optind-1;
            t = capture_create( &config, &opts );
            if (!t) {
                err("failed to create a capture test");
                exit(1);
            }
        } else if (!strcmp( argv[0], "loopback_delay" )) {
            struct loopback_delay_create_opts opts = {0};
            optind = 1;
            while (1) {
                if ((result = getopt( argc, argv, "+a:s:x:" )) == EOF) break;
                switch (result) {
                case '?':
                    printf("invalid option '%s' for test 'loopback_delay'\n", optarg);
                    usage();
                    break;
                case 'a':
                    opts.assert_delay = 1;
                    opts.expected_delay = atoi(optarg);
                    break;
                case 's':
                    if (!strcmp(optarg, "capture"))
                        opts.start_sync_mode = LSM_PREPARE_CAPTURE_PLAYBACK;
                    else if (!strcmp(optarg, "play"))
                        opts.start_sync_mode = LSM_PREPARE_PLAYBACK_CAPTURE;
                    else if (!strcmp(optarg, "link"))
                        opts.start_sync_mode = LSM_LINK;
                    else {
                        printf("invalid value '%s' for test 'loopback_delay' option '-s'\n", optarg);
                        usage();
                    }
                    break;
                }
            }
            argc -= optind-1;
            argv += optind-1;
            t = loopback_delay_create( &config, &opts );
            if (!t) {
                err("failed to create a capture test");
                exit(1);
            }
        }

        if (t) {
            if (tests_count >= MAX_TESTS) {
                err("too many tests defined.");
                exit(1);
            }
            tests[tests_count++] = t;
        } else {
            printf("undefined test '%s'.\n", argv[0]);
            usage();
        }
        argc--;
        argv++;
    }
    if (tests_count == 0) {
        printf("no tests specified.\n");
        exit(1);
    }

    /* change the scheduling priority is required */
    if (config.priority[0]) {
        int p;
        if (sscanf(config.priority, "fifo,%d", &p )==1) {
            struct sched_param param;
            param.sched_priority = p;

            dbg("priority: fifo,%d", p);
            if (sched_setscheduler(0, SCHED_FIFO, &param))
               err("sched_setscheduler");
        } else if (sscanf(config.priority, "rr,%d", &p )==1) {
            struct sched_param param;
            param.sched_priority = p;

            dbg("priority: rr,%d", p);
            if (sched_setscheduler(0, SCHED_RR, &param))
                err("sched_setscheduler");
        } else if (sscanf(config.priority, "other,%d", &p )==1) {
            struct sched_param param;
            param.sched_priority = p;

            dbg("priority: other,%d", p);
            if (sched_setscheduler(0, SCHED_OTHER, &param))
                err("sched_setscheduler");
        } else {
            printf("Invalid priority '%s'\n", config.priority);
        }
    }


    /* start the various tests */
    for (i=0; i < tests_count; i++) {
        struct test *t = tests[i];
        r = t->ops->start( t );
        if (r < 0) {
            err("starting test %s failed", t->name );
            exit(1);
        }
    }

    /* setup signal handlers to exist cleanly */
    ev_signal_init(&evw_intsig, on_exit_signal, SIGINT);
    ev_signal_start(loop, &evw_intsig);

    ev_signal_init(&evw_termsig, on_exit_signal, SIGTERM);
    ev_signal_start(loop, &evw_termsig);

    ev_io_init(&stdin_watcher, on_stdin, 0, EV_READ);
    ev_io_start( loop, &stdin_watcher );

    if (opt_assert) {
        seq_error_notify = &seq_error_assert;
    }
    if (opt_invalid_log_size > 0) {
        seq_consecutive_invalid_frames_log = opt_invalid_log_size;
    }

    if (opt_duration > 0) {
        dbg("start a %d seconds duration timer", opt_duration);
        ev_timer_init( &duration_timer, on_duration_timer, opt_duration, 0 );
        ev_timer_start( loop, &duration_timer );
    }

    ev_run( loop, 0 );

    int test_exit_status = 0;
    for (i=0; i < tests_count; i++) {
        struct test *t = tests[i];
        if (t->ops->close( t )) {
            err("%s exit status: failed", t->name);
            test_exit_status = 1;
        }
    }

    printf("total number of sequence errors: %u\n", seq_errors_total);
    printf("global tests exit status: %s\n", test_exit_status ? "FAILED" : "OK");
    /* exit with a good status only if no error was detected */
    return (seq_errors_total || test_exit_status) ? 2 : 0;
}
Example #24
0
int main(int argc, char **argv) {
    int opt;
    int option_index = 0;
    char *socket_path = getenv("I3SOCK");
    char *command = NULL;
    char *fontname = NULL;
    char *i3_default_sock_path = "/tmp/i3-ipc.sock";
    struct xcb_color_strings_t colors = { NULL, };

    /* Definition of the standard-config */
    config.hide_on_modifier = 0;
    config.dockpos = DOCKPOS_NONE;
    config.disable_ws = 0;

    static struct option long_opt[] = {
        { "socket",               required_argument, 0, 's' },
        { "command",              required_argument, 0, 'c' },
        { "hide",                 no_argument,       0, 'm' },
        { "dock",                 optional_argument, 0, 'd' },
        { "font",                 required_argument, 0, 'f' },
        { "nows",                 no_argument,       0, 'w' },
        { "help",                 no_argument,       0, 'h' },
        { "version",              no_argument,       0, 'v' },
        { "verbose",              no_argument,       0, 'V' },
        { "color-bar-fg",         required_argument, 0, 'A' },
        { "color-bar-bg",         required_argument, 0, 'B' },
        { "color-active-ws-fg",   required_argument, 0, 'C' },
        { "color-active-ws-bg",   required_argument, 0, 'D' },
        { "color-inactive-ws-fg", required_argument, 0, 'E' },
        { "color-inactive-ws-bg", required_argument, 0, 'F' },
        { "color-urgent-ws-bg",   required_argument, 0, 'G' },
        { "color-urgent-ws-fg",   required_argument, 0, 'H' },
        { "color-focus-ws-bg",    required_argument, 0, 'I' },
        { "color-focus-ws-fg",    required_argument, 0, 'J' },
        { NULL,                   0,                 0, 0}
    };

    while ((opt = getopt_long(argc, argv, "s:c:d::mf:whvVA:B:C:D:E:F:G:H:I:J:", long_opt, &option_index)) != -1) {
        switch (opt) {
            case 's':
                socket_path = expand_path(optarg);
                break;
            case 'c':
                command = strdup(optarg);
                break;
            case 'm':
                config.hide_on_modifier = 1;
                break;
            case 'd':
                config.hide_on_modifier = 0;
                if (optarg == NULL) {
                    config.dockpos = DOCKPOS_BOT;
                    break;
                }
                if (!strcmp(optarg, "top")) {
                    config.dockpos = DOCKPOS_TOP;
                } else if (!strcmp(optarg, "bottom")) {
                    config.dockpos = DOCKPOS_BOT;
                } else {
                    print_usage(argv[0]);
                    exit(EXIT_FAILURE);
                }
                break;
            case 'f':
                fontname = strdup(optarg);
                break;
            case 'w':
                config.disable_ws = 1;
                break;
            case 'v':
                printf("i3bar version " I3_VERSION " © 2010-2011 Axel Wagner and contributors\n");
                exit(EXIT_SUCCESS);
                break;
            case 'V':
                config.verbose = 1;
                break;
            case 'A':
                read_color(&colors.bar_fg);
                break;
            case 'B':
                read_color(&colors.bar_bg);
                break;
            case 'C':
                read_color(&colors.active_ws_fg);
                break;
            case 'D':
                read_color(&colors.active_ws_bg);
                break;
            case 'E':
                read_color(&colors.inactive_ws_fg);
                break;
            case 'F':
                read_color(&colors.inactive_ws_bg);
                break;
            case 'G':
                read_color(&colors.urgent_ws_bg);
                break;
            case 'H':
                read_color(&colors.urgent_ws_fg);
                break;
            case 'I':
                read_color(&colors.focus_ws_bg);
                break;
            case 'J':
                read_color(&colors.focus_ws_fg);
                break;
            default:
                print_usage(argv[0]);
                exit(EXIT_SUCCESS);
                break;
        }
    }

    if (fontname == NULL) {
        /* This is a very restrictive default. More sensefull would be something like
         * "-misc-*-*-*-*--*-*-*-*-*-*-*-*". But since that produces very ugly results
         * on my machine, let's stick with this until we have a configfile */
        fontname = "-misc-fixed-medium-r-semicondensed--12-110-75-75-c-60-iso10646-1";
    }

    if (config.dockpos != DOCKPOS_NONE) {
        if (config.hide_on_modifier) {
            ELOG("--dock and --hide are mutually exclusive!\n");
            exit(EXIT_FAILURE);
        }
    } else {
        config.hide_on_modifier = 1;
    }

    main_loop = ev_default_loop(0);

    init_colors(&colors);
    char *atom_sock_path = init_xcb(fontname);

    if (socket_path == NULL) {
        socket_path = atom_sock_path;
    }

    if (socket_path == NULL) {
        ELOG("No Socket Path Specified, default to %s\n", i3_default_sock_path);
        socket_path = expand_path(i3_default_sock_path);
    }

    free_colors(&colors);

    init_outputs();
    if (init_connection(socket_path)) {
        /* We subscribe to the i3-events we need */
        subscribe_events();

        /* We initiate the main-function by requesting infos about the outputs and
         * workspaces. Everything else (creating the bars, showing the right workspace-
         * buttons and more) is taken care of by the event-driveniness of the code */
        i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_OUTPUTS, NULL);
        if (!config.disable_ws) {
            i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_WORKSPACES, NULL);
        }
    }

    /* The name of this function is actually misleading. Even if no -c is specified,
     * this function initiates the watchers to listen on stdin and react accordingly */
    start_child(command);
    FREE(command);

    /* We listen to SIGTERM/QUIT/INT and try to exit cleanly, by stopping the main-loop.
     * We only need those watchers on the stack, so putting them on the stack saves us
     * some calls to free() */
    ev_signal *sig_term = malloc(sizeof(ev_signal));
    ev_signal *sig_int = malloc(sizeof(ev_signal));
    ev_signal *sig_hup = malloc(sizeof(ev_signal));

    if (sig_term == NULL || sig_int == NULL || sig_hup == NULL) {
        ELOG("malloc() failed: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    ev_signal_init(sig_term, &sig_cb, SIGTERM);
    ev_signal_init(sig_int, &sig_cb, SIGINT);
    ev_signal_init(sig_hup, &sig_cb, SIGHUP);

    ev_signal_start(main_loop, sig_term);
    ev_signal_start(main_loop, sig_int);
    ev_signal_start(main_loop, sig_hup);

    /* From here on everything should run smooth for itself, just start listening for
     * events. We stop simply stop the event-loop, when we are finished */
    ev_loop(main_loop, 0);

    kill_child();

    FREE(statusline_buffer);

    clean_xcb();
    ev_default_destroy();

    free_workspaces();

    return 0;
}
Example #25
0
/*
 * loop function
 */
static int default_loop(lua_State *L) {
    unsigned int flags = (unsigned int)luaL_optinteger(L, 1, EVFLAG_AUTO);
    struct ev_loop *loop = ev_default_loop(flags);
    setloop(L, loop);
    return 1;
}
int main(int argc, char **argv)
{
	int sigs[] = { SIGINT, SIGKILL, SIGTERM, SIGSEGV, SIGFPE };
	struct ev_signal signals[ARRAY_SIZE(sigs)];
	struct ev_loop *loop = ev_default_loop(0);
	struct lws_context_creation_info info;
	char interface_name[128] = "";
	const char *iface = NULL;
	ev_timer timeout_watcher;
	char cert_path[1024];
	char key_path[1024];
	int debug_level = 7;
	int use_ssl = 0;
	int opts = 0;
	int n = 0;
#ifndef _WIN32
	int syslog_options = LOG_PID | LOG_PERROR;
#endif
#ifndef LWS_NO_DAEMONIZE
	int daemonize = 0;
#endif

	/*
	 * take care to zero down the info struct, he contains random garbaage
	 * from the stack otherwise
	 */
	memset(&info, 0, sizeof info);
	info.port = 7681;

	while (n >= 0) {
		n = getopt_long(argc, argv, "eci:hsap:d:Dr:", options, NULL);
		if (n < 0)
			continue;
		switch (n) {
		case 'e':
			opts |= LWS_SERVER_OPTION_LIBEV;
			break;
#ifndef LWS_NO_DAEMONIZE
		case 'D':
			daemonize = 1;
			#ifndef _WIN32
			syslog_options &= ~LOG_PERROR;
			#endif
			break;
#endif
		case 'd':
			debug_level = atoi(optarg);
			break;
		case 's':
			use_ssl = 1;
			break;
		case 'a':
			opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
			break;
		case 'p':
			info.port = atoi(optarg);
			break;
		case 'i':
			strncpy(interface_name, optarg, sizeof interface_name);
			interface_name[(sizeof interface_name) - 1] = '\0';
			iface = interface_name;
			break;
		case 'c':
			close_testing = 1;
			fprintf(stderr, " Close testing mode -- closes on "
					   "client after 50 dumb increments"
					   "and suppresses lws_mirror spam\n");
			break;
		case 'r':
			resource_path = optarg;
			printf("Setting resource path to \"%s\"\n", resource_path);
			break;
		case 'h':
			fprintf(stderr, "Usage: test-server "
					"[--port=<p>] [--ssl] "
					"[-d <log bitfield>] "
					"[--resource_path <path>]\n");
			exit(1);
		}
	}

#if !defined(LWS_NO_DAEMONIZE) && !defined(WIN32)
	/*
	 * normally lock path would be /var/lock/lwsts or similar, to
	 * simplify getting started without having to take care about
	 * permissions or running as root, set to /tmp/.lwsts-lock
	 */
	if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
		fprintf(stderr, "Failed to daemonize\n");
		return 1;
	}
#endif

	for (n = 0; n < ARRAY_SIZE(sigs); n++) {
		_ev_init(&signals[n], signal_cb);
		ev_signal_set(&signals[n], sigs[n]);
		ev_signal_start(loop, &signals[n]);
	}

#ifndef _WIN32
	/* we will only try to log things according to our debug_level */
	setlogmask(LOG_UPTO (LOG_DEBUG));
	openlog("lwsts", syslog_options, LOG_DAEMON);
#endif

	/* tell the library what debug level to emit and to send it to syslog */
	lws_set_log_level(debug_level, lwsl_emit_syslog);

	lwsl_notice("libwebsockets test server - "
			"(C) Copyright 2010-2015 Andy Green <andy@warmcat.com> - "
						    "licensed under LGPL2.1\n");

	printf("Using resource path \"%s\"\n", resource_path);

	info.iface = iface;
	info.protocols = protocols;
#ifndef LWS_NO_EXTENSIONS
	info.extensions = lws_get_internal_extensions();
#endif

	info.ssl_cert_filepath = NULL;
	info.ssl_private_key_filepath = NULL;

	if (use_ssl) {
		if (strlen(resource_path) > sizeof(cert_path) - 32) {
			lwsl_err("resource path too long\n");
			return -1;
		}
		sprintf(cert_path, "%s/libwebsockets-test-server.pem",
								resource_path);
		if (strlen(resource_path) > sizeof(key_path) - 32) {
			lwsl_err("resource path too long\n");
			return -1;
		}
		sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
								resource_path);

		info.ssl_cert_filepath = cert_path;
		info.ssl_private_key_filepath = key_path;
	}
	info.gid = -1;
	info.uid = -1;
	info.max_http_header_pool = 1;
	info.options = opts | LWS_SERVER_OPTION_LIBEV;

	context = lws_create_context(&info);
	if (context == NULL) {
		lwsl_err("libwebsocket init failed\n");
		return -1;
	}

	/*
	 * this shows how to override the lws file operations.  You don't need
	 * to do any of this unless you have a reason (eg, want to serve
	 * compressed files without decompressing the whole archive)
	 */
	/* stash original platform fops */
	fops_plat = *(lws_get_fops(context));
	/* override the active fops */
	lws_get_fops(context)->open = test_server_fops_open;

	lws_initloop(context, loop);

	_ev_timer_init(&timeout_watcher, ev_timeout_cb, 0.05, 0.05);
	ev_timer_start(loop, &timeout_watcher);

	while (!force_exit)
		ev_run(loop, 0);

	lws_context_destroy(context);
	ev_loop_destroy(loop);

	lwsl_notice("libwebsockets-test-server exited cleanly\n");

#ifndef _WIN32
	closelog();
#endif

	return 0;
}
Example #27
0

static void _child_ev_cb(EV_P_ struct ev_signal *w, int revents) {
  environment e = (environment)w->data;

  // call for all VMs/states
  ht_vconfig_each(e->machines, _find_child_waiters);
}

environment environment_new() {
  environment e = ALLOC_N(struct rubinius_environment, 1);
  e->machines = ht_vconfig_create(11);
  e->machine_id = 1;

  e->messages = ht_vconfig_create(11);
  e->sig_event_base = ev_default_loop(EVFLAG_FORKCHECK);
  return e;
}

static void _fork_event_loops(int key, void *mach) {
  machine m = mach;
  ev_loop_fork(m->s->event_base);
  ev_loop(m->s->event_base, EVLOOP_NONBLOCK);
}

void environment_fork() {
  environment e = environment_current();

  ev_default_fork();
  ev_loop(e->sig_event_base, EVLOOP_NONBLOCK);
  ht_vconfig_each(e->machines, _fork_event_loops);
Example #28
0
int ugh_daemon_exec(const char *cfg_filename, unsigned daemon)
{
	int rc;
	ugh_daemon_t d;

	aux_clrptr(&d);

	loop = ev_default_loop(0);

	/* TODO make it possible to set default values for each module config and
	 * global config via ugh_make_command macro (by setting all this at
	 * module_handle_add stage)
	 */
	rc = ugh_config_init(&d.cfg);
	if (0 > rc) return -1;

	rc = ugh_config_load(&d.cfg, cfg_filename);
	if (0 > rc) return -1;

	if (daemon)
	{
		rc = log_create(d.cfg.log_error, log_levels(d.cfg.log_level));
		if (0 > rc) return -1;
	}
	else
	{
		log_level = log_levels(d.cfg.log_level);
	}

	rc = ugh_resolver_init(&d.resolver, &d.cfg);
	if (0 > rc) return -1;

	size_t i;

	for (i = 0; i < ugh_module_handles_size; ++i)
	{
		if (ugh_module_handles[i].module->init)
		{
			rc = ugh_module_handles[i].module->init(&d.cfg, ugh_module_handles[i].config);
			if (0 > rc) return -1;
		}
	}

	rc = ugh_server_listen(&d.srv, &d.cfg, &d.resolver);
	if (0 > rc) return -1;

	ev_timer_init(&d.wev_silent, ugh_wcb_silent, 0, UGH_CONFIG_SILENT_TIMEOUT);
	ev_timer_again(loop, &d.wev_silent);

	ev_run(loop, 0);

	ugh_server_enough(&d.srv);

	for (i = 0; i < ugh_module_handles_size; ++i)
	{
		if (ugh_module_handles[i].module->free)
		{
			rc = ugh_module_handles[i].module->free(&d.cfg, ugh_module_handles[i].config);
			if (0 > rc) return -1;
		}
	}

	ugh_resolver_free(&d.resolver);

	ugh_config_free(&d.cfg);

	return 0;
}
Example #29
0
/** Hello, this is main.
 * \param argc Who knows.
 * \param argv Who knows.
 * \return EXIT_SUCCESS I hope.
 */
int
main(int argc, char **argv)
{
    char *confpath = NULL;
    int xfd, i, screen_nbr, opt, colors_nbr;
    xcolor_init_request_t colors_reqs[2];
    ssize_t cmdlen = 1;
    xdgHandle xdg;
    xcb_generic_event_t *event;
    static struct option long_options[] =
    {
        { "help",    0, NULL, 'h' },
        { "version", 0, NULL, 'v' },
        { "config",  1, NULL, 'c' },
        { "check",   0, NULL, 'k' },
        { NULL,      0, NULL, 0 }
    };

    /* event loop watchers */
    ev_io xio    = { .fd = -1 };
    ev_check xcheck;
    ev_prepare a_refresh;
    ev_signal sigint;
    ev_signal sigterm;
    ev_signal sighup;

    /* clear the globalconf structure */
    p_clear(&globalconf, 1);
    globalconf.keygrabber = LUA_REFNIL;
    globalconf.mousegrabber = LUA_REFNIL;
    buffer_init(&globalconf.startup_errors);

    /* save argv */
    for(i = 0; i < argc; i++)
        cmdlen += a_strlen(argv[i]) + 1;

    globalconf.argv = p_new(char, cmdlen);
    a_strcpy(globalconf.argv, cmdlen, argv[0]);

    for(i = 1; i < argc; i++)
    {
        a_strcat(globalconf.argv, cmdlen, " ");
        a_strcat(globalconf.argv, cmdlen, argv[i]);
    }

    /* Text won't be printed correctly otherwise */
    setlocale(LC_CTYPE, "");

    /* Get XDG basedir data */
    xdgInitHandle(&xdg);

    /* init lua */
    luaA_init(&xdg);

    /* check args */
    while((opt = getopt_long(argc, argv, "vhkc:",
                             long_options, NULL)) != -1)
        switch(opt)
        {
          case 'v':
            eprint_version();
            break;
          case 'h':
            exit_help(EXIT_SUCCESS);
            break;
          case 'k':
            if(!luaA_parserc(&xdg, confpath, false))
            {
                fprintf(stderr, "✘ Configuration file syntax error.\n");
                return EXIT_FAILURE;
            }
            else
            {
                fprintf(stderr, "✔ Configuration file syntax OK.\n");
                return EXIT_SUCCESS;
            }
          case 'c':
            if(a_strlen(optarg))
                confpath = a_strdup(optarg);
            else
                fatal("-c option requires a file name");
            break;
        }

    globalconf.loop = ev_default_loop(0);
    ev_timer_init(&globalconf.timer, &luaA_on_timer, 0., 0.);

    /* register function for signals */
    ev_signal_init(&sigint, exit_on_signal, SIGINT);
    ev_signal_init(&sigterm, exit_on_signal, SIGTERM);
    ev_signal_init(&sighup, restart_on_signal, SIGHUP);
    ev_signal_start(globalconf.loop, &sigint);
    ev_signal_start(globalconf.loop, &sigterm);
    ev_signal_start(globalconf.loop, &sighup);
    ev_unref(globalconf.loop);
    ev_unref(globalconf.loop);
    ev_unref(globalconf.loop);

    struct sigaction sa = { .sa_handler = signal_fatal, .sa_flags = 0 };
    sigemptyset(&sa.sa_mask);
    sigaction(SIGSEGV, &sa, 0);

    /* XLib sucks */
    XkbIgnoreExtension(True);

    /* X stuff */
    globalconf.display = XOpenDisplay(NULL);
    if (globalconf.display == NULL)
        fatal("cannot open display");

    globalconf.default_screen = XDefaultScreen(globalconf.display);

    globalconf.connection = XGetXCBConnection(globalconf.display);

    /* Double checking then everything is OK. */
    if(xcb_connection_has_error(globalconf.connection))
        fatal("cannot open display");

    /* Prefetch all the extensions we might need */
    xcb_prefetch_extension_data(globalconf.connection, &xcb_big_requests_id);
    xcb_prefetch_extension_data(globalconf.connection, &xcb_test_id);
    xcb_prefetch_extension_data(globalconf.connection, &xcb_randr_id);
    xcb_prefetch_extension_data(globalconf.connection, &xcb_shape_id);

    /* initialize dbus */
    a_dbus_init();

    /* Get the file descriptor corresponding to the X connection */
    xfd = xcb_get_file_descriptor(globalconf.connection);
    ev_io_init(&xio, &a_xcb_io_cb, xfd, EV_READ);
    ev_io_start(globalconf.loop, &xio);
    ev_check_init(&xcheck, &a_xcb_check_cb);
    ev_check_start(globalconf.loop, &xcheck);
    ev_unref(globalconf.loop);
    ev_prepare_init(&a_refresh, &a_refresh_cb);
    ev_prepare_start(globalconf.loop, &a_refresh);
    ev_unref(globalconf.loop);

    /* Grab server */
    xcb_grab_server(globalconf.connection);

    /* Make sure there are no pending events. Since we didn't really do anything
     * at all yet, we will just discard all events which we received so far.
     * The above GrabServer should make sure no new events are generated. */
    xcb_aux_sync(globalconf.connection);
    while ((event = xcb_poll_for_event(globalconf.connection)) != NULL)
    {
        /* Make sure errors are printed */
        uint8_t response_type = XCB_EVENT_RESPONSE_TYPE(event);
        if(response_type == 0)
            event_handle(event);
        p_delete(&event);
    }

    for(screen_nbr = 0;
        screen_nbr < xcb_setup_roots_length(xcb_get_setup(globalconf.connection));
        screen_nbr++)
    {
        const uint32_t select_input_val = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;

        /* This causes an error if some other window manager is running */
        xcb_change_window_attributes(globalconf.connection,
                                     xutil_screen_get(globalconf.connection, screen_nbr)->root,
                                     XCB_CW_EVENT_MASK, &select_input_val);
    }

    /* Need to xcb_flush to validate error handler */
    xcb_aux_sync(globalconf.connection);

    /* Process all errors in the queue if any. There can be no events yet, so if
     * this function returns something, it must be an error. */
    if (xcb_poll_for_event(globalconf.connection) != NULL)
        fatal("another window manager is already running");

    /* Prefetch the maximum request length */
    xcb_prefetch_maximum_request_length(globalconf.connection);

    /* check for xtest extension */
    const xcb_query_extension_reply_t *xtest_query;
    xtest_query = xcb_get_extension_data(globalconf.connection, &xcb_test_id);
    globalconf.have_xtest = xtest_query->present;

    /* Allocate the key symbols */
    globalconf.keysyms = xcb_key_symbols_alloc(globalconf.connection);
    xcb_get_modifier_mapping_cookie_t xmapping_cookie =
        xcb_get_modifier_mapping_unchecked(globalconf.connection);

    /* init atom cache */
    atoms_init(globalconf.connection);

    /* init screens information */
    screen_scan();

    /* init default font and colors */
    colors_reqs[0] = xcolor_init_unchecked(&globalconf.colors.fg,
                                           "black", sizeof("black") - 1);

    colors_reqs[1] = xcolor_init_unchecked(&globalconf.colors.bg,
                                           "white", sizeof("white") - 1);

    globalconf.font = draw_font_new("sans 8");

    for(colors_nbr = 0; colors_nbr < 2; colors_nbr++)
        xcolor_init_reply(colors_reqs[colors_nbr]);

    xutil_lock_mask_get(globalconf.connection, xmapping_cookie,
                        globalconf.keysyms, &globalconf.numlockmask,
                        &globalconf.shiftlockmask, &globalconf.capslockmask,
                        &globalconf.modeswitchmask);

    /* Get the window tree associated to this screen */
    const int screen_max = xcb_setup_roots_length(xcb_get_setup(globalconf.connection));
    xcb_query_tree_cookie_t tree_c[screen_max];

    /* do this only for real screen */
    for(screen_nbr = 0; screen_nbr < screen_max; screen_nbr++)
    {
        /* select for events */
        const uint32_t change_win_vals[] =
        {
            XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY
                | XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW
                | XCB_EVENT_MASK_STRUCTURE_NOTIFY
                | XCB_EVENT_MASK_PROPERTY_CHANGE
                | XCB_EVENT_MASK_BUTTON_PRESS
                | XCB_EVENT_MASK_BUTTON_RELEASE
                | XCB_EVENT_MASK_FOCUS_CHANGE
        };

        tree_c[screen_nbr] = xcb_query_tree_unchecked(globalconf.connection,
                                                      xutil_screen_get(globalconf.connection, screen_nbr)->root);

        xcb_change_window_attributes(globalconf.connection,
                                     xutil_screen_get(globalconf.connection, screen_nbr)->root,
                                     XCB_CW_EVENT_MASK,
                                     change_win_vals);
        ewmh_init(screen_nbr);
        systray_init(screen_nbr);
    }

    /* init spawn (sn) */
    spawn_init();

    /* we will receive events, stop grabbing server */
    xcb_ungrab_server(globalconf.connection);

    /* Parse and run configuration file */
    if (!luaA_parserc(&xdg, confpath, true))
        fatal("couldn't find any rc file");

    scan(tree_c);

    xcb_flush(globalconf.connection);

    /* main event loop */
    ev_loop(globalconf.loop, 0);

    /* cleanup event loop */
    ev_ref(globalconf.loop);
    ev_check_stop(globalconf.loop, &xcheck);
    ev_ref(globalconf.loop);
    ev_prepare_stop(globalconf.loop, &a_refresh);
    ev_ref(globalconf.loop);
    ev_io_stop(globalconf.loop, &xio);

    awesome_atexit(false);

    return EXIT_SUCCESS;
}
Example #30
0
	MyServer() :
		loop_(ev_default_loop()),
		sigterm_(loop_),
		http_()
	{
	}