static void test_client_new(CuTest *tc) { const char *err = "client.c client_new FAIL"; client_t *c1, *c2; int max = STATIC_ALLOC_CLIENTS; /* For testing, use 10 is plenty */ int middle = max / 2; int i; if (STATIC_ALLOC_CLIENTS % 2 == 1) { CuFail(tc, "client.c client_new FAIL -- " "rerun with even number of clients allocated"); } for (i = 0; i < max; ++i) { c1 = client_new(); if (i == middle - 1) { //printf("Freeing client %d\n", i); client_free(c1); c1 = NULL; } } c1 = client_new(); client_free(c1); c2 = client_new(); CuAssertPtrEquals_Msg(tc, err, c1, c2); c1 = client_new(); CuAssertPtrEquals_Msg(tc, err, NULL, c1); #if UNIT_TESTING_VERBOSITY_LEVEL >= 1 printf("client.c client_new PASS\n"); #endif }
int main(int argc, char **argv) { gchar *c; int opt, i; gtk_init(&argc, &argv); grab_environment_configuration(); while ((opt = getopt(argc, argv, "e:CT")) != -1) { switch (opt) { case 'e': embed = atol(optarg); tabbed_automagic = FALSE; break; case 'C': cooperative_instances = FALSE; break; case 'T': tabbed_automagic = FALSE; break; default: fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n"); exit(EXIT_FAILURE); } } keywords_load(); if (cooperative_instances) cooperation_setup(); downloadmanager_setup(); if (tabbed_automagic && !(cooperative_instances && !cooperative_alone)) embed = tabbed_launch(); if (!cooperative_instances || cooperative_alone) { c = g_build_filename(g_get_user_data_dir(), __NAME__, "web_extensions", NULL); webkit_web_context_set_web_extensions_directory( webkit_web_context_get_default(), c ); } if (optind >= argc) client_new(home_uri); else { for (i = optind; i < argc; i++) client_new(argv[i]); } if (!cooperative_instances || cooperative_alone) gtk_main(); exit(EXIT_SUCCESS); }
/** * The primary loop and logic. Listen for packets and process them accordingly. */ void run (void) { printf("Server running normally...\n"); ENetEvent *ev = NULL; client *cli = NULL; u64 nullpacks = 0; connected = 1; do { ev = host_listen(500); if (!ev) { nullpacks++; } else if (ev->type == ENET_EVENT_TYPE_CONNECT) { ev->peer->data = client_new(); cli = ev->peer->data; cli->peer = ev->peer; fprintf(stderr, "Client connected.\n"); } else if (ev->type == ENET_EVENT_TYPE_RECEIVE) { fprintf(stderr, "Packet received.\n"); handle_event(ev); enet_packet_destroy(ev->packet); } else if (ev->type == ENET_EVENT_TYPE_DISCONNECT) { cli = ev->peer->data; host_list(cli->channel); client_destroy(cli); fprintf(stderr, "Client left.\n"); } else { fprintf(stderr, "Unrecognized event.\n"); } } while (connected); }
static void tcp_accept_handler(event_loop el, int fd, int mask, void *data) { char cip[128]; int cport, cfd; client c; NOT_USED(el); NOT_USED(mask); NOT_USED(data); if ((cfd = net_tcp_accept(fd, cip, &cport, neterr, sizeof neterr)) == -1) { xcb_log(XCB_LOG_WARNING, "Accepting client connection: %s", neterr); return; } if ((c = client_new(cfd, fd)) == NULL) { xcb_log(XCB_LOG_WARNING, "Error registering fd '%d' event for the new client: %s", cfd, strerror(errno)); close(cfd); } else { /* heartbeat */ dstr res = dstr_new("HEARTBEAT|"); dstr ip = getipv4(); xcb_log(XCB_LOG_NOTICE, "Accepted %s:%d, client '%p'", cip, cport, c); res = dstr_cat(res, ip); res = dstr_cat(res, "\r\n"); pthread_spin_lock(&c->lock); if (net_try_write(c->fd, res, dstr_length(res), 100, NET_NONBLOCK) == -1) xcb_log(XCB_LOG_WARNING, "Writing to client '%p': %s", c, strerror(errno)); pthread_spin_unlock(&c->lock); dstr_free(ip); dstr_free(res); } }
int main(int argc, char** argv) { sipua_t* sipua = NULL; sipua_uas_t* uas = NULL; module_catalog_t *mod_cata = NULL; /* phonebook loading test { sipua_load_user("heming", "heming", "hello", 5); exit(0); } */ clie_log (("main: modules in dir:'%s'\n", MOD_DIR)); mod_cata = catalog_new( "mediaformat" ); catalog_scan_modules ( mod_cata, OGMP_VERSION, MOD_DIR ); uas = client_new_uas(mod_cata, "eXosipua"); if(!uas) clie_log (("main: fail to create sipua server!\n")); if(uas && uas->init(uas, 5070, "IN", "IP4", NULL, NULL) >= UA_OK) { sipua = client_new("cursesui", uas, mod_cata, 64*1024); if(sipua) client_start(sipua); else clie_log (("main: fail to create sipua!\n")); } return 0; }
static void client_thread (void *args, zctx_t *ctx, void *pipe) { client_t *self = client_new (ctx, pipe); while (!self->stopped) { // Build structure each time since self->dealer can change zmq_pollitem_t items [] = { { self->pipe, 0, ZMQ_POLLIN, 0 }, { self->dealer, 0, ZMQ_POLLIN, 0 } }; int poll_size = self->dealer? 2: 1; if (zmq_poll (items, poll_size, self->heartbeat * ZMQ_POLL_MSEC) == -1) break; // Context has been shut down // Process incoming messages; either of these can // throw events into the state machine if (items [0].revents & ZMQ_POLLIN) control_message (self); if (items [1].revents & ZMQ_POLLIN) server_message (self); // Check whether server seems dead if (self->expires_at && zclock_time () >= self->expires_at) client_restart (self, NULL); } client_destroy (&self); }
Worker *worker_new(uint8_t id, Config *config, uint16_t num_clients, uint64_t num_requests) { Worker *worker; uint16_t i; worker = W_MALLOC(Worker, 1); worker->id = id; worker->loop = ev_loop_new(config->libev_flags); ev_ref(worker->loop); worker->config = config; worker->num_clients = num_clients; worker->stats.req_todo = num_requests; worker->progress_interval = num_requests / 10; if (worker->progress_interval == 0) worker->progress_interval = 1; worker->clients = W_MALLOC(Client*, num_clients); for (i = 0; i < num_clients; i++) { if (NULL == (worker->clients[i] = client_new(worker))) return NULL; } return worker; }
// This callback is called when data is readable on the unix socket. static void server_cb(EV_P_ ev_io *w, int revents) { puts("unix stream socket has become readable"); int client_fd; struct sock_ev_client* client; // since ev_io is the first member, // watcher `w` has the address of the // start of the sock_ev_serv struct struct sock_ev_serv* server = (struct sock_ev_serv*) w; while (1) { client_fd = accept(server->fd, NULL, NULL); if( client_fd == -1 ) { if( errno != EAGAIN && errno != EWOULDBLOCK ) { g_warning("accept() failed errno=%i (%s)", errno, strerror(errno)); exit(EXIT_FAILURE); } break; } puts("accepted a client"); client = client_new(client_fd); client->server = server; client->index = array_push(&server->clients, client); ev_io_start(EV_A_ &client->io); } }
static void on_client_accepted(int fd, const struct sockaddr *peer) { db_init(); client = client_new(); memset(request_buffer, '\0', REQUEST_BUFFER_SIZE); rbuf = request_buffer; rbufsize = REQUEST_BUFFER_SIZE; }
/* * hi_talk_cli_open * * @describe 连接设备 * @date 2013-4-28 */ hi_talk_cli_t *hi_talk_cli_open(char *ip , unsigned short port , void *ctx, media_info_t *mi) { talk_client_t *client = NULL; client = client_new(ip, port, mi, ctx, __get_talk_ops(), (loop_t *)get_best_loop2((sched_t *)__get_main_sched())); return client; }
static Client* client_instance() { static Client* the_client = 0; if (!the_client) { the_client = client_new(); } return the_client; }
gboolean remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data) { gchar *uri = NULL; g_io_channel_read_line(channel, &uri, NULL, NULL, NULL); if (uri) { g_strstrip(uri); client_new(uri); g_free(uri); } return TRUE; }
static void server_work(AVAHI_GCC_UNUSED AvahiWatch *watch, int fd, AvahiWatchEvent events, void *userdata) { Server *s = userdata; assert(s); if (events & AVAHI_WATCH_IN) { int cfd; if ((cfd = accept(fd, NULL, NULL)) < 0) avahi_log_error("accept(): %s", strerror(errno)); else client_new(s, cfd); } }
void connection_accept(uv_stream_t *handle) { Client *newClient; uv_tcp_t *newHandle; NetworkAddress address = { 0 }; Listener *listener; if(handle == NULL) { return; } listener = handle->data; newHandle = Malloc(sizeof(uv_tcp_t)); uv_tcp_init(serverstate_get_event_loop(), newHandle); if(uv_accept(handle, (uv_stream_t *)newHandle) != 0) { Free(handle); return; } if(!network_address_from_stream(newHandle, &address)) { uv_close((uv_handle_t *)handle, NULL); Free(handle); return; } newClient = client_new(); newHandle->data = newClient; newClient->handle = newHandle; memcpy(&newClient->Address, &address, sizeof(NetworkAddress)); if(listener->IsTls) { if(!connection_tls_handshake(newClient)) { client_free(newClient); return; } } client_lookup_dns(newClient); }
/* For standalone sipua */ int main(int argc, char** argv) { sipua_t* sipua = NULL; sipua_uas_t* uas = NULL; module_catalog_t *mod_cata = NULL; char *realm = NULL; int sip_port; if(argc == 1) { sip_port = 5060; } else if(argc == 2) { sip_port = strtol(argv[1], NULL, 10); } else if(argc == 3) { sip_port = strtol(argv[1], NULL, 10); realm = argv[2]; } printf("main: sip port is %d\n", sip_port); printf("main: modules in dir:'%s'\n", OGMP_MODULEDIR); mod_cata = catalog_new( "mediaformat" ); catalog_scan_modules (mod_cata, OGMP_VERSION, OGMP_MODULEDIR); uas = client_new_uas(mod_cata, "eXosipua"); if(!uas) printf("main: fail to create sipua server!\n"); if(uas && uas->init(uas, sip_port, "IN", "IP4", NULL, NULL) >= UA_OK) { sipua = client_new("cursesui", uas, realm, mod_cata, 64*1024); if(sipua) client_start(sipua); else printf("main: fail to create sipua!\n"); } return 0; }
/* ================ run_client() ================ */ int run_client(const char *endpoint, int op_code, int total_threads, uint32_t total_files, const char *key, const char *filename, int verbose) { info_log("run_client() with op_code:%d endpoint:%s threads:%d count:%d key:%s filename:%s", op_code, endpoint, total_threads, total_files, key, filename); if ( prepare_file_data(filename) != 0 ){ return -1; } total_actors = total_threads; client_t **clients = (client_t**)malloc(sizeof(client_t*) * total_actors); for ( int i = 0 ; i < total_actors ; i++ ){ client_t *client = client_new(i, endpoint); client->op_code = op_code; client->total_threads = total_threads; client->total_files = total_files; client->key = key; client->filename = filename; client->file_data = file_data; client->file_size = file_size; client_create_actor(client); clients[i] = client; } zloop_t *loop = zloop_new(); zloop_set_verbose(loop, verbose); for ( int i = 0 ; i < total_actors ; i++ ){ zactor_t *actor = clients[i]->actor; zloop_reader(loop, (zsock_t*)zactor_resolve(actor), handle_pullin_on_client_pipe, clients[i]); } zloop_start(loop); zloop_destroy(&loop); for ( int i = 0 ; i < total_actors ; i++ ){ client_free(clients[i]); } return 0; }
void server_start(struct server *s) { if (s == NULL) { return; } int client_sock, client_len; struct sockaddr_in client_addr; int pid; /* Now start listening for the clients, here * process will go in sleep mode and will wait * for the incoming connection */ listen(s->sock, 5); client_len = sizeof(client_addr); while (1) { client_sock = accept(s->sock, (struct sockaddr *) &client_addr, &client_len); if (client_sock < 0) { perror("ERROR on accept"); exit(1); } /* Create child process */ pid = fork(); if (pid < 0) { perror("ERROR on fork"); exit(1); } if (pid == 0) { /* This is the client process */ close(s->sock); struct client *c = client_new(client_sock); if (s->on_client != NULL) { (*s->on_client)(c); } client_work(c); exit(0); } else { close(client_sock); } } }
static void server_client_message (server_t *self) { fmq_msg_t *request = fmq_msg_recv (self->router); if (!request) return; // Interrupted; do nothing char *hashkey = zframe_strhex (fmq_msg_address (request)); client_t *client = zhash_lookup (self->clients, hashkey); if (client == NULL) { client = client_new (fmq_msg_address (request)); client->heartbeat = self->heartbeat; client->router = self->router; zhash_insert (self->clients, hashkey, client); zhash_freefn (self->clients, hashkey, client_free); } free (hashkey); if (client->request) fmq_msg_destroy (&client->request); client->request = request; // Any input from client counts as heartbeat client->heartbeat_at = zclock_time () + client->heartbeat; // Any input from client counts as activity client->expires_at = zclock_time () + client->heartbeat * 3; if (fmq_msg_id (request) == FMQ_MSG_OHAI) server_client_execute (self, client, ohai_event); else if (fmq_msg_id (request) == FMQ_MSG_YARLY) server_client_execute (self, client, yarly_event); else if (fmq_msg_id (request) == FMQ_MSG_ICANHAZ) server_client_execute (self, client, icanhaz_event); else if (fmq_msg_id (request) == FMQ_MSG_NOM) server_client_execute (self, client, nom_event); else if (fmq_msg_id (request) == FMQ_MSG_HUGZ) server_client_execute (self, client, hugz_event); else if (fmq_msg_id (request) == FMQ_MSG_KTHXBAI) server_client_execute (self, client, kthxbai_event); }
// Accept a connection. Create the client object, and then attach the socket handle to it. static void accept_conn_cb( struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *address, int socklen, void *ctx) { client_t *client; assert(listener); assert(fd > 0); assert(address && socklen > 0); assert(ctx == NULL); // create client object. // TODO: We should be pulling these client objects out of a mempool. client = client_new(); client_accept(client, fd, address, socklen); _conncount ++; }
static void event_maprequest(XEvent *e) { XMapRequestEvent *ev = &e->xmaprequest; XWindowAttributes at; struct _systray *s; /* Which windows to manage */ if(!XGetWindowAttributes(EVDPY(e), ev->window, &at) || at.override_redirect) return; if(!client_gb_win(ev->window)) client_new(ev->window, &at, false); else if((s = systray_find(ev->window))) { ewmh_send_message(s->win, s->win, "_XEMBED", CurrentTime, XEMBED_WINDOW_ACTIVATE, 0, 0, 0); systray_update(); } }
void read_client(char *file, llist *client_list) { FILE *fp; char client_name[MAX_NAME_SIZE]; int client_id; client *client; if ((fp = fopen(file, "r")) == NULL) { return; } while (fscanf(fp, "%[^,], %d\n", client_name, &client_id) == 2) { client = client_new(client_name); client->id = client_id; llist_insert(client_list, client); } fclose(fp); }
/* Accept client requests */ void accept_cb(struct ev_loop *loop, struct ev_io *watcher, int revents) { struct sockaddr_in client_addr; struct ev_io *w_client; client_t *client; socklen_t client_len = sizeof (client_addr); int client_sd; assert(loop); /* loop must not be a NULL pointer */ assert(watcher); /* watcher must not be a NULL pointer */ if (EV_ERROR & revents) { perror("got invalid event"); return; } /* Accept client request */ client_sd = accept(watcher->fd, (struct sockaddr *) & client_addr, &client_len); if (client_sd < 0) { perror("accept error"); return; } /* Set the client socket fd to non-blocking mode */ setnonblock(client_sd); printf("Successfully connected with client.\n"); /* Initialize and start watcher to read client requests */ client = client_new(); client->in_buffer.fd = client_sd; client->out_buffer.fd = client_sd; w_client = ev_watcher_new(); w_client->attachment = client; ev_io_init(w_client, &read_cb, client_sd, EV_READ); ev_io_start(loop, w_client); }
gpointer connectionHandler(gpointer connection) { if (!isAthorized(connection)) { connection_close(connection); free(connection); return NULL; } gint shell_stdin; gint shell_stdout; gint shell_stderr; #ifdef __WIN32__ gchar* argv[] = {"cmd.exe", NULL}; #elif __UNIX__ gchar* argv[] = {"zsh", NULL}; #endif GError* error = NULL; gboolean success = g_spawn_async_with_pipes(".", argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, &shell_stdin, &shell_stdout, &shell_stderr, &error); if (!success) { g_error(error->message); return NULL; } Client* client = client_new(shell_stdin, shell_stdout, shell_stderr, connection); client->isShellActive = TRUE; GThread* readingThread = g_thread_new(NULL, (GThreadFunc) client_reading_loop, client); GThread* writingOutThread = g_thread_new(NULL, (GThreadFunc) client_writing_shell_out_loop, client); GThread* writingErrThread = g_thread_new(NULL, (GThreadFunc) client_writing_shell_err_loop, client); g_print("threads started\n"); g_thread_join(readingThread); g_thread_join(writingOutThread); g_thread_join(writingErrThread); g_thread_unref(readingThread); g_thread_unref(writingOutThread); g_thread_unref(writingErrThread); g_print("Client disconnected\n"); client_free(client); return NULL; }
int main (int argc, char *argv[]){ Client *client; char s[MAXLINE]; if (argc < 2){ fprintf(stderr, "Please provide an address to connect to.\n"); return(EXIT_FAILURE); } client = client_new(); //connect the client to the server if(client_connect(client, argv[1]) == SOCKET_CONNECT_ERROR){ fprintf(stdout, "Cannot connect to the server\n"); } //create the listening thread of the client pthread_t t1; int iret1 = pthread_create(&t1, NULL, listen_thread, (void *) client); //sending loop while(true){ while(fgets(s, MAXLINE, stdin) != NULL){ fprintf(stdout, "Sending: %s to the client.\n", s); char *c; if ((c = strchr(s, '\n')) != NULL) *c = '\0'; if(client_send(client, s) == MSG_SENT){ fprintf(stdout, "Message sent to the server.\n"); } } } return(EXIT_SUCCESS); }
/**************************************************************************** * This function gets called when a connection is made to a listening socket ****************************************************************************/ void listener_cb(int fd, short events, void *arg) { struct sockaddr_in sin; socklen_t addrlen = sizeof(sin); int s = accept(fd, (struct sockaddr *)&sin, &addrlen); fcntl(s, F_SETFL, O_NONBLOCK); Client *cli = client_new(); cli->state = CLIENT_STATE_CONNECTED; cli->fd = s; cli->port = ntohs(sin.sin_port); *(uint32_t*)cli->ip = sin.sin_addr.s_addr; sprintf(cli->id, "%d.%d.%d.%d:%d", cli->ip[0], cli->ip[1], cli->ip[2], cli->ip[3], cli->port); g_ptr_array_add(g_clients, cli); event_set(&cli->evt, s, EV_READ|EV_PERSIST, client_cb, cli); event_add(&cli->evt, NULL); }
static void agent_client_message (agent_t *self) { zmsg_t *msg = zmsg_recv (self->router); if (!msg) return; // Interrupted; do nothing puts ("Received message from client"); zmsg_dump (msg); // Frame 0 is address client that sent message zframe_t *address = zmsg_pop (msg); char *hashkey = zframe_strhex (address); client_t *client = zhash_lookup (self->clients, hashkey); if (client == NULL) { client = client_new (self->router, hashkey, address); zhash_insert (self->clients, hashkey, client); zhash_freefn (self->clients, hashkey, client_free); } else { free (hashkey); zframe_destroy (&address); } // Frame 1 is the command char *command = zmsg_popstr (msg); client_set_request (client, msg); if (command) { if (streq (command, "OHAI")) client_execute (client, ohai_event); else if (streq (command, "ICANHAZ")) client_execute (client, icanhaz_event); else if (streq (command, "HUGZ")) client_execute (client, hugz_event); free (command); } }
/** * \brief Called when a node connects via TCP * \param * \return */ void on_connect (Socket* client_sock, void* handle) { (void)handle; // This parameter is unused MString *mstr = mstring_create (); mstring_sprintf (mstr,"%s.%d", resultfile_name, session->client_count); logdebug("New client (index %d) connected\n", session->client_count); session->client_count++; Client* client = client_new(client_sock, page_size, mstring_buf (mstr), downstream_port, downstream_address); mstring_delete (mstr); session_add_client (session, client); client->session = session; client->recv_event = eventloop_on_read_in_channel(client_sock, client_callback, status_callback, (void*)client); pthread_create (&client->thread, NULL, client_send_thread, (void*)client); }
// Finally here's the client thread itself, which polls its two // sockets and processes incoming messages static void client_thread (void *args, zctx_t *ctx, void *pipe) { client_t *self = client_new (ctx, pipe); int pollset_size = 1; zmq_pollitem_t pollset [MAX_SERVERS] = { { self->pipe, 0, ZMQ_POLLIN, 0 } }; while (!self->stopped && !zctx_interrupted) { // Rebuild pollset if we need to int server_nbr; if (self->dirty) { for (server_nbr = 0; server_nbr < self->nbr_servers; server_nbr++) { pollset [1 + server_nbr].socket = self->servers [server_nbr]->dealer; pollset [1 + server_nbr].events = ZMQ_POLLIN; } pollset_size = 1 + self->nbr_servers; } if (zmq_poll (pollset, pollset_size, self->heartbeat * ZMQ_POLL_MSEC) == -1) break; // Context has been shut down // Process incoming messages; either of these can // throw events into the state machine if (pollset [0].revents & ZMQ_POLLIN) client_control_message (self); // Here, array of sockets to servers for (server_nbr = 0; server_nbr < self->nbr_servers; server_nbr++) { if (pollset [1 + server_nbr].revents & ZMQ_POLLIN) { server_t *server = self->servers [server_nbr]; client_server_message (self, server); } } } client_destroy (&self); }
static int s_agent_handle_router (agent_t *self) { zframe_t *address = zframe_recv (self->router); char *hashkey = zframe_strhex (address); client_t *client = (client_t *) zhash_lookup (self->clients, hashkey); if (client == NULL && self->nbr_pending < self->max_pending) { client = client_new (self, address); client_set_pending (client); curve_codec_set_verbose (client->codec, self->verbose); zhash_foreach (self->metadata, client_set_metadata, client); zhash_insert (self->clients, hashkey, client); zhash_freefn (self->clients, hashkey, client_free); } free (hashkey); zframe_destroy (&address); // If we're overloaded, discard client request without any further // ado. The client will have to detect this and retry later. // TODO: retry in client side to handle overloaded servers. if (client == NULL) return 0; // If not yet connected, process one command frame // We always read one request, and send one reply if (client->state == pending) { zframe_t *input = zframe_recv (self->router); zframe_t *output = curve_codec_execute (client->codec, &input); if (output) { zframe_send (&client->address, self->router, ZFRAME_MORE + ZFRAME_REUSE); zframe_send (&output, self->router, 0); if (curve_codec_connected (client->codec)) client_set_connected (client); } else client_set_exception (client); } else // If connected, process one message frame // We will queue message frames in the client until we get a // whole message ready to deliver up the data socket -- frames // from different clients will be randomly intermixed. if (client->state == connected) { zframe_t *encrypted = zframe_recv (self->router); zframe_t *cleartext = curve_codec_decode (client->codec, &encrypted); if (cleartext) { if (client->incoming == NULL) client->incoming = zmsg_new (); zmsg_add (client->incoming, cleartext); if (!zframe_more (cleartext)) { zmsg_pushstr (client->incoming, client->hashkey); zmsg_send (&client->incoming, self->data); } } else client_set_exception (client); } // If client is misbehaving, remove it if (client->state == exception) zhash_delete (self->clients, client->hashkey); return 0; }
/** * @brief Create a client structure for a service and add it to the global service list * * @param key Unique key for this client * @param clientName Name of the application */ static void client_new_service(const char *key, const char *clientName) { ShutdownClient *client = client_new(key, clientName); g_hash_table_replace(sClientList->services, client->id, client); }