int main(int argc, char *argv[]) { Looper *looper; Server *server; server = NULL; looper = NULL; server = server_new(); if (!server) { printf("Can't add message and client\n"); return -1; } looper = looper_new(); if (!looper) { printf("Can't make looper\n"); } add_accept_event_call_back(looper, server_handle_accept_event); add_remove_client_call_back(looper, server_remove_client); add_handle_event_call_back(looper, server_handle_event); run(looper, server); return 0; }
void agent_control_message (agent_t *self) { zmsg_t *msg = zmsg_recv (self->control); char *command = zmsg_pop (msg); if (strcmp (command, "CONNECT") == 0) { char *endpoint = zmsg_pop (msg); printf ("I: connecting to %s...\n", endpoint); int rc = zmq_connect (self->router, endpoint); assert (rc == 0); server_t *server = server_new (endpoint); zhash_insert (self->servers, endpoint, server); zhash_freefn (self->servers, endpoint, s_server_free); zlist_append (self->actives, server); server->ping_at = s_clock () + PING_INTERVAL; server->expires = s_clock () + SERVER_TTL; free (endpoint); } else if (strcmp (command, "REQUEST") == 0) { assert (!self->request); // Strict request-reply cycle // Prefix request with sequence number and empty envelope char sequence_text [10]; sprintf (sequence_text, "%u", ++self->sequence); zmsg_push (msg, sequence_text); // Take ownership of request message self->request = msg; msg = NULL; // Request expires after global timeout self->expires = s_clock () + GLOBAL_TIMEOUT; } free (command); zmsg_destroy (&msg); }
session * new_ircwindow (server *serv, char *name, int type, int focus) { session *sess; switch (type) { case SESS_SERVER: serv = server_new (); if (prefs.hex_gui_tab_server) sess = session_new (serv, name, SESS_SERVER, focus); else sess = session_new (serv, name, SESS_CHANNEL, focus); serv->server_session = sess; serv->front_session = sess; break; case SESS_DIALOG: sess = session_new (serv, name, type, focus); log_open_or_close (sess); break; default: /* case SESS_CHANNEL: case SESS_NOTICES: case SESS_SNOTICES:*/ sess = session_new (serv, name, type, focus); break; } irc_init (sess); chanopt_load (sess); scrollback_load (sess); plugin_emit_dummy_print (sess, "Open Context"); return sess; }
static struct connection* connection_new(const char *evdev_path, const char *host_and_port) { struct connection* self; /* Allocate the new server object */ self = malloc(sizeof(struct connection)); assert(self != NULL); memset(self, 0, sizeof(struct connection)); if (evdev_init(&self->evdev, evdev_path) < 0) { connection_delete(self); return NULL; } connection_set_status_led(self, 0); connection_message(self, "Connecting to '%s'...", host_and_port); self->server = server_new(host_and_port); if (!self->server) { connection_delete(self); return NULL; } /* Tell the server about our device */ if (evdev_send_metadata(&self->evdev, self->server)) { connection_delete(self); return NULL; } connection_list_append(self); connection_message(self, "Connected"); connection_set_status_led(self, 1); return self; }
session * new_ircwindow (server *serv, char *name, int type, int focus) { session *sess; switch (type) { case SESS_SERVER: serv = server_new (); if (prefs.use_server_tab) sess = session_new (serv, name, SESS_SERVER, focus); else sess = session_new (serv, name, SESS_CHANNEL, focus); serv->server_session = sess; serv->front_session = sess; break; case SESS_DIALOG: sess = session_new (serv, name, type, focus); if (prefs.logging) log_open (sess); break; default: /* case SESS_CHANNEL: case SESS_NOTICES: case SESS_SNOTICES:*/ sess = session_new (serv, name, type, focus); break; } irc_init (sess); if (prefs.text_replay) scrollback_load (sess); return sess; }
void server_server(char *data) { char *server; server = string_index(data + 1, 0); printf("[+] server: new server <%s>\n", server); server_new(server); free(server); }
static Server* server_instance() { static Server* the_server = 0; if (!the_server) { the_server = server_new(); } return the_server; }
void hwf_container_add_address(HwfContainer *container, const char *host, int port) { Server *server; server = server_new(host, port); container->servers = g_slist_prepend(container->servers, server); }
int main(void) { Server *server = server_new("0.0.0.0", 7000); //Server *server = server_new("::", 7000); Status rc; rc = server_listen(server, 0); insist_return(rc == GREAT_SUCCESS, rc, "Server failed to start listening") printf("fd: %d\n", server->fd); server_accept(server); return 0; } /* main */
int main(int argc, char *argv[]) { server_type_t server_type; int port; read_args(argc, argv, &port, &server_type); server_t *server = server_new(server_type, port); server_set_accept_callback(server, on_client_accepted); server_set_data_callback(server, on_incoming_data); server_set_close_callback(server, on_client_closed); server_loop(server); server_destroy(server); return 0; }
void * start_server_thread_func (void *ptr) { client_thread = false; client_t *client = (client_t *)ptr; server_t *server = server_new (&client->buffer); server->server_signal = &client->server_signal; server->client_signal = &client->client_signal; mutex_unlock (client->server_started_mutex); prctl (PR_SET_TIMERSLACK, 1); pthread_t id = pthread_self (); int online_cpus = sysconf (_SC_NPROCESSORS_ONLN); int available_cpus = sysconf (_SC_NPROCESSORS_CONF); if (online_cpus > 1) { cpu_set_t cpu_set; CPU_ZERO (&cpu_set); if (pthread_getaffinity_np (id, sizeof (cpu_set_t), &cpu_set) == 0) { /* find first cpu to run on */ int cpu = 0; int i; for (i = 1; i < available_cpus; i++) { if (CPU_ISSET (i, &cpu_set)) { cpu = i; break; } } /* force server to run on cpu1 */ if (cpu == 0) cpu = 1; if (cpu != 0) { for (i = 0; i < available_cpus; i++) { if (i != cpu) CPU_CLR (i, &cpu_set); } CPU_SET (cpu, &cpu_set); pthread_setaffinity_np (id, sizeof (cpu_set_t), &cpu_set); } } } server_start_work_loop (server); server_destroy(server); return NULL; }
extern EXPORT_API gboolean gst_dvb_css_wc_start(const gchar *address, gint port, gboolean followup, guint32 max_freq_error_ppm, gboolean isDebug) { GST_DEBUG("dvb_css_wc_start\n"); G_LOCK(mutex); sServer = server_new(); if (sServer == NULL) { goto server_struct_not_initialized; } gst_init(NULL, NULL); sServer->loop = g_main_loop_new(NULL, FALSE); sServer->clock = gst_system_clock_obtain(); if(isDebug == FALSE){ sServer->gstdvbcsswcserver = gst_dvb_css_wc_server_new(sServer->clock, address, port, followup, max_freq_error_ppm); } else{ sServer->gstdvbcsswcserver = gst_net_time_provider_new(sServer->clock, address, port); } if (sServer->gstdvbcsswcserver == NULL) { GST_ERROR("Dvb_css_wc server not created\n"); goto cleanup; } g_object_get(sServer->gstdvbcsswcserver, "port", &port, NULL); GST_DEBUG("Published network clock on port %u\n", port); sServer->thread = g_thread_try_new("dvb_css_wc_thread", (GThreadFunc) g_main_loop_run, sServer->loop, NULL); if (sServer->thread == NULL) { GST_ERROR("Thread for dvb_css_wc server not created\n"); goto cleanup; } GST_DEBUG("Dvb_css_wc server started\n"); G_UNLOCK(mutex); return TRUE; /* ERRORS */ server_struct_not_initialized:{ GST_ERROR("Dvb_css_wc server struct not initialized\n"); G_UNLOCK(mutex); return FALSE; } cleanup:{ server_free(&sServer); G_UNLOCK(mutex); return FALSE; } }
void parent_main_loop(int control_port, unsigned long listen_ip, int listen_port) { Server *serv; int child; int control_fd; /* specify port and size of the listen queue we're going to use */ serv = server_new(listen_ip, listen_port, 1024); if (listen_port == DONT_CARE) fprintf(stderr,"Started accepting connections on port %d\n", serv->port); glob_server = serv; serv->control_port = control_port; /* confirm that the control port is valid, since if it isn't, we'll * have a rather nasty fork-bomb behaviour - children will suicide on * startup because they can't connect to the control port, the parent * will notice that there are fewer children than min_children, and * fork more. */ control_fd = open_connection(serv,inet_addr(control_ip),control_port,1,0); if (control_fd < 0) fatal(serv, "parent unable to open control port: %m\n"); else close(control_fd); #ifdef DEBUG fprintf(stderr,"parent pid = %ld\n", getpid()); #endif glob_child_dat.num_children = 0; for (child = 0; child < max_children; child++) glob_child_dat.children[child] = -1; for (child = 0; child < min_children; child++) (void) create_child(serv); signal(SIGCHLD, child_signal); signal(SIGPIPE, SIG_IGN); glob_child_dat.curr_child = 0; /* listen to stdin, so we know when erlang stops */ set_server_read_fd(serv, STDIN_FILENO); /* tell the first child to start handling connections */ if (debug) syslog(LOG_INFO,"passing the ball to child %d (# %d)\n", glob_child_dat.children[glob_child_dat.curr_child], glob_child_dat.curr_child); add_data(serv, glob_child_dat.child_pipe[glob_child_dat.curr_child], "x", 0, 1, fs_output); server_main_loop(serv, parent_write, parent_read, NULL); }
int main(int argc, char *argv[]) { #ifdef SIGHUP signal(SIGHUP,signal_handler); #endif if ( command_line_parameters(argc, argv) != 0 ) { exit(EXIT_FAILURE); } s = server_new(cfg_file); server_start(s); return EXIT_SUCCESS; }
session * new_ircwindow (server *serv, char *name, int type, int focus) { session *sess; switch (type) { case SESS_SERVER: serv = server_new (); if (prefs.hex_gui_tab_server) sess = session_new (serv, name, SESS_SERVER, focus); else sess = session_new (serv, name, SESS_CHANNEL, focus); serv->server_session = sess; serv->front_session = sess; break; case SESS_DIALOG: sess = session_new (serv, name, type, focus); break; default: /* case SESS_CHANNEL: case SESS_NOTICES: case SESS_SNOTICES:*/ sess = session_new (serv, name, type, focus); break; } irc_init (sess); chanopt_load (sess); scrollback_load (sess); if (sess->scrollwritten && sess->scrollback_replay_marklast) sess->scrollback_replay_marklast (sess); if (type == SESS_DIALOG) { struct User *user; log_open_or_close (sess); user = userlist_find_global (serv, name); if (user && user->hostname) set_topic (sess, user->hostname, user->hostname); } plugin_emit_dummy_print (sess, "Open Context"); return sess; }
/** * main * * Parses the user commandline input and creates and waits for the * server thread. * * @param argc number of command line arguments * @param argv the command line arguments * @return EXIT_SUCCES after successful completion. */ int main(int argc, char** argv) { int ret; struct sigaction act; server *s; act.sa_handler = signal_Handler; act.sa_flags = 0; if ((sigaction(SIGINT, &act, NULL) == -1)) { SystemFatal("Failed to set SIGINT handler\n"); } if ((sigaction(SIGPIPE, &act, NULL) == -1)) { SystemFatal("Failed to set SIGPIPE handler\n"); } if ((sigaction(SIGSEGV, &act, NULL) == -1)) { SystemFatal("Failed to set SIGPIPE handler\n"); } /* creates a new server variable and initialize the structure. */ s = server_new(); serv = s; switch (argc) { case 1: s->port = SERVER_TCP_PORT; // Use the default port break; case 2: s->port = atoi(argv[1]); // Get user specified port break; default: fprintf(stderr, "Usage: %s [port]\n", argv[0]); exit(1); } ret = pthread_create(&master_manager, NULL, client_manager, s); if (ret != 0) SystemFatal("Unable to create client management thread\n"); pthread_join(master_manager, NULL); free(s); return (EXIT_SUCCESS); }
// Finally here's the server thread itself, which polls its two // sockets and processes incoming messages static void server_thread (void *args, zctx_t *ctx, void *pipe) { server_t *self = server_new (ctx, pipe); zmq_pollitem_t items [] = { { self->pipe, 0, ZMQ_POLLIN, 0 }, { self->router, 0, ZMQ_POLLIN, 0 } }; self->monitor_at = zclock_time () + self->monitor; while (!self->stopped && !zctx_interrupted) { // Calculate tickless timer, up to interval seconds uint64_t tickless = zclock_time () + self->monitor; zhash_foreach (self->clients, client_tickless, &tickless); // Poll until at most next timer event int rc = zmq_poll (items, 2, (tickless - zclock_time ()) * ZMQ_POLL_MSEC); if (rc == -1) break; // Context has been shut down // Process incoming message from either socket if (items [0].revents & ZMQ_POLLIN) server_control_message (self); if (items [1].revents & ZMQ_POLLIN) server_client_message (self); // Send heartbeats to idle clients as needed zhash_foreach (self->clients, client_ping, self); // If clock went past timeout, then monitor server if (zclock_time () >= self->monitor_at) { monitor_the_server (self, NULL); self->monitor_at = zclock_time () + self->monitor; } } server_destroy (&self); }
/** * main function **/ int main(int argc, char ** argv) { int ret; int serviceid = 80; g_server = server_new(); atexit(stop); signal(SIGINT, terminate); ServicesFactory *factory = servicesfactory_new(); servicesfactory_add(factory, serviceid, NULL, serviceinet_new); Connector *connector = connector_new(factory, serviceid); connector_readparameters(connector, argv, argc); server_addconnector(g_server, connector); ret = server_main(g_server); server_destroy(g_server); servicesfactory_destroy(factory); return ret; }
static void start_daemon(const char *progname, struct a6o_daemon_options *opts) { struct a6o_conf *conf; struct armadito *armadito; int server_sock; struct server *server; a6o_error *error = NULL; GMainLoop *loop; loop = g_main_loop_new(NULL, FALSE); log_init(opts->s_log_level, !opts->no_daemon); if (!opts->no_daemon) daemonize(); if (opts->pid_file != NULL) create_pid_file(opts->pid_file); a6o_log(ARMADITO_LOG_SERVICE, ARMADITO_LOG_LEVEL_NONE, "starting %s%s", progname, opts->no_daemon ? "" : " in daemon mode"); conf = a6o_conf_new(); load_conf(conf); load_conf_dir(conf); armadito = a6o_open(conf, &error); if (armadito == NULL) { a6o_error_print(error, stderr); exit(EXIT_FAILURE); } server_sock = create_server_socket(opts); server = server_new(armadito, server_sock, opts->ipc_type); g_main_loop_run(loop); }
// Process message from pipe static void client_control_message (client_t *self) { zmsg_t *msg = zmsg_recv (self->pipe); char *method = zmsg_popstr (msg); if (streq (method, "SUBSCRIBE")) { char *path = zmsg_popstr (msg); // Store subscription along with any previous ones // Check we don't already have a subscription for this path self->sub = (sub_t *) zlist_first (self->subs); while (self->sub) { if (streq (path, self->sub->path)) return; self->sub = (sub_t *) zlist_next (self->subs); } // Subscription path must start with '/' // We'll do better error handling later assert (*path == '/'); // New subscription, store it for later replay char *inbox = fmq_config_resolve (self->config, "client/inbox", ".inbox"); self->sub = sub_new (self, inbox, path); zlist_append (self->subs, self->sub); free (path); } else if (streq (method, "SET INBOX")) { char *path = zmsg_popstr (msg); fmq_config_path_set (self->config, "client/inbox", path); free (path); } else if (streq (method, "SET RESYNC")) { char *enabled_string = zmsg_popstr (msg); long enabled = atoi (enabled_string); free (enabled_string); // Request resynchronization from server fmq_config_path_set (self->config, "client/resync", enabled? "1" :"0"); } else if (streq (method, "CONFIG")) { char *config_file = zmsg_popstr (msg); fmq_config_destroy (&self->config); self->config = fmq_config_load (config_file); if (self->config) client_apply_config (self); else { printf ("E: cannot load config file '%s'\n", config_file); self->config = fmq_config_new ("root", NULL); } free (config_file); } else if (streq (method, "SETOPTION")) { char *path = zmsg_popstr (msg); char *value = zmsg_popstr (msg); fmq_config_path_set (self->config, path, value); client_config_self (self); free (path); free (value); } else if (streq (method, "STOP")) { zstr_send (self->pipe, "OK"); self->stopped = true; } else if (streq (method, "CONNECT")) { char *endpoint = zmsg_popstr (msg); if (self->nbr_servers < MAX_SERVERS) { server_t *server = server_new (self->ctx, endpoint); self->servers [self->nbr_servers++] = server; self->dirty = true; client_server_execute (self, server, initialize_event); } else printf ("E: too many server connections (max %d)\n", MAX_SERVERS); free (endpoint); } free (method); zmsg_destroy (&msg); }
int main(void) { Simulation_Run_Ptr simulation_run; Simulation_Run_Data_Ptr data; /* * Declare and initialize our random number generator seeds defined in * simparameters.h */ unsigned RANDOM_SEEDS[] = {RANDOM_SEED_LIST, 0}; unsigned random_seed; int j=0; /* * Loop for each random number generator seed, doing a separate * simulation_run run for each. */ while ((random_seed = RANDOM_SEEDS[j++]) != 0) { simulation_run = simulation_run_new(); /* Create a new simulation run. */ /* * Create a Simulation_Run_Data object. This will hold all of our user * defined data (declared in main.h). Set the simulation_run data pointer * to our new object. */ data = (Simulation_Run_Data_Ptr) xmalloc(sizeof(Simulation_Run_Data)); simulation_run_set_data(simulation_run, (void*) data); /* * Initialize the simulation_run data variables, declared in main.h. */ data->blip_counter = 0; data->arrival_count = 0; data->number_of_packets_processed = 0; data->accumulated_delay = 0.0; data->random_seed = random_seed; /* * Create the packet buffer and transmission link, declared in main.h. */ data->buffer = fifoqueue_new(); data->link = server_new(); /* * Set the random number generator seed for this run. */ random_generator_initialize(random_seed); /* * Schedule the initial packet arrival for the current clock time (= 0). */ schedule_packet_arrival_event(simulation_run, simulation_run_get_time(simulation_run)); /* * Execute events until we are finished. */ while(data->number_of_packets_processed < RUNLENGTH) { simulation_run_execute_event(simulation_run); } /* * Output results and clean up after ourselves. */ output_results(simulation_run); cleanup_memory(simulation_run); } getchar(); /* Pause before finishing. */ return 0; }
int main(int argc, char * const argv[]) { int stream_sock[] = {0, 0, 0}; /* tcp4, tcp6, UNIX */ int stream_socklen = sizeof(stream_sock) / sizeof(stream_sock[0]); int dgram_sock[] = {0, 0}; /* udp4, udp6 */ int dgram_socklen = sizeof(dgram_sock) / sizeof(dgram_sock[0]); char id; unsigned short listenport = 2003; int ch; size_t numaggregators; size_t numcomputes; server *internal_submission; char *listeninterface = NULL; server **servers; char *allowed_chars = NULL; int i; enum { SUB, CUM } smode = CUM; if (gethostname(relay_hostname, sizeof(relay_hostname)) < 0) snprintf(relay_hostname, sizeof(relay_hostname), "127.0.0.1"); while ((ch = getopt(argc, argv, ":hvdmstf:i:l:p:w:b:q:S:c:H:")) != -1) { switch (ch) { case 'v': do_version(); break; case 'd': if (mode == TEST) { mode = DEBUGTEST; } else { mode = DEBUG; } break; case 'm': smode = SUB; break; case 's': mode = SUBMISSION; break; case 't': if (mode == DEBUG) { mode = DEBUGTEST; } else { mode = TEST; } break; case 'f': config = optarg; break; case 'i': listeninterface = optarg; break; case 'l': relay_logfile = optarg; break; case 'p': listenport = (unsigned short)atoi(optarg); if (listenport == 0) { fprintf(stderr, "error: port needs to be a number >0\n"); do_usage(1); } break; case 'w': workercnt = (char)atoi(optarg); if (workercnt <= 0) { fprintf(stderr, "error: workers needs to be a number >0\n"); do_usage(1); } break; case 'b': batchsize = atoi(optarg); if (batchsize <= 0) { fprintf(stderr, "error: batch size needs to be a number >0\n"); do_usage(1); } break; case 'q': queuesize = atoi(optarg); if (queuesize <= 0) { fprintf(stderr, "error: queue size needs to be a number >0\n"); do_usage(1); } break; case 'S': collector_interval = atoi(optarg); if (collector_interval <= 0) { fprintf(stderr, "error: sending interval needs to be " "a number >0\n"); do_usage(1); } break; case 'c': allowed_chars = optarg; break; case 'H': snprintf(relay_hostname, sizeof(relay_hostname), "%s", optarg); break; case '?': case ':': do_usage(1); break; case 'h': default: do_usage(0); break; } } if (optind == 1 || config == NULL) do_usage(1); /* seed randomiser for dispatcher and aggregator "splay" */ srand(time(NULL)); if (workercnt == 0) workercnt = mode == SUBMISSION ? 2 : get_cores(); /* any_of failover maths need batchsize to be smaller than queuesize */ if (batchsize > queuesize) { fprintf(stderr, "error: batchsize must be smaller than queuesize\n"); exit(-1); } if (relay_logfile != NULL && mode != TEST && mode != DEBUGTEST) { FILE *f = fopen(relay_logfile, "a"); if (f == NULL) { fprintf(stderr, "error: failed to open logfile '%s': %s\n", relay_logfile, strerror(errno)); exit(-1); } relay_stdout = f; relay_stderr = f; } else { relay_stdout = stdout; relay_stderr = stderr; } relay_can_log = 1; logout("starting carbon-c-relay v%s (%s), pid=%d\n", VERSION, GIT_VERSION, getpid()); fprintf(relay_stdout, "configuration:\n"); fprintf(relay_stdout, " relay hostname = %s\n", relay_hostname); fprintf(relay_stdout, " listen port = %u\n", listenport); if (listeninterface != NULL) fprintf(relay_stdout, " listen interface = %s\n", listeninterface); fprintf(relay_stdout, " workers = %d\n", workercnt); fprintf(relay_stdout, " send batch size = %d\n", batchsize); fprintf(relay_stdout, " server queue size = %d\n", queuesize); fprintf(relay_stdout, " statistics submission interval = %ds\n", collector_interval); if (allowed_chars != NULL) fprintf(relay_stdout, " extra allowed characters = %s\n", allowed_chars); if (mode == DEBUG || mode == DEBUGTEST) fprintf(relay_stdout, " debug = true\n"); else if (mode == SUBMISSION) fprintf(relay_stdout, " submission = true\n"); fprintf(relay_stdout, " routes configuration = %s\n", config); fprintf(relay_stdout, "\n"); if (router_readconfig(&clusters, &routes, config, queuesize, batchsize) == 0) { logerr("failed to read configuration '%s'\n", config); return 1; } router_optimise(&routes); numaggregators = aggregator_numaggregators(); numcomputes = aggregator_numcomputes(); #define dbg (mode == DEBUG || mode == DEBUGTEST ? 2 : 0) if (numaggregators > 10 && !dbg) { fprintf(relay_stdout, "parsed configuration follows:\n" "(%zd aggregations with %zd computations omitted " "for brevity)\n", numaggregators, numcomputes); router_printconfig(relay_stdout, 0, clusters, routes); } else { fprintf(relay_stdout, "parsed configuration follows:\n"); router_printconfig(relay_stdout, 1 + dbg, clusters, routes); } fprintf(relay_stdout, "\n"); /* shortcut for rule testing mode */ if (mode == TEST || mode == DEBUGTEST) { char metricbuf[METRIC_BUFSIZ]; char *p; fflush(relay_stdout); while (fgets(metricbuf, sizeof(metricbuf), stdin) != NULL) { if ((p = strchr(metricbuf, '\n')) != NULL) *p = '\0'; router_test(metricbuf, routes); } exit(0); } if (signal(SIGINT, exit_handler) == SIG_ERR) { logerr("failed to create SIGINT handler: %s\n", strerror(errno)); return 1; } if (signal(SIGTERM, exit_handler) == SIG_ERR) { logerr("failed to create SIGTERM handler: %s\n", strerror(errno)); return 1; } if (signal(SIGQUIT, exit_handler) == SIG_ERR) { logerr("failed to create SIGQUIT handler: %s\n", strerror(errno)); return 1; } if (signal(SIGHUP, hup_handler) == SIG_ERR) { logerr("failed to create SIGHUP handler: %s\n", strerror(errno)); return 1; } if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { logerr("failed to ignore SIGPIPE: %s\n", strerror(errno)); return 1; } workers = malloc(sizeof(dispatcher *) * (1 + workercnt + 1)); if (workers == NULL) { logerr("failed to allocate memory for workers\n"); return 1; } if (bindlisten(stream_sock, &stream_socklen, dgram_sock, &dgram_socklen, listeninterface, listenport) < 0) { logerr("failed to bind on port %s:%d: %s\n", listeninterface == NULL ? "" : listeninterface, listenport, strerror(errno)); return -1; } for (ch = 0; ch < stream_socklen; ch++) { if (dispatch_addlistener(stream_sock[ch]) != 0) { logerr("failed to add listener\n"); return -1; } } for (ch = 0; ch < dgram_socklen; ch++) { if (dispatch_addlistener_udp(dgram_sock[ch]) != 0) { logerr("failed to listen to datagram socket\n"); return -1; } } if ((workers[0] = dispatch_new_listener()) == NULL) logerr("failed to add listener\n"); if (allowed_chars == NULL) allowed_chars = "-_:#"; logout("starting %d workers\n", workercnt); for (id = 1; id < 1 + workercnt; id++) { workers[id + 0] = dispatch_new_connection(routes, allowed_chars); if (workers[id + 0] == NULL) { logerr("failed to add worker %d\n", id); break; } } workers[id + 0] = NULL; if (id < 1 + workercnt) { logerr("shutting down due to errors\n"); keep_running = 0; } /* server used for delivering metrics produced inside the relay, * that is collector (statistics) and aggregator (aggregations) */ if ((internal_submission = server_new("internal", listenport, CON_PIPE, NULL, 3000 + (numcomputes * 3), batchsize)) == NULL) { logerr("failed to create internal submission queue, shutting down\n"); keep_running = 0; } if (numaggregators > 0) { logout("starting aggregator\n"); if (!aggregator_start(internal_submission)) { logerr("shutting down due to failure to start aggregator\n"); keep_running = 0; } } logout("starting statistics collector\n"); collector_start(&workers[1], clusters, internal_submission, smode == CUM); logout("startup sequence complete\n"); /* workers do the work, just wait */ while (keep_running) sleep(1); logout("shutting down...\n"); /* make sure we don't accept anything new anymore */ for (ch = 0; ch < stream_socklen; ch++) dispatch_removelistener(stream_sock[ch]); destroy_usock(listenport); logout("listeners for port %u closed\n", listenport); /* since workers will be freed, stop querying the structures */ collector_stop(); logout("collector stopped\n"); if (numaggregators > 0) { aggregator_stop(); logout("aggregator stopped\n"); } server_shutdown(internal_submission); /* give a little time for whatever the collector/aggregator wrote, * to be delivered by the dispatchers */ usleep(500 * 1000); /* 500ms */ /* make sure we don't write to our servers any more */ logout("stopped worker"); for (id = 0; id < 1 + workercnt; id++) dispatch_stop(workers[id + 0]); for (id = 0; id < 1 + workercnt; id++) { dispatch_shutdown(workers[id + 0]); fprintf(relay_stdout, " %d", id + 1); fflush(relay_stdout); } fprintf(relay_stdout, "\n"); router_shutdown(); servers = router_getservers(clusters); logout("stopped server"); for (i = 0; servers[i] != NULL; i++) server_stop(servers[i]); for (i = 0; servers[i] != NULL; i++) { server_shutdown(servers[i]); fprintf(relay_stdout, " %d", i + 1); fflush(relay_stdout); } fprintf(relay_stdout, "\n"); logout("routing stopped\n"); router_free(clusters, routes); free(workers); return 0; }
int main (int argc, char *argv[]) { int i; int ret; // BEGIN NEW CODE server *fake_serv; GIOChannel *channel; session *sess; // END NEW CODE #ifdef WIN32 HRESULT coinit_result; #endif srand ((unsigned int) time (NULL)); /* CL: do this only once! */ /* We must check for the config dir parameter, otherwise load_config() will behave incorrectly. * load_config() must come before fe_args() because fe_args() calls gtk_init() which needs to * know the language which is set in the config. The code below is copy-pasted from fe_args() * for the most part. */ if (argc >= 2) { for (i = 1; i < argc; i++) { if ((strcmp (argv[i], "-d") == 0 || strcmp (argv[i], "--cfgdir") == 0) && i + 1 < argc) { xdir = g_strdup (argv[i + 1]); } else if (strncmp (argv[i], "--cfgdir=", 9) == 0) { xdir = g_strdup (argv[i] + 9); } if (xdir != NULL) { if (xdir[strlen (xdir) - 1] == G_DIR_SEPARATOR) { xdir[strlen (xdir) - 1] = 0; } break; } } } #if ! GLIB_CHECK_VERSION (2, 36, 0) // RFM: Don't think we hit this g_type_init (); #endif if (check_config_dir () == 0) { if (load_config () != 0) load_default_config (); } else { /* this is probably the first run */ load_default_config (); make_config_dirs (); make_dcc_dirs (); } /* we MUST do this after load_config () AND before fe_init (thus gtk_init) otherwise it will fail */ // RFM: Does nothing on *NIX set_locale (); // RFM: Parses some command line crap. Not important ret = fe_args (argc, argv); if (ret != -1) return ret; #ifdef USE_DBUS hexchat_remote (); #endif #ifdef USE_LIBPROXY // RFM: Not using libproxy_factory = px_proxy_factory_new(); #endif #ifdef WIN32 coinit_result = CoInitializeEx (NULL, COINIT_APARTMENTTHREADED); if (SUCCEEDED (coinit_result)) { CoInitializeSecurity (NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); } #endif // RFM: Inits some fe-text stuff fe_init (); // RFM: Pretty sure this just allows us to save chats... /* This is done here because cfgfiles.c is too early in * the startup process to use gtk functions. */ if (g_access (get_xdir (), W_OK) != 0) { char buf[2048]; g_snprintf (buf, sizeof(buf), _("You do not have write access to %s. Nothing from this session can be saved."), get_xdir ()); fe_message (buf, FE_MSG_ERROR); } // RFM: Checks if root on *NIX #ifndef WIN32 #ifndef __EMX__ /* OS/2 uses UID 0 all the time */ if (getuid () == 0) fe_message (_("* Running IRC as root is stupid! You should\n" " create a User Account and use that to login.\n"), FE_MSG_WARN|FE_MSG_WAIT); #endif #endif /* !WIN32 */ // RFM: Loads a bunch of configure options xchat_init (); // BEGIN NEW CODE fake_serv = server_new(); fake_serv->sok = STDIN_FILENO; // fake_serv->pos = 0; //??? sess = session_new(fake_serv, "fake_sess", SESS_CHANNEL, 0); fake_serv->server_session = sess; fake_serv->front_session = sess; channel = g_io_channel_unix_new(STDIN_FILENO); g_io_add_watch(channel, G_IO_IN, (GIOFunc)server_read, fake_serv); //g_io_add_watch(channel, G_IO_IN, (GIOFunc)io_callback, fake_serv); g_io_channel_unref(channel); // END NEW CODE fe_main (); #ifdef WIN32 if (SUCCEEDED (coinit_result)) { CoUninitialize (); } #endif #ifdef USE_LIBPROXY px_proxy_factory_free(libproxy_factory); #endif #ifdef WIN32 WSACleanup (); #endif return 0; }
int main(int argc, const char* argv[]) { DBusConnection* session; #if 0 dbus_uint32_t result; #endif static const DBusObjectPathVTable vtable = { .unregister_function = ping_object_unregistered_cb, .message_function = ping_object_message_handler_cb }; if (argc > 2) { usage(); return 1; } if (argc == 2) { if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) { usage(); return 1; } else { s_report = (unsigned)atoi(argv[1]); if (s_report <= 0) { fprintf(stderr, "DPONG: ERROR: invalid reporting period. Quitting!\n"); return 1; } } } g_type_init(); s_server = server_new(); set_base_time(); printf ("DPONG: server starting with PID %u ...\n", (unsigned) getpid()); printf ("DPONG: reporting period is set to %u messages.\n", s_report); printf ("DPONG: base test time set to %ld seconds.\n", base_time); dbus_error_init (&s_error) ; /* Setup main loop */ s_server->context = g_main_context_new(); s_server->loop = g_main_loop_new(s_server->context, FALSE) ; session = dbus_bus_get(DBUS_SERVER_TYPE, &s_error); if (check_dbus_error(&s_error) || NULL == session ) { fatal("DPONG: ERROR: dbus_bus_get() failure.\n"); } dbus_connection_setup_with_g_main (session, s_server->context) ; dbus_bus_request_name (session, SERVICE, DBUS_NAME_FLAG_ALLOW_REPLACEMENT, &s_error); if ( check_dbus_error(&s_error) ) { fatal("DPONG: ERROR: Unable to use service name " SERVICE "."); } #if 0 /* Create registry */ registry = bus_registry_new(BusContext*); if ( !registry ) { fatal("unable to create registry"); } if ( bus_registry_acquire_service(registry, session, SERVICE, 0, &result, transaction, &s_error) ) { fprintf (stderr, "bus_registry_acquire_service --> %u + %u\n", result, s_error); fatal("unable to acquire service"); } #endif if ( !dbus_connection_register_object_path(session, OBJECT, &vtable, NULL) ) { fatal("DPONG: ERROR: dbus_connection_register_object_path() failure."); } fprintf (stderr, "DPONG: server base service is \"%s\".\n", dbus_bus_get_unique_name(session)); fprintf (stderr, "DPONG: server is ready to accept calls!\n"); g_main_loop_run (s_server->loop) ; dbus_connection_close (session); server_delete(s_server); return 0; } /* main */
/* ==================== start_listen() ==================== */ int start_listen(int listen_port, const char *data_dir) { int r; /* -------- server_addr -------- */ struct sockaddr_in server_addr; r = uv_ip4_addr("0.0.0.0", listen_port, &server_addr); if ( r ) { error_log("uv_ip4_addr() failed."); return -1; } /* -------- server-------- */ server_t *server = server_new(); if ( server_init(server) != 0 ){ error_log("server_init() failed."); return -1; } /* -------- loop -------- */ uv_loop_t *loop = &server->connection.loop; /* -------- tcp_handle -------- */ uv_tcp_t *tcp_handle = &server->connection.handle.tcp; /* -------- uv_tcp_init -------- */ r = uv_tcp_init(loop, tcp_handle); if ( r ) { error_log("uv_tcp_init() failed."); server_free(server); return -1; } tcp_handle->data = server; /* -------- uv_tcp_bind -------- */ r = uv_tcp_bind(tcp_handle, (const struct sockaddr*)&server_addr, 0); if ( r ) { error_log("uv_tcp_bind() failed."); server_free(server); return -1; } /* -------- uv_listen -------- */ r = uv_listen((uv_stream_t*)tcp_handle, SOMAXCONN, on_connection); if ( r ) { error_log("uv_listen() failed."); server_free(server); return -1; } info_log("Listen on port %d.", listen_port); /* -------- uv_run -------- */ r = uv_run(loop, UV_RUN_DEFAULT); if ( r ) { error_log("uv_run() failed."); server_free(server); return -1; } /* FIXME */ /*MAKE_VALGRIND_HAPPY(loop);*/ /*close_loop(loop); */ /*uv_loop_delete(loop); */ server_free(server); notice_log("Server exit."); return 0; }
static void timeout_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 1, .tv_usec = 0}; timeout_t *ptr; unsigned int inmem, outmem, filemem; int i; ptr = (timeout_t *) arg; assert(ptr != NULL); assert(ptr->clockevent.ev_base != NULL); // reset the timer to go off again in 1 second. evtimer_del(&ptr->clockevent); evtimer_set(&ptr->clockevent, timeout_handler, arg); event_base_set(ptr->clockevent.ev_base, &ptr->clockevent); evtimer_add(&ptr->clockevent, &t); assert(fd == INVALID_HANDLE); assert(ptr->server != NULL); assert(ptr->stats != NULL); if (ptr->stats->in_bytes || ptr->stats->out_bytes || ptr->stats->commands || ptr->stats->operations) { inmem=0; outmem=0; filemem = 0; for(i=0; i<ptr->server->maxconns; i++) { if (ptr->server->nodes[i] != NULL) { inmem += ptr->server->nodes[i]->in.length; outmem += ptr->server->nodes[i]->out.length; filemem += ptr->server->nodes[i]->filebuf.length; } } if (inmem > 0) { inmem /= 1024; } if (outmem > 0) { outmem /= 1024; } if (filemem > 0) { filemem /= 1024; } printf("Bytes [%u/%u], Commands [%u], Operations[%u], Mem[%uk/%uk/%uk], Cycles[%u], Undone[%u], RW[%u/%u]\n", ptr->stats->in_bytes, ptr->stats->out_bytes, ptr->stats->commands, ptr->stats->operations, inmem, outmem, filemem, ptr->stats->cycles, ptr->stats->undone, ptr->stats->reads, ptr->stats->writes); ptr->stats->in_bytes = 0; ptr->stats->out_bytes = 0; ptr->stats->commands = 0; ptr->stats->operations = 0; ptr->stats->cycles = 0; ptr->stats->undone = 0; ptr->stats->reads = 0; ptr->stats->writes = 0; } } void timeout_init(timeout_t *ptr, struct event_base *base) { struct timeval t = {.tv_sec = 1, .tv_usec = 0}; assert(ptr != NULL); assert(ptr->clockevent.ev_base == NULL); evtimer_set(&ptr->clockevent, timeout_handler, (void *) ptr); event_base_set(ptr->clockevent.ev_base, &ptr->clockevent); evtimer_add(&ptr->clockevent, &t); assert(ptr->clockevent.ev_base != NULL); } //----------------------------------------------------------------------------- // Main... process command line parameters, and then setup our listening // sockets and event loop. int main(int argc, char **argv) { int c; settings_t *settings = NULL; server_t *server = NULL; timeout_t *timeout = NULL; stats_t *stats = NULL; risp_t *risp = NULL; // handle SIGINT signal(SIGINT, sig_handler); // init settings settings = (settings_t *) malloc(sizeof(settings_t)); assert(settings != NULL); settings_init(settings); // set stderr non-buffering (for running under, say, daemontools) setbuf(stderr, NULL); // process arguments /// Need to check the options in here, there're possibly ones that we dont need. while ((c = getopt(argc, argv, "p:k:c:hvd:u:P:l:s:")) != -1) { switch (c) { case 'p': settings->port = atoi(optarg); assert(settings->port > 0); break; case 'c': settings->maxconns = atoi(optarg); assert(settings->maxconns > 0); break; case 'h': usage(); exit(EXIT_SUCCESS); case 'v': settings->verbose++; break; case 'd': assert(settings->daemonize == false); settings->daemonize = true; break; case 's': assert(settings->storepath == NULL); settings->storepath = optarg; assert(settings->storepath != NULL); assert(settings->storepath[0] != '\0'); break; case 'u': assert(settings->username == NULL); settings->username = optarg; assert(settings->username != NULL); assert(settings->username[0] != '\0'); break; case 'P': assert(settings->pid_file == NULL); settings->pid_file = optarg; assert(settings->pid_file != NULL); assert(settings->pid_file[0] != '\0'); break; case 'l': assert(settings->interface == NULL); settings->interface = strdup(optarg); assert(settings->interface != NULL); assert(settings->interface[0] != '\0'); break; default: fprintf(stderr, "Illegal argument \"%c\"\n", c); return 1; } } if (settings->verbose) printf("Finished processing command-line args\n"); // If needed, increase rlimits to allow as many connections as needed. if (settings->verbose) printf("Settings Max connections: %d\n", settings->maxconns); assert(settings->maxconns > 0); set_maxconns(settings->maxconns); // if we are supplied with a username, drop privs to it. This will only // work if we are running as root, and is really only needed when running as // a daemon. if (settings->username != NULL) { if (settings->verbose) printf("Dropping privs and changing username: '******'\n", settings->username); if (drop_privs(settings->username) != 0) { usage(); exit(EXIT_FAILURE); } } // daemonize if requested // if we want to ensure our ability to dump core, don't chdir to / if (settings->daemonize) { int res; if (settings->verbose) printf("Daemonising\n"); res = daemon(0, settings->verbose); if (res == -1) { fprintf(stderr, "failed to daemon() in order to daemonize\n"); exit(EXIT_FAILURE); } } // initialize main thread libevent instance if (settings->verbose) printf("Initialising the event system.\n"); main_event_base = event_init(); if (settings->verbose) printf("Ignoring SIGPIPE interrupts\n"); ignore_sigpipe(); // save the PID in if we're a daemon, do this after thread_init due to a // file descriptor handling bug somewhere in libevent if (settings->daemonize && settings->pid_file) { if (settings->verbose) printf("Saving Pid file: %s\n", settings->pid_file); save_pid(getpid(), settings->pid_file); } // create and init the 'server' structure. if (settings->verbose) printf("Starting server listener on port %d.\n", settings->port); server = server_new(settings->port, settings->maxconns, settings->interface); if (server == NULL) { fprintf(stderr, "Failed to listen on port %d\n", settings->port); exit(EXIT_FAILURE); } assert(server != NULL); server->verbose = settings->verbose; server->storepath = settings->storepath; // add the server to the event base assert(main_event_base != NULL); server_add_event(server, main_event_base); // initialise clock event. The clock event is used to keep up our node // network. If we dont have enough connections, we will need to make some // requests. // create the timeout structure, and the timeout event. This is used to // perform certain things spread over time. Such as indexing the // 'complete' paths that we have, and ensuring that the 'chunks' parts are // valid. if (settings->verbose) printf("Setting up Timeout event.\n"); timeout = (timeout_t *) malloc(sizeof(timeout_t)); assert(timeout != NULL); assert(main_event_base != NULL); if (settings->verbose) printf("Initialising timeout.\n"); timeout_init(timeout, main_event_base); timeout->server = server; stats = (stats_t *) malloc(sizeof(stats_t)); stats->out_bytes = 0; stats->in_bytes = 0; stats->commands = 0; stats->operations = 0; server->stats = stats; timeout->stats = stats; // Initialise the risp system. risp = risp_init(); assert(risp != NULL); risp_add_invalid(risp, cmdInvalid); risp_add_command(risp, CMD_CLEAR, &cmdClear); risp_add_command(risp, CMD_EXECUTE, &cmdExecute); risp_add_command(risp, CMD_LIST, &cmdList); risp_add_command(risp, CMD_LISTING, &cmdListing); risp_add_command(risp, CMD_LISTING_DONE, &cmdListingDone); risp_add_command(risp, CMD_PUT, &cmdPut); risp_add_command(risp, CMD_GET, &cmdGet); risp_add_command(risp, CMD_SIZE, &cmdSize); risp_add_command(risp, CMD_OFFSET, &cmdOffset); risp_add_command(risp, CMD_FILE, &cmdFile); risp_add_command(risp, CMD_DATA, &cmdData); assert(server->risp == NULL); server->risp = risp; // enter the event loop. if (settings->verbose) printf("Starting Event Loop\n\n"); event_base_loop(main_event_base, 0); // cleanup risp library. risp_shutdown(risp); risp = NULL; // cleanup 'server', which should cleanup all the 'nodes' if (settings->verbose) printf("\n\nExiting.\n"); // remove the PID file if we're a daemon if (settings->daemonize && settings->pid_file != NULL) { if (settings->verbose) printf("Removing pid file: %s\n", settings->pid_file); remove_pidfile(settings->pid_file); } assert(settings != NULL); settings_cleanup(settings); settings = NULL; return 0; }