void zauth (zsock_t *pipe, void *unused) { self_t *self = s_self_new (pipe); if (!self) return; // Signal successful initialization zsock_signal (pipe, 0); while (!self->terminated) { zsock_t *which = (zsock_t *) zpoller_wait (self->poller, -1); if (which == self->pipe) s_self_handle_pipe (self); else if (which == self->handler) s_self_authenticate (self); else if (zpoller_terminated (self->poller)) break; // Interrupted } s_self_destroy (&self); }
void zbeacon (zsock_t *pipe, void *args) { self_t *self = s_self_new (pipe); assert (self); // Signal successful initialization zsock_signal (pipe, 0); while (!self->terminated) { // Poll on API pipe and on UDP socket zmq_pollitem_t pollitems [] = { { zsock_resolve (self->pipe), 0, ZMQ_POLLIN, 0 }, { NULL, self->udpsock, ZMQ_POLLIN, 0 } }; long timeout = -1; if (self->transmit) { timeout = (long) (self->ping_at - zclock_mono ()); if (timeout < 0) timeout = 0; } if (zmq_poll (pollitems, self->udpsock ? 2 : 1, timeout * ZMQ_POLL_MSEC) == -1) break; // Interrupted if (pollitems [0].revents & ZMQ_POLLIN) s_self_handle_pipe (self); if (pollitems [1].revents & ZMQ_POLLIN) s_self_handle_udp (self); if ( self->transmit && zclock_mono () >= self->ping_at) { // Send beacon to any listening peers zsys_udp_send (self->udpsock, self->transmit, &self->broadcast); self->ping_at = zclock_mono () + self->interval; } } s_self_destroy (&self); }
void zproxy (zsock_t *pipe, void *unused) { self_t *self = s_self_new (pipe); assert (self); // Signal successful initialization zsock_signal (pipe, 0); while (!self->terminated) { zsock_t *which = (zsock_t *) zpoller_wait (self->poller, -1); if (zpoller_terminated (self->poller)) break; // Interrupted else if (which == self->pipe) s_self_handle_pipe (self); else if (which == self->frontend) s_self_switch (self, self->frontend, self->backend); else if (which == self->backend) s_self_switch (self, self->backend, self->frontend); } s_self_destroy (&self); }
void zsock_test (bool verbose) { printf (" * zsock: "); // @selftest zsock_t *writer = zsock_new_push ("@tcp://127.0.0.1:5560"); assert (writer); assert (zsock_resolve (writer) != writer); assert (streq (zsock_type_str (writer), "PUSH")); int rc; #if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (3,2,0)) // Check unbind rc = zsock_unbind (writer, "tcp://127.0.0.1:%d", 5560); assert (rc == 0); // In some cases and especially when running under Valgrind, doing // a bind immediately after an unbind causes an EADDRINUSE error. // Even a short sleep allows the OS to release the port for reuse. zclock_sleep (100); // Bind again rc = zsock_bind (writer, "tcp://127.0.0.1:%d", 5560); assert (rc == 5560); assert (streq (zsock_endpoint (writer), "tcp://127.0.0.1:5560")); #endif zsock_t *reader = zsock_new_pull (">tcp://127.0.0.1:5560"); assert (reader); assert (zsock_resolve (reader) != reader); assert (streq (zsock_type_str (reader), "PULL")); zstr_send (writer, "Hello, World"); zmsg_t *msg = zsock_recv (reader); assert (msg); char *string = zmsg_popstr (msg); assert (streq (string, "Hello, World")); free (string); zmsg_destroy (&msg); // Test binding to ephemeral ports, sequential and random int port = zsock_bind (writer, "tcp://127.0.0.1:*"); assert (port >= DYNAMIC_FIRST && port <= DYNAMIC_LAST); port = zsock_bind (writer, "tcp://127.0.0.1:*[50000-]"); assert (port >= 50000 && port <= DYNAMIC_LAST); port = zsock_bind (writer, "tcp://127.0.0.1:*[-50001]"); assert (port >= DYNAMIC_FIRST && port <= 50001); port = zsock_bind (writer, "tcp://127.0.0.1:*[60000-60010]"); assert (port >= 60000 && port <= 60010); port = zsock_bind (writer, "tcp://127.0.0.1:!"); assert (port >= DYNAMIC_FIRST && port <= DYNAMIC_LAST); port = zsock_bind (writer, "tcp://127.0.0.1:![50000-]"); assert (port >= 50000 && port <= DYNAMIC_LAST); port = zsock_bind (writer, "tcp://127.0.0.1:![-50001]"); assert (port >= DYNAMIC_FIRST && port <= 50001); port = zsock_bind (writer, "tcp://127.0.0.1:![60000-60010]"); assert (port >= 60000 && port <= 60010); // Test zsock_endpoint method rc = zsock_bind (writer, "inproc://test.%s", "writer"); assert (rc == 0); assert (streq (zsock_endpoint (writer), "inproc://test.writer")); // Test error state when connecting to an invalid socket type // ('txp://' instead of 'tcp://', typo intentional) rc = zsock_connect (reader, "txp://127.0.0.1:5560"); assert (rc == -1); rc = zsock_signal (writer, 123); assert (rc == 0); rc = zsock_wait (reader); assert (rc == 123); zsock_destroy (&reader); zsock_destroy (&writer); // Test zsock_attach method zsock_t *server = zsock_new (ZMQ_DEALER); rc = zsock_attach (server, "@inproc://myendpoint,tcp://127.0.0.1:5556,inproc://others", true); assert (rc == 0); rc = zsock_attach (server, "", false); assert (rc == 0); rc = zsock_attach (server, NULL, true); assert (rc == 0); rc = zsock_attach (server, ">a,@b, c,, ", false); assert (rc == -1); zsock_destroy (&server); // @end printf ("OK\n"); }
void zyre_node_actor (zsock_t *pipe, void *args) { // Create node instance to pass around zyre_node_t *self = zyre_node_new (pipe, args); if (!self) // Interrupted return; // Signal actor successfully initialized zsock_signal (self->pipe, 0); // Loop until the agent is terminated one way or another int64_t reap_at = zclock_mono () + REAP_INTERVAL; while (!self->terminated) { // Start beacon as soon as we can if (self->beacon && self->port <= 0) { // Our hostname is provided by zbeacon zsock_send(self->beacon, "si", "CONFIGURE", self->beacon_port); char *hostname = zstr_recv(self->beacon); // Is UDP broadcast interface available? if (!streq(hostname, "")) { if (zsys_ipv6()) self->port = zsock_bind(self->inbox, "tcp://%s%%%s:*", zsys_ipv6_address(), zsys_interface()); else self->port = zsock_bind(self->inbox, "tcp://%s:*", hostname); if (self->port > 0) { assert(!self->endpoint); // If caller set this, we'd be using gossip if (streq(zsys_interface(), "*")) { char *hostname = zsys_hostname(); self->endpoint = zsys_sprintf("tcp://%s:%d", hostname, self->port); zstr_free(&hostname); } else { self->endpoint = strdup(zsock_endpoint(self->inbox)); } // Set broadcast/listen beacon beacon_t beacon; beacon.protocol[0] = 'Z'; beacon.protocol[1] = 'R'; beacon.protocol[2] = 'E'; beacon.version = BEACON_VERSION; beacon.port = htons(self->port); zuuid_export(self->uuid, beacon.uuid); zsock_send(self->beacon, "sbi", "PUBLISH", (byte *)&beacon, sizeof(beacon_t), self->interval); zsock_send(self->beacon, "sb", "SUBSCRIBE", (byte *) "ZRE", 3); zpoller_add(self->poller, self->beacon); // Start polling on inbox zpoller_add(self->poller, self->inbox); } } zstr_free(&hostname); } int timeout = (int) (reap_at - zclock_mono ()); if (timeout > REAP_INTERVAL) timeout = REAP_INTERVAL; else if (timeout < 0) timeout = 0; zsock_t *which = (zsock_t *) zpoller_wait (self->poller, timeout); if (which == self->pipe) zyre_node_recv_api (self); else if (which == self->inbox) zyre_node_recv_peer (self); else if (self->beacon && (void *) which == self->beacon) zyre_node_recv_beacon (self); else if (self->gossip && (zactor_t *) which == self->gossip) zyre_node_recv_gossip (self); else if (zpoller_terminated (self->poller)) break; // Interrupted, check before expired else if (zpoller_expired (self->poller)) { if (zclock_mono () >= reap_at) { void *item; reap_at = zclock_mono () + REAP_INTERVAL; // Ping all peers and reap any expired ones for (item = zhash_first (self->peers); item != NULL; item = zhash_next (self->peers)) zyre_node_ping_peer (zhash_cursor (self->peers), item, self); } } } zyre_node_destroy (&self); }
static int s_self_handle_pipe (self_t *self) { // Get the whole message off the pipe in one go zmsg_t *request = zmsg_recv (self->pipe); if (!request) return -1; // Interrupted char *command = zmsg_popstr (request); assert (command); if (self->verbose) zsys_info ("zproxy: API command=%s", command); if (streq (command, "FRONTEND")) { s_self_configure (self, &self->frontend, request, "frontend"); zsock_signal (self->pipe, 0); } else if (streq (command, "BACKEND")) { s_self_configure (self, &self->backend, request, "backend"); zsock_signal (self->pipe, 0); } else if (streq (command, "CAPTURE")) { self->capture = zsock_new (ZMQ_PUSH); assert (self->capture); char *endpoint = zmsg_popstr (request); assert (endpoint); int rc = zsock_connect (self->capture, "%s", endpoint); assert (rc == 0); zstr_free (&endpoint); zsock_signal (self->pipe, 0); } else if (streq (command, "PAUSE")) { zpoller_destroy (&self->poller); self->poller = zpoller_new (self->pipe, NULL); assert (self->poller); zsock_signal (self->pipe, 0); } else if (streq (command, "RESUME")) { zpoller_destroy (&self->poller); self->poller = zpoller_new (self->pipe, self->frontend, self->backend, NULL); assert (self->poller); zsock_signal (self->pipe, 0); } else if (streq (command, "VERBOSE")) { self->verbose = true; zsock_signal (self->pipe, 0); } else if (streq (command, "$TERM")) self->terminated = true; else { zsys_error ("zproxy: - invalid command: %s", command); assert (false); } zstr_free (&command); zmsg_destroy (&request); return 0; }
/* ================ client_thread_main() ================ */ void client_thread_main(zsock_t *pipe, void *user_data) { client_t *client = (client_t*)user_data; int id = client->id; UNUSED const char *file_data = client->file_data; UNUSED uint32_t file_size = client->file_size; trace_log("Client %d Ready.", id); zsock_signal(pipe, 0); char sz_id[16]; sprintf(sz_id, "%d", id); message_send_status(pipe, MSG_STATUS_ACTOR_READY); zsock_t *sock_client = zsock_new_req(client->endpoint); if ( sock_client == NULL ){ error_log("Connect broker failed. Client %d", client->id); return; } uint32_t file_count = 0; while ( true ){ char key[NAME_MAX]; client_rebuild_data_key(client, file_count, key); int retries = 0; while ( retries++ < RETRIES ) { int rc = 0; if ( client->op_code == 1 ) { rc = upload_data(sock_client, key, file_data, file_size); } else if ( client->op_code == 2 ) { rc = download_data(sock_client, key); } else if ( client->op_code == 3 ) { rc = delete_data(sock_client, key); } if ( rc == -2 ) break; if ( rc == 0 ) break; notice_log("Retry %d/%d...", retries, RETRIES); zclock_sleep(1000); } /* ---------------- Check exit loop ---------------- */ file_count++; if ( file_count % 100 == 1 || file_count + 5 >= client->total_files ){ info_log("Client %d Send message %d/%d", client->id, file_count, client->total_files); } if ( file_count >= client->total_files ) break; } message_send_status(pipe, MSG_STATUS_ACTOR_OVER); zsock_destroy(&sock_client); trace_log("Client %d Exit.", id); }
static void zyre_node_recv_api (zyre_node_t *self) { // Get the whole message off the pipe in one go zmsg_t *request = zmsg_recv (self->pipe); if (!request) return; // Interrupted char *command = zmsg_popstr (request); if (streq (command, "UUID")) zstr_send (self->pipe, zuuid_str (self->uuid)); else if (streq (command, "NAME")) zstr_send (self->pipe, self->name); else if (streq (command, "SET NAME")) { free (self->name); self->name = zmsg_popstr (request); assert (self->name); } else if (streq (command, "SET HEADER")) { char *name = zmsg_popstr (request); char *value = zmsg_popstr (request); zhash_update (self->headers, name, value); zstr_free (&name); zstr_free (&value); } else if (streq (command, "SET VERBOSE")) self->verbose = true; else if (streq (command, "SET PORT")) { char *value = zmsg_popstr (request); self->beacon_port = atoi (value); zstr_free (&value); } else if (streq (command, "SET EVASIVE TIMEOUT")) { char *value = zmsg_popstr (request); self->evasive_timeout = atoi (value); zstr_free (&value); } else if (streq (command, "SET EXPIRED TIMEOUT")) { char *value = zmsg_popstr (request); self->expired_timeout = atoi (value); zstr_free (&value); } else if (streq (command, "SET INTERVAL")) { char *value = zmsg_popstr (request); self->interval = atol (value); zstr_free (&value); } else if (streq (command, "SET ENDPOINT")) { zyre_node_gossip_start (self); char *endpoint = zmsg_popstr (request); if (zsock_bind (self->inbox, "%s", endpoint) != -1) { zstr_free (&self->endpoint); self->endpoint = endpoint; zsock_signal (self->pipe, 0); } else { zstr_free (&endpoint); zsock_signal (self->pipe, 1); } } else if (streq (command, "GOSSIP BIND")) { zyre_node_gossip_start (self); zstr_free (&self->gossip_bind); self->gossip_bind = zmsg_popstr (request); zstr_sendx (self->gossip, "BIND", self->gossip_bind, NULL); } else if (streq (command, "GOSSIP CONNECT")) { zyre_node_gossip_start (self); zstr_free (&self->gossip_connect); self->gossip_connect = zmsg_popstr (request); zstr_sendx (self->gossip, "CONNECT", self->gossip_connect, NULL); } else if (streq (command, "START")) zsock_signal (self->pipe, zyre_node_start (self)); else if (streq (command, "STOP")) zsock_signal (self->pipe, zyre_node_stop (self)); else if (streq (command, "WHISPER")) { // Get peer to send message to char *identity = zmsg_popstr (request); zyre_peer_t *peer = (zyre_peer_t *) zhash_lookup (self->peers, identity); // Send frame on out to peer's mailbox, drop message // if peer doesn't exist (may have been destroyed) if (peer) { zre_msg_t *msg = zre_msg_new (ZRE_MSG_WHISPER); zre_msg_set_content (msg, &request); zyre_peer_send (peer, &msg); } zstr_free (&identity); } else if (streq (command, "SHOUT")) { // Get group to send message to char *name = zmsg_popstr (request); zyre_group_t *group = (zyre_group_t *) zhash_lookup (self->peer_groups, name); if (group) { zre_msg_t *msg = zre_msg_new (ZRE_MSG_SHOUT); zre_msg_set_group (msg, name); zre_msg_set_content (msg, &request); zyre_group_send (group, &msg); } zstr_free (&name); } else if (streq (command, "JOIN")) { char *name = zmsg_popstr (request); if (!zlist_exists (self->own_groups, name)) { void *item; // Only send if we're not already in group zlist_append (self->own_groups, name); zre_msg_t *msg = zre_msg_new (ZRE_MSG_JOIN); zre_msg_set_group (msg, name); // Update status before sending command zre_msg_set_status (msg, ++(self->status)); for (item = zhash_first (self->peers); item != NULL; item = zhash_next (self->peers)) zyre_node_send_peer (zhash_cursor (self->peers), item, msg); zre_msg_destroy (&msg); if (self->verbose) zsys_info ("(%s) JOIN group=%s", self->name, name); } zstr_free (&name); } else if (streq (command, "LEAVE")) { char *name = zmsg_popstr (request); if (zlist_exists (self->own_groups, name)) { void *item; // Only send if we are actually in group zre_msg_t *msg = zre_msg_new (ZRE_MSG_LEAVE); zre_msg_set_group (msg, name); // Update status before sending command zre_msg_set_status (msg, ++(self->status)); for (item = zhash_first (self->peers); item != NULL; item = zhash_next (self->peers)) zyre_node_send_peer (zhash_cursor (self->peers), item, msg); zre_msg_destroy (&msg); zlist_remove (self->own_groups, name); if (self->verbose) zsys_info ("(%s) LEAVE group=%s", self->name, name); } zstr_free (&name); } else if (streq (command, "PEERS")) zsock_send (self->pipe, "p", zhash_keys (self->peers)); else if (streq (command, "GROUP PEERS")) { char *name = zmsg_popstr (request); zyre_group_t *group = (zyre_group_t *) zhash_lookup (self->peer_groups, name); if (group) zsock_send (self->pipe, "p", zyre_group_peers (group)); else zsock_send (self->pipe, "p", NULL); zstr_free (&name); } else if (streq (command, "PEER ENDPOINT")) { char *uuid = zmsg_popstr (request); zyre_peer_t *peer = (zyre_peer_t *) zhash_lookup (self->peers, uuid); assert (peer); zsock_send (self->pipe, "s", zyre_peer_endpoint (peer)); zstr_free (&uuid); } else if (streq (command, "PEER NAME")) { char *uuid = zmsg_popstr (request); zyre_peer_t *peer = (zyre_peer_t *) zhash_lookup (self->peers, uuid); assert (peer); zsock_send (self->pipe, "s", zyre_peer_name (peer)); zstr_free (&uuid); } else if (streq (command, "PEER HEADER")) { char *uuid = zmsg_popstr (request); char *key = zmsg_popstr (request); zyre_peer_t *peer = (zyre_peer_t *) zhash_lookup (self->peers, uuid); if (!peer) zstr_send (self->pipe, ""); else zstr_send (self->pipe, zyre_peer_header (peer, key, NULL)); zstr_free (&uuid); zstr_free (&key); } else if (streq (command, "PEER GROUPS")) zsock_send (self->pipe, "p", zhash_keys (self->peer_groups)); else if (streq (command, "OWN GROUPS")) zsock_send (self->pipe, "p", zlist_dup (self->own_groups)); else if (streq (command, "DUMP")) zyre_node_dump (self); else if (streq (command, "$TERM")) self->terminated = true; else { zsys_error ("invalid command '%s'", command); assert (false); } zstr_free (&command); zmsg_destroy (&request); }
static void ipc_actor (zsock_t *pipe, void *args) { // Do some initialization char* name = (char*) args; node = zyre_new (name); assert(node); if (!node) // Could not create new node { sim_printf("Couldn't create IPC node ... %s\n", name); return; } ipc_printf("Starting IPC node %s ...", name); if (ipc_verbose) zyre_set_verbose (node); // uncomment to watch the events zyre_start (node); zyre_join (node, fnpGroup); zsock_signal (pipe, 0); // Signal "ready" to caller terminated = false; poller = zpoller_new (pipe, zyre_socket (node), NULL); assert(poller); ipc_printf(" done\n"); while (!terminated) { void *which = zpoller_wait (poller, -1); // no timeout if (!terminated && which == pipe) { zmsg_t *msg = zmsg_recv (which); if (!msg) break; // Interrupted char *command = zmsg_popstr (msg); if (streq (command, "$TERM")) { terminated = true; } else if (streq (command, "SHOUT")) { char *string = zmsg_popstr (msg); zyre_shouts (node, fnpGroup, "%s", string); } else if (streq (command, "WHISPER")) { char *string = zmsg_popstr (msg); zyre_whispers (node, lastPeer, "%s", string); } else { sim_debug (DBG_IPCVERBOSE, &ipc_dev,"ipc_actor(): E: invalid message to actor"); //assert (false); } free (command); zmsg_destroy (&msg); } else if (!terminated && which == zyre_socket (node)) { zmsg_t *msg = zmsg_recv (which); char *event = zmsg_popstr (msg); char *peer = zmsg_popstr (msg); char *name = zmsg_popstr (msg); char *group = zmsg_popstr (msg); char *message = zmsg_popstr (msg); // change to zmsg_popmsg (zmsg_t *self) later if (streq (event, "ENTER")) { ipc(ipcEnter, name, peer, message, 0); } else if (streq (event, "EXIT")) { ipc(ipcExit, name, peer, 0, 0); } if (streq (event, "SHOUT")) { ipc(ipcShoutRx, name, peer, message, 0); } if (streq (event, "WHISPER")) { ipc(ipcWhisperRx, name, peer, group, 0); } if (ipc_verbose) { ipc_printf("Message from node\n"); ipc_printf("event: %s peer: %s name: %s group: %s message: %s\n", event, peer, name, group, message); } free (event); free (peer); free (name); free (group); free (message); zmsg_destroy (&msg); } } }
static int s_self_handle_pipe (self_t *self) { // Get the whole message off the pipe in one go zmsg_t *request = zmsg_recv (self->pipe); if (!request) return -1; // Interrupted char *command = zmsg_popstr (request); assert (command); if (self->verbose) zsys_info ("zproxy: API command=%s", command); if (streq (command, "FRONTEND")) { s_self_configure (self, &self->frontend, request, FRONTEND); zsock_signal (self->pipe, 0); } else if (streq (command, "BACKEND")) { s_self_configure (self, &self->backend, request, BACKEND); zsock_signal (self->pipe, 0); } else if (streq (command, "CAPTURE")) { self->capture = zsock_new (ZMQ_PUSH); assert (self->capture); char *endpoint = zmsg_popstr (request); assert (endpoint); int rc = zsock_connect (self->capture, "%s", endpoint); assert (rc == 0); zstr_free (&endpoint); zsock_signal (self->pipe, 0); } else if (streq (command, "PAUSE")) { zpoller_destroy (&self->poller); self->poller = zpoller_new (self->pipe, NULL); assert (self->poller); zsock_signal (self->pipe, 0); } else if (streq (command, "RESUME")) { zpoller_destroy (&self->poller); self->poller = zpoller_new (self->pipe, self->frontend, self->backend, NULL); assert (self->poller); zsock_signal (self->pipe, 0); } else if (streq (command, "VERBOSE")) { self->verbose = true; zsock_signal (self->pipe, 0); } else if (streq (command, "DOMAIN")) { proxy_socket selected_socket = s_self_selected_socket (request); char *domain = zmsg_popstr (request); assert (domain); zstr_free (&self->domain [selected_socket]); self->domain [selected_socket] = domain; zsock_signal (self->pipe, 0); } else if (streq (command, "PLAIN")) { proxy_socket selected_socket = s_self_selected_socket (request); self->auth_type [selected_socket] = AUTH_PLAIN; zsock_signal (self->pipe, 0); } else if (streq (command, "CURVE")) { proxy_socket selected_socket = s_self_selected_socket (request); self->auth_type [selected_socket] = AUTH_CURVE; char *public_key = zmsg_popstr (request); assert (public_key); char *secret_key = zmsg_popstr (request); assert (secret_key); zstr_free (&self->public_key [selected_socket]); zstr_free (&self->secret_key [selected_socket]); self->public_key [selected_socket] = public_key; self->secret_key [selected_socket] = secret_key; zsock_signal (self->pipe, 0); } else if (streq (command, "$TERM")) self->terminated = true; else { zsys_error ("zproxy: - invalid command: %s", command); assert (false); } zstr_free (&command); zmsg_destroy (&request); return 0; }
static void handler (zsock_t *pipe, void *args) { curl_global_init(CURL_GLOBAL_ALL); CURLM *multi = curl_multi_init (); CURLSH *share = curl_share_init (); curl_share_setopt (share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS); curl_share_setopt (share, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION); curl_share_setopt (share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT); long verbose = (*(bool *) args) ? 1L : 0L; long timeout = 30; CURLMcode code; SOCKET pipefd = zsock_fd (pipe); struct curl_waitfd waitfd = {pipefd, CURL_WAIT_POLLIN}; // List to hold pending curl handles, in case we are destroy the client // while request are inprogress zlistx_t *pending_handles = zlistx_new (); zlistx_set_destructor (pending_handles, (zlistx_destructor_fn *) curl_destructor); zsock_signal (pipe, 0); bool terminated = false; while (!terminated) { int events = zsock_events (pipe); if ((events & ZMQ_POLLIN) == 0) { code = curl_multi_wait (multi, &waitfd, 1, 1000, NULL); assert (code == CURLM_OK); } events = zsock_events (pipe); if (events & ZMQ_POLLIN) { char* command = zstr_recv (pipe); if (!command) break; // Interrupted // All actors must handle $TERM in this way if (streq (command, "$TERM")) terminated = true; else if (streq (command, "GET")) { char *url; zlistx_t *headers; void *userp; int rc = zsock_recv (pipe, "slp", &url, &headers, &userp); assert (rc == 0); zchunk_t *data = zchunk_new (NULL, 100); assert (data); struct curl_slist *curl_headers = zlistx_to_slist (headers); CURL *curl = curl_easy_init (); zlistx_add_end (pending_handles, curl); http_request *request = (http_request *) zmalloc (sizeof (http_request)); assert (request); request->userp = userp; request->curl = curl; request->data = data; request->headers = curl_headers; curl_easy_setopt (curl, CURLOPT_SHARE, share); curl_easy_setopt (curl, CURLOPT_TIMEOUT, timeout); curl_easy_setopt (curl, CURLOPT_VERBOSE, verbose); curl_easy_setopt (curl, CURLOPT_HTTPHEADER, curl_headers); curl_easy_setopt (curl, CURLOPT_URL, url); curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt (curl, CURLOPT_WRITEDATA, data); curl_easy_setopt (curl, CURLOPT_PRIVATE, request); code = curl_multi_add_handle (multi, curl); assert (code == CURLM_OK); zlistx_destroy (&headers); zstr_free (&url); } else { puts ("E: invalid message to actor"); assert (false); } zstr_free (&command); } int still_running; code = curl_multi_perform (multi, &still_running); assert (code == CURLM_OK); int msgq = 0; struct CURLMsg *msg = curl_multi_info_read(multi, &msgq); while (msg) { if(msg->msg == CURLMSG_DONE) { CURL *curl = msg->easy_handle; http_request *request; curl_easy_getinfo(curl, CURLINFO_PRIVATE, &request); long response_code_long; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &response_code_long); int response_code = (int)response_code_long; int rc = zsock_send (pipe, "icp", response_code, request->data, request->userp); assert (rc == 0); curl_multi_remove_handle (multi, curl); // Remove curl from the pending handles and delete it void *handle = zlistx_find (pending_handles, curl); assert (handle); rc = zlistx_delete (pending_handles, handle); assert (rc == 0); } msg = curl_multi_info_read(multi, &msgq); } } zlistx_destroy (&pending_handles); curl_share_cleanup (share); curl_multi_cleanup (multi); curl_global_cleanup (); }
static void node_actor (zsock_t *pipe, void *args) { zyre_t *node = zyre_new (NULL); if (!node) return; // Could not create new node zyre_set_verbose (node); zyre_set_endpoint (node, "inproc://%s", (char *) args); free (args); // Connect to test hub zyre_gossip_connect (node, "inproc://zyre-hub"); zyre_start (node); zsock_signal (pipe, 0); // Signal "ready" to caller int counter = 0; char *to_peer = NULL; // Either of these set, char *to_group = NULL; // and we set a message char *cookie = NULL; zpoller_t *poller = zpoller_new (pipe, zyre_socket (node), NULL); int64_t trigger = zclock_mono () + 1000; while (true) { void *which = zpoller_wait (poller, randof (1000)); if (!which) break; // Interrupted // $TERM from parent means exit; anything else is breach of // contract so we should assert if (which == pipe) { char *command = zstr_recv (pipe); assert (streq (command, "$TERM")); zstr_free (&command); break; // Finished } // Process an event from node if (which == zyre_socket (node)) { zmsg_t *incoming = zyre_recv (node); if (!incoming) break; // Interrupted char *event = zmsg_popstr (incoming); char *peer = zmsg_popstr (incoming); char *name = zmsg_popstr (incoming); if (streq (event, "ENTER")) // Always say hello to new peer to_peer = strdup (peer); else if (streq (event, "EXIT")) // Always try talk to departed peer to_peer = strdup (peer); else if (streq (event, "WHISPER")) { // Send back response 1/2 the time if (randof (2) == 0) { to_peer = strdup (peer); cookie = zmsg_popstr (incoming); } } else if (streq (event, "SHOUT")) { to_peer = strdup (peer); to_group = zmsg_popstr (incoming); cookie = zmsg_popstr (incoming); // Send peer response 1/3rd the time if (randof (3) > 0) { free (to_peer); to_peer = NULL; } // Send group response 1/3rd the time if (randof (3) > 0) { free (to_group); to_group = NULL; } } else if (streq (event, "JOIN")) { char *group = zmsg_popstr (incoming); printf ("I: %s joined %s\n", name, group); free (group); } else if (streq (event, "LEAVE")) { char *group = zmsg_popstr (incoming); printf ("I: %s left %s\n", name, group); free (group); } free (event); free (peer); free (name); zmsg_destroy (&incoming); // Send outgoing messages if needed if (to_peer) { zyre_whispers (node, to_peer, "%d", counter++); free (to_peer); to_peer = NULL; } if (to_group) { zyre_shouts (node, to_group, "%d", counter++); free (to_group); to_group = NULL; } if (cookie) { free (cookie); cookie = NULL; } } if (zclock_mono () >= trigger) { trigger = zclock_mono () + 1000; char group [10]; sprintf (group, "GROUP%03d", randof (MAX_GROUP)); if (randof (4) == 0) zyre_join (node, group); else if (randof (3) == 0) zyre_leave (node, group); } } zpoller_destroy (&poller); zyre_destroy (&node); }
// .split main task // We have a single task that implements the worker side of the // Paranoid Pirate Protocol (PPP). The interesting parts here are // the heartbeating, which lets the worker detect if the queue has // died, and vice versa: static void ppworker_actor(zsock_t *pipe, void *args) { ubx_block_t *b = (ubx_block_t *) args; struct czmq_ppworker_info *inf = (struct czmq_ppworker_info*) b->private_data; zsock_t *worker = s_worker_socket (); // If liveness hits zero, queue is considered disconnected size_t liveness = HEARTBEAT_LIVENESS; size_t interval = INTERVAL_INIT; // Send out heartbeats at regular intervals uint64_t heartbeat_at = zclock_time () + HEARTBEAT_INTERVAL; srandom ((unsigned) time (NULL)); printf("ppworker: actor started.\n"); // send signal on pipe socket to acknowledge initialisation zsock_signal (pipe, 0); while (true) { zmq_pollitem_t items [] = { { zsock_resolve(worker), 0, ZMQ_POLLIN, 0 } }; int rc = zmq_poll (items, 1, HEARTBEAT_INTERVAL * ZMQ_POLL_MSEC); if (rc == -1) break; // Interrupted if (items [0].revents & ZMQ_POLLIN) { // Get message // - 3-part envelope + content -> request // - 1-part HEARTBEAT -> heartbeat zmsg_t *msg = zmsg_recv (worker); if (!msg) break; // Interrupted if (zmsg_size (msg) == 3) { printf ("I: normal reply\n"); byte *buffer; size_t buffer_size = zmsg_encode (msg, &buffer); ubx_type_t* type = ubx_type_get(b->ni, "unsigned char"); ubx_data_t umsg; umsg.data = (void *)buffer; umsg.len = buffer_size; umsg.type = type; __port_write(inf->ports.zmq_in, &umsg); zmsg_send (&msg, worker); liveness = HEARTBEAT_LIVENESS; sleep (1); // Do some heavy work if (zsys_interrupted) break; } else // .split handle heartbeats // When we get a heartbeat message from the queue, it means the // queue was (recently) alive, so we must reset our liveness // indicator: if (zmsg_size (msg) == 1) { zframe_t *frame = zmsg_first (msg); if (memcmp (zframe_data (frame), PPP_HEARTBEAT, 1) == 0) liveness = HEARTBEAT_LIVENESS; else { printf ("E: invalid message\n"); zmsg_dump (msg); } zmsg_destroy (&msg); } else { printf ("E: invalid message\n"); zmsg_dump (msg); } interval = INTERVAL_INIT; } else // .split detecting a dead queue // If the queue hasn't sent us heartbeats in a while, destroy the // socket and reconnect. This is the simplest most brutal way of // discarding any messages we might have sent in the meantime: if (--liveness == 0) { printf ("W: heartbeat failure, can't reach queue\n"); printf ("W: reconnecting in %zd msec...\n", interval); zclock_sleep (interval); if (interval < INTERVAL_MAX) interval *= 2; zsock_destroy(&worker); worker = s_worker_socket (); liveness = HEARTBEAT_LIVENESS; } // Send heartbeat to queue if it's time if (zclock_time () > heartbeat_at) { heartbeat_at = zclock_time () + HEARTBEAT_INTERVAL; printf ("I: worker heartbeat\n"); zframe_t *frame = zframe_new (PPP_HEARTBEAT, 1); zframe_send (&frame, worker, 0); } } }
/// // Send a signal over a socket. A signal is a short message carrying a // success/failure code (by convention, 0 means OK). Signals are encoded // to be distinguishable from "normal" messages. Accepts a zsock_t or a // zactor_t argument, and returns 0 if successful, -1 if the signal could // not be sent. Takes a polymorphic socket reference. int QZsock::signal (byte status) { int rv = zsock_signal (self, status); return rv; }
Z K2(zsocksignal){PC(x); R kj(zsock_signal(VSK(x), y->g));}
static int pipe_loop_handler(zloop_t *loop, zsock_t *pipe, void *arg) { int ret = 0; client_proxy_t *self = arg; zmsg_t *request = zmsg_recv(pipe); if (!request) { return ret; } char *command = zmsg_popstr(request); if (self->verbose) { zsys_debug("client proxy: API command %s", command); } if (streq(command, "START")) { char *endpoint = zmsg_popstr(request); self->rep = zsock_new_rep(endpoint); assert(self->rep); zsys_info("client proxy: is listening on %s", endpoint); zloop_reader(self->loop, self->rep, reader_rep_event, self); zstr_free(&endpoint); char *pub_ep = zmsg_popstr(request); self->pub = zsock_new_pub(pub_ep); assert(self->pub); zsys_info("client proxy: is publishing on %s", pub_ep); zstr_free(&pub_ep); zsock_signal(self->pipe, 0); } else if (streq(command, "SETTICKETSTORE")) { char *ep = zmsg_popstr(request); self->ticket_store_req = zsock_new_req(ep); assert(self->ticket_store_req); zsys_info("client proxy: ticket api using %s", ep); zstr_free(&ep); char *pub_ep = zmsg_popstr(request); self->ticket_store_sub = zsock_new_sub(pub_ep, ""); zloop_reader(self->loop, self->ticket_store_sub, reader_internal_sub_event, self); zsys_info("client proxy: republishing messages from %s", pub_ep); zstr_free(&pub_ep); zsock_signal(self->pipe, 0); } else if (streq(command, "SETPRINTERSTORE")) { char *ep = zmsg_popstr(request); self->printer_store_req = zsock_new_req(ep); assert(self->printer_store_req); zsys_info("client proxy: printer api is ready from %s", ep); zstr_free(&ep); char *subep = zmsg_popstr(request); self->printer_store_sub = zsock_new_sub(subep, ""); zloop_reader(self->loop, self->printer_store_sub, reader_internal_sub_event, self); zsys_info("client proxy: republishing message from %s", subep); zstr_free(&subep); zsock_signal(self->pipe, 0); } else if (streq(command, "$TERM")) { ret = -1; } else if (streq(command, "VERBOSE")) { self->verbose = true; } zstr_free(&command); zmsg_destroy(&request); return ret; }
/// // Send a signal over a socket. A signal is a short message carrying a // success/failure code (by convention, 0 means OK). Signals are encoded // to be distinguishable from "normal" messages. Accepts a zsock_t or a // zactor_t argument, and returns 0 if successful, -1 if the signal could // not be sent. Takes a polymorphic socket reference. int QmlZsock::signal (byte status) { return zsock_signal (self, status); };
static void chat_actor (zsock_t *pipe, void *args) { zyre_t *node = zyre_new ((char *) args); if (!node) return; // Could not create new node zyre_start (node); zyre_join (node, "CHAT"); zsock_signal (pipe, 0); // Signal "ready" to caller bool terminated = false; zpoller_t *poller = zpoller_new (pipe, zyre_socket (node), NULL); while (!terminated) { void *which = zpoller_wait (poller, -1); if (which == pipe) { zmsg_t *msg = zmsg_recv (which); if (!msg) break; // Interrupted char *command = zmsg_popstr (msg); if (streq (command, "$TERM")) terminated = true; else if (streq (command, "SHOUT")) { char *string = zmsg_popstr (msg); zyre_shouts (node, "CHAT", "%s", string); } else { puts ("E: invalid message to actor"); assert (false); } free (command); zmsg_destroy (&msg); } else if (which == zyre_socket (node)) { zmsg_t *msg = zmsg_recv (which); char *event = zmsg_popstr (msg); char *peer = zmsg_popstr (msg); char *name = zmsg_popstr (msg); char *group = zmsg_popstr (msg); char *message = zmsg_popstr (msg); if (streq (event, "ENTER")) printf ("%s has joined the chat\n", name); else if (streq (event, "EXIT")) printf ("%s has left the chat\n", name); else if (streq (event, "SHOUT")) printf ("%s: %s\n", name, message); else if (streq (event, "EVASIVE")) printf ("%s is being evasive\n", name); free (event); free (peer); free (name); free (group); free (message); zmsg_destroy (&msg); } } zpoller_destroy (&poller); zyre_stop (node); zclock_sleep (100); zyre_destroy (&node); }
void WorkerAgent::actorTask(zsock_t *pipe, void *args) { assert(pipe); assert(args); const WorkerAgent &agent = *static_cast<WorkerAgent *>(args); const auto worker = detail::makeSock(zsock_new_router(agent._localEndpoint.c_str())); assert(worker.get()); const auto poller = detail::makePoller(zpoller_new(pipe, worker.get(), nullptr)); assert(poller.get()); int rc = zsock_signal(pipe, 0); UNUSED(rc); assert(rc == 0); bool terminated = false; while (!terminated && !zsys_interrupted) { zsock_t *sock = static_cast<zsock_t *>(zpoller_wait(poller.get(), -1)); if (sock == pipe) { std::unique_ptr<char> command(zstr_recv(sock)); if (streq(command.get(), "$TERM")) { terminated = true; } } else if (sock == worker.get()) { auto request = detail::makeMsg(zmsg_recv(sock)); assert(zmsg_size(request.get()) == 3); auto identity = detail::makeFrame(zmsg_pop(request.get())); auto id = detail::makeFrame(zmsg_pop(request.get())); static const auto respond = []( auto &&identity, auto &&id, const char *status, auto &&data, zsock_t *sock) { zmsg_t *response = zmsg_new(); // Identity for ROUTER zframe_t *f = identity.release(); zmsg_append(response, &f); // Caller local ID f = id.release(); zmsg_append(response, &f); // Status f = zframe_new(status, std::strlen(status)); zmsg_append(response, &f); // Result f = data.release(); zmsg_append(response, &f); zmsg_send(&response, sock); }; try { auto argsFrame = detail::makeFrame(zmsg_pop(request.get())); msgpack::unpacked msg; msgpack::unpack( &msg, reinterpret_cast<const char *>(zframe_data(argsFrame.get())), zframe_size(argsFrame.get())); msgpack::sbuffer sbuf; agent._callback(msg, sbuf); auto resultFrame = detail::makeFrame(zframe_new(sbuf.data(), sbuf.size())); respond(identity, id, "", resultFrame, sock); } catch (const msgpack::type_error &e) { respond(identity, id, "I", detail::makeFrame(zframe_new_empty()), sock); } catch (const InvalidArgument &e) { respond(identity, id, "I", detail::makeFrame(zframe_new_empty()), sock); } catch (const UndefinedReference &e) { respond(identity, id, "U", detail::makeFrame(zframe_new_empty()), sock); } catch (const NetworkError &e) { respond(identity, id, "N", detail::makeFrame(zframe_new_empty()), sock); } catch (...) { respond(identity, id, "?", detail::makeFrame(zframe_new_empty()), sock); } } } zsys_debug("Cleaned up worker agent."); }
static int mrb_actor_pipe_reader(zloop_t* reactor, zsock_t* pipe, void* args) { errno = 0; self_t* self = (self_t*)args; int rc = 0; zmsg_t* msg = zmsg_recv(pipe); if (!msg) return -1; char* command = zmsg_popstr(msg); zsys_debug("command: %s", command); if (streq(command, "$TERM")) { rc = -1; } else if (streq(command, "BIND ROUTER")) { char* endpoint = zmsg_popstr(msg); if (zsock_bind(self->router, "%s", endpoint) >= 0) { const char* boundendpoint = zsock_endpoint(self->router); zyre_set_header(self->discovery, "mrb-actor-v1-router", "%s", boundendpoint); zsock_signal(pipe, 0); zsock_send(pipe, "s", boundendpoint); } else { zsock_signal(pipe, 1); zsock_send(pipe, "i", errno); } zstr_free(&endpoint); } else if (streq(command, "BIND PULL")) { char* endpoint = zmsg_popstr(msg); if (zsock_bind(self->pull, "%s", endpoint) >= 0) { const char* boundendpoint = zsock_endpoint(self->pull); zyre_set_header(self->discovery, "mrb-actor-v1-pull", "%s", boundendpoint); zsock_signal(pipe, 0); zsock_send(pipe, "s", boundendpoint); } else { zsock_signal(pipe, 1); zsock_send(pipe, "i", errno); } zstr_free(&endpoint); } else if (streq(command, "ZYRE SET ENDPOINT")) { char* endpoint = zmsg_popstr(msg); if (zyre_set_endpoint(self->discovery, "%s", endpoint) == -1) { zsock_signal(pipe, 1); } else { zsock_signal(pipe, 0); } zstr_free(&endpoint); } else if (streq(command, "ZYRE GOSSIP BIND")) { char* endpoint = zmsg_popstr(msg); zyre_gossip_bind(self->discovery, "%s", endpoint); zstr_free(&endpoint); } else if (streq(command, "ZYRE GOSSIP CONNECT")) { char* endpoint = zmsg_popstr(msg); zyre_gossip_connect(self->discovery, "%s", endpoint); zstr_free(&endpoint); } else if (streq(command, "ZYRE START")) { if (zyre_start(self->discovery) == -1) { zsock_signal(pipe, 1); } else { zyre_join(self->discovery, "mrb-actor-v1"); zsock_signal(pipe, 0); } } else if (streq(command, "LOAD IREP FILE")) { char* mrb_file = zmsg_popstr(msg); mrb_state* mrb = self->mrb; int ai = mrb_gc_arena_save(mrb); struct mrb_jmpbuf* prev_jmp = mrb->jmp; struct mrb_jmpbuf c_jmp; MRB_TRY(&c_jmp) { mrb->jmp = &c_jmp; FILE* fp = fopen(mrb_file, "rb"); if (!fp) { mrb_sys_fail(mrb, "fopen"); } mrb_load_irep_file(mrb, fp); fclose(fp); if (mrb->exc) { mrb_exc_raise(mrb, mrb_obj_value(mrb->exc)); } zsock_signal(pipe, 0); mrb->jmp = prev_jmp; } MRB_CATCH(&c_jmp) { mrb->jmp = prev_jmp; mrb_print_error(mrb); zsock_signal(pipe, 1); mrb->exc = NULL; } MRB_END_EXC(&c_jmp); mrb_gc_arena_restore(mrb, ai); zstr_free(&mrb_file); }
static int zyre_node_recv_api (zyre_node_t *self) { // Get the whole message off the pipe in one go zmsg_t *request = zmsg_recv (self->pipe); char *command = zmsg_popstr (request); if (!command) return -1; // Interrupted if (streq (command, "SET NAME")) { free (self->name); self->name = zmsg_popstr (request); assert (self->name); } else if (streq (command, "SET HEADER")) { char *name = zmsg_popstr (request); char *value = zmsg_popstr (request); zhash_update (self->headers, name, value); zstr_free (&name); zstr_free (&value); } else if (streq (command, "SET VERBOSE")) self->verbose = true; else if (streq (command, "SET PORT")) { char *value = zmsg_popstr (request); self->beacon_port = atoi (value); zstr_free (&value); } else if (streq (command, "SET INTERVAL")) { char *value = zmsg_popstr (request); self->interval = atol (value); zstr_free (&value); } else if (streq (command, "UUID")) zstr_send (self->pipe, zuuid_str (self->uuid)); else if (streq (command, "NAME")) zstr_send (self->pipe, self->name); else if (streq (command, "BIND")) { char *endpoint = zmsg_popstr (request); zsock_signal (self->pipe, zyre_node_bind (self, endpoint)); zstr_free (&endpoint); } else if (streq (command, "CONNECT")) { char *endpoint = zmsg_popstr (request); zsock_signal (self->pipe, zyre_node_connect (self, endpoint)); zstr_free (&endpoint); } else if (streq (command, "START")) zsock_signal (self->pipe, zyre_node_start (self)); else if (streq (command, "STOP")) zsock_signal (self->pipe, zyre_node_stop (self)); else if (streq (command, "WHISPER")) { // Get peer to send message to char *identity = zmsg_popstr (request); zyre_peer_t *peer = (zyre_peer_t *) zhash_lookup (self->peers, identity); // Send frame on out to peer's mailbox, drop message // if peer doesn't exist (may have been destroyed) if (peer) { zre_msg_t *msg = zre_msg_new (ZRE_MSG_WHISPER); zre_msg_set_content (msg, &request); zyre_peer_send (peer, &msg); } zstr_free (&identity); } else if (streq (command, "SHOUT")) { // Get group to send message to char *name = zmsg_popstr (request); zyre_group_t *group = (zyre_group_t *) zhash_lookup (self->peer_groups, name); if (group) { zre_msg_t *msg = zre_msg_new (ZRE_MSG_SHOUT); zre_msg_set_group (msg, name); zre_msg_set_content (msg, &request); zyre_group_send (group, &msg); } zstr_free (&name); } else if (streq (command, "JOIN")) { char *name = zmsg_popstr (request); zyre_group_t *group = (zyre_group_t *) zhash_lookup (self->own_groups, name); if (!group) { // Only send if we're not already in group group = zyre_group_new (name, self->own_groups); zre_msg_t *msg = zre_msg_new (ZRE_MSG_JOIN); zre_msg_set_group (msg, name); // Update status before sending command zre_msg_set_status (msg, ++(self->status)); zhash_foreach (self->peers, zyre_node_send_peer, msg); zre_msg_destroy (&msg); if (self->verbose) zsys_info ("(%s) JOIN group=%s", self->name, name); } zstr_free (&name); } else if (streq (command, "LEAVE")) { char *name = zmsg_popstr (request); zyre_group_t *group = (zyre_group_t *) zhash_lookup (self->own_groups, name); if (group) { // Only send if we are actually in group zre_msg_t *msg = zre_msg_new (ZRE_MSG_LEAVE); zre_msg_set_group (msg, name); // Update status before sending command zre_msg_set_status (msg, ++(self->status)); zhash_foreach (self->peers, zyre_node_send_peer, msg); zre_msg_destroy (&msg); zhash_delete (self->own_groups, name); if (self->verbose) zsys_info ("(%s) LEAVE group=%s", self->name, name); } zstr_free (&name); } else if (streq (command, "DUMP")) zyre_node_dump (self); else if (streq (command, "$TERM")) self->terminated = true; else { zsys_error ("invalid command '%s'\n", command); assert (false); } zstr_free (&command); zmsg_destroy (&request); return 0; }
static void zyre_bridge_actor (zsock_t *pipe, void *args) { // initialization ubx_block_t *b = (ubx_block_t *) args; struct zyre_bridge_info *inf = (struct zyre_bridge_info*) b->private_data; printf("[zyre_bridge]: actor started.\n"); // send signal on pipe socket to acknowledge initialization zsock_signal (pipe, 0); bool terminated = false; zpoller_t *poller = zpoller_new (pipe, zyre_socket (inf->node), NULL); while (!terminated) { void *which = zpoller_wait (poller, -1); // handle msgs from main thread if (which == pipe) { zmsg_t *msg = zmsg_recv (which); if (!msg) break; // Interrupted // only react to TERM signal char *command = zmsg_popstr (msg); if (streq (command, "$TERM")) terminated = true; else { puts ("Invalid pipe message to actor"); } free (command); zmsg_destroy (&msg); } else // handle msgs from zyre network if (which == zyre_socket (inf->node)) { zmsg_t *msg = zmsg_recv (which); if (!msg) { printf("[zyre_bridge]: interrupted!\n"); } char *event = zmsg_popstr (msg); char *peer = zmsg_popstr (msg); char *name = zmsg_popstr (msg); if (streq (event, "ENTER")) printf ("[zyre_bridge]: %s has entered\n", name); else if (streq (event, "EXIT")) printf ("[zyre_bridge]: %s has exited\n", name); else if (streq (event, "SHOUT")) { printf ("[zyre_bridge]: SHOUT received from %s.\n", name); char *group = zmsg_popstr (msg); char *message = zmsg_popstr (msg); // load JSON msg json_t *m; json_error_t error; m= json_loads(message,0,&error); if(!m) { printf("Error parsing JSON payload! line %d: %s\n", error.line, error.text); json_decref(m); return; } printf("%s\n",message); if (json_object_get(m, "type")) { std::string type = json_dumps(json_object_get(m, "type"), JSON_ENCODE_ANY); type = type.substr(1, type.size()-2); // get rid of " characters printf("type: %s\n",json_dumps(json_object_get(m, "type"), JSON_ENCODE_ANY)); for (int i=0; i < inf->input_type_list.size();i++) { //if (json_string_value(json_object_get(m, "type")) == inf->input_type_list[i]){ //printf("type list, type : %s, %s \n", inf->input_type_list[i].c_str(), type.c_str()); if (inf->input_type_list[i].compare(type) == 0) { ubx_type_t* type = ubx_type_get(b->ni, "unsigned char"); ubx_data_t ubx_msg; ubx_msg.data = (void *)json_dumps(json_object_get(m, "payload"), JSON_ENCODE_ANY); printf("message: %s\n",json_dumps(json_object_get(m, "payload"), JSON_ENCODE_ANY)); ubx_msg.len = strlen(json_dumps(json_object_get(m, "payload"), JSON_ENCODE_ANY)); ubx_msg.type = type; __port_write(inf->ports.zyre_in, &ubx_msg); } } } else { printf("Error parsing JSON string! Does not conform to msg model.\n"); } free (group); free (message); } else if (streq (event, "WHISPER")){ char *message = zmsg_popstr (msg); printf ("%s: WHISPER \n%s\n", name, message); free (message); } else if (streq (event, "EVASIVE")) printf ("[zyre_bridge]: %s is being evasive\n", name); free (event); free (peer); free (name); zmsg_destroy (&msg); } } zpoller_destroy (&poller); //TODO: make parametrizable zclock_sleep (100); }
JNIEXPORT jint JNICALL Java_org_zeromq_czmq_Zsock__1_1signal (JNIEnv *env, jclass c, jlong self, jbyte status) { jint signal_ = (jint) zsock_signal ((zsock_t *) (intptr_t) self, (byte) status); return signal_; }
static int s_self_handle_pipe (self_t *self) { // Get the whole message off the pipe in one go zmsg_t *request = zmsg_recv (self->pipe); if (!request) return -1; // Interrupted char *command = zmsg_popstr (request); if (self->verbose) zsys_info ("zauth: API command=%s", command); if (streq (command, "ALLOW")) { char *address = zmsg_popstr (request); while (address) { if (self->verbose) zsys_info ("zauth: - whitelisting ipaddress=%s", address); zhashx_insert (self->whitelist, address, "OK"); zstr_free (&address); address = zmsg_popstr (request); } zsock_signal (self->pipe, 0); } else if (streq (command, "DENY")) { char *address = zmsg_popstr (request); while (address) { if (self->verbose) zsys_info ("zauth: - blacklisting ipaddress=%s", address); zhashx_insert (self->blacklist, address, "OK"); zstr_free (&address); address = zmsg_popstr (request); } zsock_signal (self->pipe, 0); } else if (streq (command, "PLAIN")) { // Get password file and load into zhash table // If the file doesn't exist we'll get an empty table char *filename = zmsg_popstr (request); zhashx_destroy (&self->passwords); self->passwords = zhashx_new (); if (zhashx_load (self->passwords, filename) && self->verbose) zsys_info ("zauth: could not load file=%s", filename); zstr_free (&filename); zsock_signal (self->pipe, 0); } else if (streq (command, "CURVE")) { // If location is CURVE_ALLOW_ANY, allow all clients. Otherwise // treat location as a directory that holds the certificates. char *location = zmsg_popstr (request); if (streq (location, CURVE_ALLOW_ANY)) self->allow_any = true; else { zcertstore_destroy (&self->certstore); // FIXME: what if this fails? self->certstore = zcertstore_new (location); self->allow_any = false; } zstr_free (&location); zsock_signal (self->pipe, 0); } else if (streq (command, "GSSAPI")) // GSSAPI authentication is not yet implemented here zsock_signal (self->pipe, 0); else if (streq (command, "VERBOSE")) { self->verbose = true; zsock_signal (self->pipe, 0); } else if (streq (command, "$TERM")) self->terminated = true; else { zsys_error ("zauth: - invalid command: %s", command); assert (false); } zstr_free (&command); zmsg_destroy (&request); return 0; }
static int s_on_command (zloop_t *loop, zsock_t *reader, void *arg) { zdir_watch_t *watch = (zdir_watch_t *) arg; zmsg_t *msg = zmsg_recv (watch->pipe); assert (msg); char *command = zmsg_popstr (msg); assert (command); if (watch->verbose) zsys_info ("zdir_watch: Command received: %s", command); if (streq (command, "$TERM")) { zstr_free (&command); zmsg_destroy (&msg); return -1; } else if (streq (command, "VERBOSE")) { watch->verbose = true; zsock_signal (watch->pipe, 0); } else if (streq (command, "SUBSCRIBE")) { char *path = zmsg_popstr (msg); if (path) { s_zdir_watch_subscribe (watch, path); freen (path); } else { if (watch->verbose) zsys_error ("zdir_watch: Unable to extract path from SUBSCRIBE message"); zsock_signal (watch->pipe, 1); } } else if (streq (command, "UNSUBSCRIBE")) { char *path = zmsg_popstr (msg); if (path) { assert (path); s_zdir_watch_unsubscribe (watch, path); freen (path); } else { if (watch->verbose) zsys_error ("zdir_watch: Unable to extract path from UNSUBSCRIBE message"); zsock_signal (watch->pipe, 1); } } else if (streq (command, "TIMEOUT")) { char *timeout_string = zmsg_popstr (msg); if (timeout_string) { int timeout = atoi (timeout_string); zsock_signal (watch->pipe, s_zdir_watch_timeout (watch, timeout)); freen (timeout_string); } else { if (watch->verbose) zsys_error ("zdir_watch: Unable to extract time from TIMEOUT message"); zsock_signal (watch->pipe, 1); } } else { if (watch->verbose) zsys_warning ("zdir_watch: Unknown command '%s'", command); zsock_signal (watch->pipe, 1); } freen (command); zmsg_destroy (&msg); return 0; }