JABBER_MAIN("jabberd2c2s", "Jabber 2 C2S", "Jabber Open Source Server: Client to Server", "jabberd2router\0")
{
    c2s_t c2s;
    char *config_file;
    int optchar;
    int mio_timeout;
    sess_t sess;
    bres_t res;
    union xhashv xhv;
    time_t check_time = 0;
    const char *cli_id = 0;

#ifdef HAVE_UMASK
    umask((mode_t) 0027);
#endif

    srand(time(NULL));

#ifdef HAVE_WINSOCK2_H
/* get winsock running */
    {
        WORD wVersionRequested;
        WSADATA wsaData;
        int err;

        wVersionRequested = MAKEWORD( 2, 2 );

        err = WSAStartup( wVersionRequested, &wsaData );
        if ( err != 0 ) {
            /* !!! tell user that we couldn't find a usable winsock dll */
            return 0;
        }
    }
#endif

    jabber_signal(SIGINT, _c2s_signal);
    jabber_signal(SIGTERM, _c2s_signal);
#ifdef SIGHUP
    jabber_signal(SIGHUP, _c2s_signal_hup);
#endif
#ifdef SIGPIPE
    jabber_signal(SIGPIPE, SIG_IGN);
#endif
    jabber_signal(SIGUSR1, _c2s_signal_usr1);
    jabber_signal(SIGUSR2, _c2s_signal_usr2);


    c2s = (c2s_t) calloc(1, sizeof(struct c2s_st));

    /* load our config */
    c2s->config = config_new();

    config_file = CONFIG_DIR "/c2s.xml";

    /* cmdline parsing */
    while((optchar = getopt(argc, argv, "Dc:hi:?")) >= 0)
    {
        switch(optchar)
        {
            case 'c':
                config_file = optarg;
                break;
            case 'D':
#ifdef DEBUG
                set_debug_flag(1);
#else
                printf("WARN: Debugging not enabled.  Ignoring -D.\n");
#endif
                break;
            case 'i':
                cli_id = optarg;
                break;
            case 'h': case '?': default:
                fputs(
                    "c2s - jabberd client-to-server connector (" VERSION ")\n"
                    "Usage: c2s <options>\n"
                    "Options are:\n"
                    "   -c <config>     config file to use [default: " CONFIG_DIR "/c2s.xml]\n"
                    "   -i id           Override <id> config element\n"
#ifdef DEBUG
                    "   -D              Show debug output\n"
#endif
                    ,
                    stdout);
                config_free(c2s->config);
                free(c2s);
                return 1;
        }
    }

    if(config_load_with_id(c2s->config, config_file, cli_id) != 0)
    {
        fputs("c2s: couldn't load config, aborting\n", stderr);
        config_free(c2s->config);
        free(c2s);
        return 2;
    }

    c2s->stream_redirects = xhash_new(11);

    _c2s_config_expand(c2s);

    c2s->log = log_new(c2s->log_type, c2s->log_ident, c2s->log_facility);

    c2s->ar_modules = xhash_new(5);
    if(c2s->ar_module_name == NULL) {
        log_write(c2s->log, LOG_NOTICE, "no default authreg module specified in config file");
    }
    else if((c2s->ar = authreg_init(c2s, c2s->ar_module_name)) == NULL) {
        access_free(c2s->access);
        config_free(c2s->config);
        log_free(c2s->log);
        free(c2s);
        exit(1);
    }

    log_write(c2s->log, LOG_NOTICE, "starting up");

    _c2s_pidfile(c2s);

    c2s->sessions = xhash_new(1023);

    c2s->conn_rates = xhash_new(101);

    c2s->dead = jqueue_new();

    c2s->dead_sess = jqueue_new();

    c2s->sx_env = sx_env_new();

#ifdef HAVE_SSL
    /* get the ssl context up and running */
    if(c2s->local_pemfile != NULL) {
        c2s->sx_ssl = sx_env_plugin(c2s->sx_env, sx_ssl_init, NULL, c2s->local_pemfile, c2s->local_cachain, c2s->local_verify_mode, c2s->local_private_key_password, c2s->local_ciphers);
        if(c2s->sx_ssl == NULL) {
            log_write(c2s->log, LOG_ERR, "failed to load local SSL pemfile, SSL will not be available to clients");
            c2s->local_pemfile = NULL;
        }
    }

    /* try and get something online, so at least we can encrypt to the router */
    if(c2s->sx_ssl == NULL && c2s->router_pemfile != NULL) {
        c2s->sx_ssl = sx_env_plugin(c2s->sx_env, sx_ssl_init, NULL, c2s->router_pemfile, c2s->router_cachain, NULL, c2s->router_private_key_password, c2s->router_ciphers);
        if(c2s->sx_ssl == NULL) {
            log_write(c2s->log, LOG_ERR, "failed to load router SSL pemfile, channel to router will not be SSL encrypted");
            c2s->router_pemfile = NULL;
        }
    }
#endif

#ifdef USE_WEBSOCKET
    /* possibly wrap in websocket */
    if(c2s->websocket) {
        sx_env_plugin(c2s->sx_env, sx_websocket_init, c2s->http_forward);
    }
#else
    if(c2s->websocket) {
        log_write(c2s->log, LOG_ERR, "websocket support not built-in - not enabling");
    }
    if(c2s->http_forward) {
        log_write(c2s->log, LOG_ERR, "httpforward available only with websocket support built-in");
    }
#endif

#ifdef HAVE_LIBZ
    /* get compression up and running */
    if(c2s->compression) {
        sx_env_plugin(c2s->sx_env, sx_compress_init);
    }
#endif

    /* get stanza ack up */
    sx_env_plugin(c2s->sx_env, sx_ack_init);

    /* and user IP address plugin */
    sx_env_plugin(c2s->sx_env, address_init);

    /* get sasl online */
    c2s->sx_sasl = sx_env_plugin(c2s->sx_env, sx_sasl_init, "xmpp", _c2s_sx_sasl_callback, (void *) c2s);
    if(c2s->sx_sasl == NULL) {
        log_write(c2s->log, LOG_ERR, "failed to initialise SASL context, aborting");
        exit(1);
    }

    /* get bind up */
    sx_env_plugin(c2s->sx_env, bind_init, c2s);

    c2s->mio = mio_new(c2s->io_max_fds);
    if(c2s->mio == NULL) {
        log_write(c2s->log, LOG_ERR, "failed to create MIO, aborting");
        exit(1);
    }

    /* hosts mapping */
    c2s->hosts = xhash_new(1021);
    _c2s_hosts_expand(c2s);
    c2s->sm_avail = xhash_new(1021);

    c2s->retry_left = c2s->retry_init;
    _c2s_router_connect(c2s);

    mio_timeout = ((c2s->io_check_interval != 0 && c2s->io_check_interval < 5) ?
        c2s->io_check_interval : 5);

    while(!c2s_shutdown) {
        mio_run(c2s->mio, mio_timeout);

        if(c2s_logrotate) {
            set_debug_log_from_config(c2s->config);

            log_write(c2s->log, LOG_NOTICE, "reopening log ...");
            log_free(c2s->log);
            c2s->log = log_new(c2s->log_type, c2s->log_ident, c2s->log_facility);
            log_write(c2s->log, LOG_NOTICE, "log started");

            c2s_logrotate = 0;
        }

        if(c2s_sighup) {
            log_write(c2s->log, LOG_NOTICE, "reloading some configuration items ...");
            config_t conf;
            conf = config_new();
            if (conf && config_load(conf, config_file) == 0) {
                xhash_free(c2s->stream_redirects);
                c2s->stream_redirects = xhash_new(11);

                char *req_domain, *to_address, *to_port;
                config_elem_t elem;
                int i;
                stream_redirect_t sr;

                elem = config_get(conf, "stream_redirect.redirect");
                if(elem != NULL)
                {
                    for(i = 0; i < elem->nvalues; i++)
                    {
                        sr = (stream_redirect_t) pmalloco(xhash_pool(c2s->stream_redirects), sizeof(struct stream_redirect_st));
                        if(!sr) {
                            log_write(c2s->log, LOG_ERR, "cannot allocate memory for new stream redirection record, aborting");
                            exit(1);
                        }
                        req_domain = j_attr((const char **) elem->attrs[i], "requested_domain");
                        to_address = j_attr((const char **) elem->attrs[i], "to_address");
                        to_port = j_attr((const char **) elem->attrs[i], "to_port");

                        if(req_domain == NULL || to_address == NULL || to_port == NULL) {
                            log_write(c2s->log, LOG_ERR, "Error reading a stream_redirect.redirect element from file, skipping");
                            continue;
                        }

                        // Note that to_address should be RFC 3986 compliant
                        sr->to_address = to_address;
                        sr->to_port = to_port;

                        xhash_put(c2s->stream_redirects, pstrdup(xhash_pool(c2s->stream_redirects), req_domain), sr);
                    }
                }
                config_free(conf);
            } else {
                log_write(c2s->log, LOG_WARNING, "couldn't reload config (%s)", config_file);
                if (conf) config_free(conf);
            }
            c2s_sighup = 0;
        }

        if(c2s_lost_router) {
            if(c2s->retry_left < 0) {
                log_write(c2s->log, LOG_NOTICE, "attempting reconnect");
                sleep(c2s->retry_sleep);
                c2s_lost_router = 0;
                if (c2s->router) sx_free(c2s->router);
                _c2s_router_connect(c2s);
            }

            else if(c2s->retry_left == 0) {
                c2s_shutdown = 1;
            }

            else {
                log_write(c2s->log, LOG_NOTICE, "attempting reconnect (%d left)", c2s->retry_left);
                c2s->retry_left--;
                sleep(c2s->retry_sleep);
                c2s_lost_router = 0;
                if (c2s->router) sx_free(c2s->router);
                _c2s_router_connect(c2s);
            }
        }

        /* cleanup dead sess (before sx_t as sess->result uses sx_t nad cache) */
        while(jqueue_size(c2s->dead_sess) > 0) {
            sess = (sess_t) jqueue_pull(c2s->dead_sess);

            /* free sess data */
            if(sess->ip != NULL) free((void*)sess->ip);
            if(sess->smcomp != NULL) free((void*)sess->smcomp);
            if(sess->result != NULL) nad_free(sess->result);
            if(sess->resources != NULL)
                for(res = sess->resources; res != NULL;) {
                    bres_t tmp = res->next;
                    jid_free(res->jid);
                    free(res);
                    res = tmp;
                }
            if(sess->rate != NULL) rate_free(sess->rate);
            if(sess->stanza_rate != NULL) rate_free(sess->stanza_rate);

            free(sess);
        }

        /* cleanup dead sx_ts */
        while(jqueue_size(c2s->dead) > 0)
            sx_free((sx_t) jqueue_pull(c2s->dead));

        /* time checks */
        if(c2s->io_check_interval > 0 && time(NULL) >= c2s->next_check) {
            log_debug(ZONE, "running time checks");

            _c2s_time_checks(c2s);

            c2s->next_check = time(NULL) + c2s->io_check_interval;
            log_debug(ZONE, "next time check at %d", c2s->next_check);
        }

        if(time(NULL) > check_time + 60) {
#ifdef POOL_DEBUG
            pool_stat(1);
#endif
            if(c2s->packet_stats != NULL) {
                int fd = open(c2s->packet_stats, O_TRUNC | O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP);
                if (fd >= 0) {
                    char buf[100];
                    int len = snprintf(buf, 100, "%lld\n", c2s->packet_count);
                    if (write(fd, buf, len) != len) {
                        close(fd);
                        fd = -1;
                    } else close(fd);
                }
                if (fd < 0) {
                    log_write(c2s->log, LOG_ERR, "failed to write packet statistics to: %s", c2s->packet_stats);
                    c2s_shutdown = 1;
                }
            }

            check_time = time(NULL);
        }
    }

    log_write(c2s->log, LOG_NOTICE, "shutting down");

    if(xhash_iter_first(c2s->sessions))
        do {
            xhv.sess_val = &sess;
            xhash_iter_get(c2s->sessions, NULL, NULL, xhv.val);

            if(sess->active && sess->s)
                sx_close(sess->s);

        } while(xhash_iter_next(c2s->sessions));

    /* cleanup dead sess */
    while(jqueue_size(c2s->dead_sess) > 0) {
        sess = (sess_t) jqueue_pull(c2s->dead_sess);

        /* free sess data */
        if(sess->ip != NULL) free((void*)sess->ip);
        if(sess->result != NULL) nad_free(sess->result);
        if(sess->resources != NULL)
            for(res = sess->resources; res != NULL;) {
                bres_t tmp = res->next;
                jid_free(res->jid);
                free(res);
                res = tmp;
            }

        free(sess);
    }

    while(jqueue_size(c2s->dead) > 0)
        sx_free((sx_t) jqueue_pull(c2s->dead));

    if (c2s->fd != NULL) mio_close(c2s->mio, c2s->fd);
    sx_free(c2s->router);

    sx_env_free(c2s->sx_env);

    mio_free(c2s->mio);

    xhash_free(c2s->sessions);

    xhash_walk(c2s->ar_modules, _c2s_ar_free, NULL);
    xhash_free(c2s->ar_modules);

    xhash_free(c2s->conn_rates);

    xhash_free(c2s->stream_redirects);

    xhash_free(c2s->sm_avail);

    xhash_free(c2s->hosts);

    jqueue_free(c2s->dead);

    jqueue_free(c2s->dead_sess);

    access_free(c2s->access);

    log_free(c2s->log);

    config_free(c2s->config);

    free(c2s);

#ifdef POOL_DEBUG
    pool_stat(1);
#endif

#ifdef HAVE_WINSOCK2_H
    WSACleanup();
#endif

    return 0;
}