Esempio n. 1
0
int32_t crypto777_peer(struct crypto777_node *nn,struct crypto777_node *peer)
{
    struct crypto777_peer *ptr;
    int32_t err=0,err2=0,timeout = 1;//,insock;
    struct crypto777_transport *transport = &nn->transport;
    if ( nn->numpeers < MAXPEERS )
    {
        ptr = &transport->peers[transport->numpeers++];
        printf("%p peer.(%s).%d\n",peer->ip_port,peer->ip_port,peer->transport.port);
        strcpy(ptr->type,peer->transport.type), strcpy(ptr->ip_port,peer->ip_port), ptr->port = peer->transport.port;
        //if ( nn_connect(transport->bus,peer->ip_port) < 0 )
        //    printf("error %d nn_connect.%d bus (%s) | %s\n",err,transport->bus,peer->ip_port,nn_strerror(nn_errno())), getchar();
        if ( (ptr->subsock= nn_socket(AF_SP,NN_SUB)) < 0 || (err= nn_setsockopt(ptr->subsock,NN_SUB,NN_SUB_SUBSCRIBE,"",0)) < 0 || (err2= nn_connect(ptr->subsock,ptr->ip_port)) < 0 )
        {
            printf("error %d too many subs.%d nodeid.%d peerid.%d err.%s err.%d err2.%d ip_port.(%s)\n",ptr->subsock,nn->numpeers,nn->nodeid,peer->nodeid,nn_strerror(nn_errno()),err,err2,ptr->ip_port);
            if ( ptr->subsock >= 0 )
                nn_shutdown(ptr->subsock,0);
            return(-1);
        }
        if ( nn_setsockopt(ptr->subsock,NN_SOL_SOCKET,NN_RCVTIMEO,&timeout,sizeof(timeout)) < 0 )
            printf("error setting recv timeout to %d\n",timeout);
        /*if ( (ptr->pairsock= nn_socket(AF_SP,NN_PAIR)) < 0 )
         printf("error %d nn_socket err.%s\n",ptr->pairsock,nn_strerror(nn_errno()));
         else if ( (err= nn_bind(ptr->pairsock,transport->ip_port)) < 0 )
         printf("error %d nn_bind.%d (%s) | %s\n",err,ptr->pairsock,transport->ip_port,nn_strerror(nn_errno()));
         else if ( nn_connect(ptr->pairsock,peer->ip_port) < 0 )
         printf("error %d nn_connect.%d pairsock (%s) | %s\n",err,ptr->pairsock,peer->ip_port,nn_strerror(nn_errno()));
         if ( nn_setsockopt(ptr->pairsock,NN_SOL_SOCKET,NN_RCVTIMEO,&timeout,sizeof(timeout)) < 0 )
         printf("error setting recv timeout to %d\n",timeout);
         
         if ( (insock= nn_socket(AF_SP,NN_PAIR)) < 0 )
         printf("error %d nn_socket err.%s\n",insock,nn_strerror(nn_errno()));
         else if ( (err= nn_bind(insock,peer->ip_port)) < 0 )
         printf("error %d nn_bind.%d (%s) | %s\n",err,insock,peer->ip_port,nn_strerror(nn_errno()));
         else if ( nn_connect(insock,nn->ip_port) < 0 )
         printf("error %d nn_connect.%d insock (%s) | %s\n",err,insock,nn->ip_port,nn_strerror(nn_errno()));
         else peer->transport.insocks[peer->transport.numpairs++] = insock;*/
        set_bloombits(&nn->blooms[0],peer->nxt64bits);
        nn->peers[nn->numpeers++] = peer;
        return(nn->numpeers);
    } else return(-1);
}
Esempio n. 2
0
int ftw_nanomsg_connector_connect(struct ftw_socket_callsite **callsite, const char *addr,
    int linger, int max_recv_size, struct ftw_socket **sock)
{
    struct ftw_socket *inst;
    int rcs;
    int rco;
    int rcc;

    /*  Preconditions expected of LabVIEW. */
    ftw_assert(*callsite && addr);
    nn_mutex_lock(&(*callsite)->sync);

    rcs = nn_socket(AF_SP, NN_REQ);

    /*  Socket creation failure? */
    if (rcs < 0) {
        *sock = NULL;
        nn_mutex_unlock(&(*callsite)->sync);
        return rcs;
    }

    rco = nn_setsockopt(rcs, NN_SOL_SOCKET, NN_LINGER, &linger, sizeof(linger));
    if (rco < 0) {
        *sock = NULL;
        nn_mutex_unlock(&(*callsite)->sync);
        return rco;
    }

    rco = nn_setsockopt(rcs, NN_SOL_SOCKET, NN_RCVMAXSIZE, &max_recv_size, sizeof(max_recv_size));
    if (rco < 0) {
        *sock = NULL;
        nn_mutex_unlock(&(*callsite)->sync);
        return rco;
    }

    rcc = nn_connect(rcs, addr);

    /*  Endpoint creation failure? */
    if (rcc < 0) {
        nn_close(rcs);
        *sock = NULL;
        nn_mutex_unlock(&(*callsite)->sync);
        return rcc;
    }

    inst = ftw_malloc(sizeof(struct ftw_socket));
    ftw_assert(inst);

    memset(inst, 0, sizeof(*inst));

    inst->id = rcs;
    inst->callsite = *callsite;

    nn_list_item_init(&inst->item);
    nn_list_insert(&(*callsite)->active_sockets, &inst->item,
        nn_list_end(&(*callsite)->active_sockets));

    *sock = inst;

    (*callsite)->lifetime_sockets++;
    nn_mutex_unlock(&(*callsite)->sync);

    return 0;

}
Esempio n. 3
0
int ftw_subscriber_construct(struct ftw_socket_callsite **callsite, LVUserEventRef *lv_event,
    const char *addr, int linger, int max_recv_size, struct ftw_socket **sock)
{
    struct ftw_socket *inst;
    int rcc;
    int rcs;
    int rco;

    /*  Preconditions expected of LabVIEW. */
    ftw_assert(*callsite && addr);
    nn_mutex_lock(&(*callsite)->sync);

    rcs = nn_socket(AF_SP, NN_SUB);

    /*  Socket creation failure? */
    if (rcs < 0) {
        *sock = NULL;
        nn_mutex_unlock(&(*callsite)->sync);
        return rcs;
    }

    rco = nn_setsockopt(rcs, NN_SOL_SOCKET, NN_LINGER, &linger, sizeof(linger));
    if (rco < 0) {
        *sock = NULL;
        nn_mutex_unlock(&(*callsite)->sync);
        return rco;
    }

    rco = nn_setsockopt(rcs, NN_SOL_SOCKET, NN_RCVMAXSIZE, &max_recv_size, sizeof(max_recv_size));
    if (rco < 0) {
        *sock = NULL;
        nn_mutex_unlock(&(*callsite)->sync);
        return rco;
    }

    rcc = nn_connect(rcs, addr);

    /*  Endpoint creation failure? */
    if (rcc < 0) {
        nn_close(rcs);
        *sock = NULL;
        nn_mutex_unlock(&(*callsite)->sync);
        return rcc;
    }

    rco = nn_setsockopt (rcs, NN_SUB, NN_SUB_SUBSCRIBE, "", 0);
    if (rco < 0) {
        nn_close(rcs);
        *sock = NULL;
        nn_mutex_unlock(&(*callsite)->sync);
        return rco;
    }

    inst = ftw_malloc(sizeof(struct ftw_socket));
    ftw_assert(inst);

    inst->incoming_msg_notifier_event = *lv_event;
    inst->id = rcs;
    inst->callsite = *callsite;

    nn_list_item_init(&inst->item);
    nn_list_insert(&(*callsite)->active_sockets, &inst->item,
        nn_list_end(&(*callsite)->active_sockets));

    nn_sem_init(&inst->msg_acknowledged);

    /*  Launch thread and wait for it to initialize. */
    nn_sem_init(&inst->async_recv_ready);
    nn_thread_init(&inst->async_recv_thread, ftw_subscriber_async_recv_thread, inst);
    nn_sem_wait(&inst->async_recv_ready);

    *sock = inst;

    (*callsite)->lifetime_sockets++;
    nn_mutex_unlock(&(*callsite)->sync);

    return 0;
}
Esempio n. 4
0
int main ()
{
    int rc;
    int sb;
    int sc;
    int i;
    char buf [256];
    int val;

    /*  Create a simple topology. */
    sc = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sc != -1);
    rc = nn_connect (sc, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    sb = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sb != -1);
    rc = nn_bind (sb, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    /*  Try a duplicate bind. It should fail. */
    rc = nn_bind (sc, SOCKET_ADDRESS);
    nn_assert (rc < 0 && errno == EADDRINUSE);

    /*  Ping-pong test. */
    for (i = 0; i != 100; ++i) {

        rc = nn_send (sc, "ABC", 3, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);

        rc = nn_recv (sb, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);

        rc = nn_send (sb, "DEFG", 4, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 4);

        rc = nn_recv (sc, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 4);
    }

    /*  Batch transfer test. */
    for (i = 0; i != 100; ++i) {
        rc = nn_send (sc, "XYZ", 3, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);
    }
    for (i = 0; i != 100; ++i) {
        rc = nn_recv (sb, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);
    }

    rc = nn_close (sc);
    errno_assert (rc == 0);
    rc = nn_close (sb);
    errno_assert (rc == 0);

    /*  Test whether queue limits are observed. */
    sb = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sb != -1);
    val = 200;
    rc = nn_setsockopt (sb, NN_SOL_SOCKET, NN_RCVBUF, &val, sizeof (val));
    errno_assert (rc == 0);
    rc = nn_bind (sb, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    sc = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sc != -1);
    rc = nn_connect (sc, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    val = 200;
    rc = nn_setsockopt (sc, NN_SOL_SOCKET, NN_SNDTIMEO, &val, sizeof (val));
    errno_assert (rc == 0);
    i = 0;
    while (1) {
        rc = nn_send (sc, "0123456789", 10, 0);
        if (rc < 0 && nn_errno () == EAGAIN)
            break;
        errno_assert (rc >= 0);
        nn_assert (rc == 10);
        ++i;
    }
    nn_assert (i == 20);
    rc = nn_recv (sb, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 10);
    rc = nn_send (sc, "0123456789", 10, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 10);
    rc = nn_send (sc, "0123456789", 10, 0);
    nn_assert (rc < 0 && nn_errno () == EAGAIN);
    for (i = 0; i != 20; ++i) {
        rc = nn_recv (sb, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 10);
    }

    /*  Make sure that even a message that doesn't fit into the buffers
        gets across. */
    for (i = 0; i != sizeof (buf); ++i)
        buf [i] = 'A';
    rc = nn_send (sc, buf, 256, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 256);
    rc = nn_recv (sb, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 256);

    rc = nn_close (sc);
    errno_assert (rc == 0);
    rc = nn_close (sb);
    errno_assert (rc == 0);

    return 0;
}
Esempio n. 5
0
File: ipc.c Progetto: Droppe/nanomsg
int main ()
{
#if !defined NN_HAVE_WINDOWS
    int rc;
    int sb;
    int sc;
    int i;
    char buf [3];

    /*  Try closing a IPC socket while it not connected. */
    sc = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sc != -1);
    rc = nn_connect (sc, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    rc = nn_close (sc);
    errno_assert (rc == 0);

    /*  Open the socket anew. */
    sc = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sc != -1);
    rc = nn_connect (sc, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    /*  Leave enough time for at least on re-connect attempt. */
    nn_sleep (200);

    sb = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sb != -1);
    rc = nn_bind (sb, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    /*  Ping-pong test. */
    for (i = 0; i != 1; ++i) {

        rc = nn_send (sc, "0123456789012345678901234567890123456789", 40, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 40);

        rc = nn_recv (sb, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 40);

        rc = nn_send (sb, "0123456789012345678901234567890123456789", 40, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 40);

        rc = nn_recv (sc, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 40);
    }

    /*  Batch transfer test. */
    for (i = 0; i != 100; ++i) {
        rc = nn_send (sc, "XYZ", 3, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);
    }
    for (i = 0; i != 100; ++i) {
        rc = nn_recv (sb, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);
    }

    rc = nn_close (sc);
    errno_assert (rc == 0);
    rc = nn_close (sb);
    errno_assert (rc == 0);

#endif

    return 0;
}
Esempio n. 6
0
int flux_cli_id_list(flux_cli_t * client, flux_id_t ** ids) {
    assert(ids);
    assert(*ids == NULL);

    int id_size = nn_send(client->broker_sock, "ID", 2, 0);
    if(id_size != 2) {
        if(client->verbose) printf("Unable to list ids: unable to send to broker: %s\n", nn_strerror(errno));
        return -1;
    }

    char * resp = NULL;
    int resp_size = nn_recv(client->broker_sock, &resp, NN_MSG, 0);
    if(resp_size < 0) {
        if(client->verbose) printf("Unable to list ids: invalid broker response: %s\n", nn_strerror(errno));
        return -1;
    }

    if(servers_string) free(servers_string);
    servers_string = malloc(resp_size);
    assert(servers_string);
    memcpy(servers_string, resp, resp_size);
    nn_freemsg(resp);

    // Split lines & tokenize. Each newline is a server
    // Tokenize string in form "URL\tIDS\n"; replace '\t' with '\0'

    // XXX: not quite thread safe
    int n = 0;
    for(int i = 0; i < resp_size; i++) {
        if(servers_string[i] == '\n') n++;
    }

    struct flux_server * servers = NULL;
    if(n > 0) {
        if(servers_string[resp_size-1] != '\n') {
            if(client->verbose) printf("Warning while listing ids: invalid broker response.\n");
            return -1;
        }
        servers = malloc(n * sizeof(struct flux_server));
        assert(servers);
        char * sptr = servers_string;
        for(int i = 0; i < n; i++) {
            servers[i].rep_url = sptr;
            int j = 0;
            while(sptr[j] != '\t' && sptr[j] != '\n') j++;
            if(sptr[j] != '\t') {
                if(client->verbose) printf("Warning while listing ids: invalid broker response.\n");
                if(client->verbose) printf("Msg: %s; %s\n", servers_string, sptr);
                free(servers);
                return -1;
            }
            sptr += j;
            *(sptr++) = '\0';
            servers[i].ids = (flux_id_t *) sptr;
            for(j = 0; sptr[j] != '\n'; j++);
            servers[i].n_ids = j / sizeof(flux_id_t);
            //assert(servers[i].n_ids * sizeof(flux_id_t) == (size_t) j);
            sptr += j;
            *(sptr++) = '\0';

            servers[i].sock = nn_socket(AF_SP, NN_REQ);
            assert(servers[i].sock >= 0);
            assert(nn_setsockopt(servers[i].sock, NN_SOL_SOCKET, NN_RCVTIMEO, &client->timeout, sizeof(int)) >= 0);
            assert(nn_setsockopt(servers[i].sock, NN_SOL_SOCKET, NN_SNDTIMEO, &client->timeout, sizeof(int)) >= 0);
            if(nn_connect(servers[i].sock, servers[i].rep_url) >= 0) {
                if(client->verbose) printf("Connected to server: %s\n", servers[i].rep_url);
            } else {
                if(client->verbose) printf("Unable to connect to server %s: %s\n", servers[i].rep_url, nn_strerror(errno));
                assert(nn_close(servers[i].sock) == 0);
                n--;
                i--;
            }
        }
    }

    for(size_t i = 0; i < client->n_servers; i++) {
        assert(nn_close(client->servers[i].sock) == 0);
    }
    client->n_servers = n;
    if(client->servers) free(client->servers);
    client->servers = servers;


    // Count the total number of ids
    size_t n_ids = 0;
    for(size_t i = 0; i < client->n_servers; i++) {
        n_ids += client->servers[i].n_ids;
    }

    // Allocate a buffer to id array
    *ids = malloc(n_ids * sizeof(flux_id_t));
    assert(*ids);

    // Concatenate ids
    char * iptr = (char *) *ids;
    for(size_t i = 0; i < client->n_servers; i++) {
        memcpy(iptr, client->servers[i].ids, client->servers[i].n_ids * sizeof(flux_id_t));
        iptr += sizeof(flux_id_t);
    }

    return n_ids;
}
Esempio n. 7
0
int main ()
{
    int rc;
    int rep1;
    int rep2;
    int req1;
    int req2;
    int resend_ivl;
    char buf [7];
    int timeo;

    /*  Test req/rep with full socket types. */
    rep1 = nn_socket (AF_SP, NN_REP);
    errno_assert (rep1 != -1);
    rc = nn_bind (rep1, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    req1 = nn_socket (AF_SP, NN_REQ);
    errno_assert (req1 != -1);
    rc = nn_connect (req1, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    req2 = nn_socket (AF_SP, NN_REQ);
    errno_assert (req2 != -1);
    rc = nn_connect (req2, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    /*  Check invalid sequence of sends and recvs. */
    rc = nn_send (rep1, "ABC", 3, 0);
    nn_assert (rc == -1 && nn_errno () == EFSM);
    rc = nn_recv (req1, buf, sizeof (buf), 0);
    nn_assert (rc == -1 && nn_errno () == EFSM);

    /*  Check fair queueing the requests. */
    rc = nn_send (req2, "ABC", 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (rep1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_send (rep1, buf, 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (req2, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);

    rc = nn_send (req1, "ABC", 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (rep1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_send (rep1, buf, 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (req1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);

    rc = nn_close (rep1);
    errno_assert (rc == 0);
    rc = nn_close (req1);
    errno_assert (rc == 0);    
    rc = nn_close (req2);
    errno_assert (rc == 0);

    /*  Check load-balancing of requests. */
    req1 = nn_socket (AF_SP, NN_REQ);
    errno_assert (req1 != -1);
    rc = nn_bind (req1, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    rep1 = nn_socket (AF_SP, NN_REP);
    errno_assert (rep1 != -1);
    rc = nn_connect (rep1, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    rep2 = nn_socket (AF_SP, NN_REP);
    errno_assert (rep2 != -1);
    rc = nn_connect (rep2, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    rc = nn_send (req1, "ABC", 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (rep1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_send (rep1, buf, 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (req1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);

    rc = nn_send (req1, "ABC", 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (rep2, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_send (rep2, buf, 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (req1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);

    rc = nn_close (rep2);
    errno_assert (rc == 0);
    rc = nn_close (rep1);
    errno_assert (rc == 0);    
    rc = nn_close (req1);
    errno_assert (rc == 0);

    /*  Test re-sending of the request. */
    rep1 = nn_socket (AF_SP, NN_REP);
    errno_assert (rep1 != -1);
    rc = nn_bind (rep1, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    req1 = nn_socket (AF_SP, NN_REQ);
    errno_assert (req1 != -1);
    rc = nn_connect (req1, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    resend_ivl = 100;
    rc = nn_setsockopt (req1, NN_REQ, NN_REQ_RESEND_IVL,
        &resend_ivl, sizeof (resend_ivl));
    errno_assert (rc == 0);

    rc = nn_send (req1, "ABC", 3, 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (rep1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);
    rc = nn_recv (rep1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);

    rc = nn_close (req1);
    errno_assert (rc == 0);
    rc = nn_close (rep1);
    errno_assert (rc == 0);

    /*  Check sending a request when the peer is not available. (It should
        be sent immediatelly when the peer comes online rather than relying
        on the resend algorithm. */
    req1 = nn_socket (AF_SP, NN_REQ);
    errno_assert (req1 != -1);
    rc = nn_connect (req1, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    rc = nn_send (req1, "ABC", 3, 0);
    errno_assert (rc >= 0);

    nn_sleep (10);

    rep1 = nn_socket (AF_SP, NN_REP);
    errno_assert (rep1 != -1);
    rc = nn_bind (rep1, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    timeo = 100;
    rc = nn_setsockopt (rep1, NN_SOL_SOCKET, NN_RCVTIMEO,
       &timeo, sizeof (timeo));
    errno_assert (rc == 0);
    rc = nn_recv (rep1, buf, sizeof (buf), 0);
    errno_assert (rc >= 0);
    nn_assert (rc == 3);

    rc = nn_close (req1);
    errno_assert (rc == 0);
    rc = nn_close (rep1);
    errno_assert (rc == 0);

    return 0;
}
Esempio n. 8
0
static gboolean gst_nanomsgsrc_init_sockets(GstNanomsgSrc *nanomsgsrc)
{
	/* This function must be called with a mutex lock */

	int rc;
	size_t watch_fd_size = sizeof(nanomsgsrc->watch_fd);
	gchar const *actual_uri;

	/* No URI -> cannot initialize anything */
	if (nanomsgsrc->uri == NULL)
	{
		GST_ELEMENT_ERROR(nanomsgsrc, RESOURCE, NOT_FOUND, ("No URI specified"), (NULL));
		return FALSE;
	}

	/* Check for the URI scheme prefix */
	if (!g_str_has_prefix(nanomsgsrc->uri, PROTOCOL_PREFIX))
	{
		GST_ELEMENT_ERROR(nanomsgsrc, RESOURCE, NOT_FOUND, ("URI starts with the wrong prefix"), ("URI: %s , expected prefix: \"" PROTOCOL_PREFIX "\"", nanomsgsrc->uri));
		return FALSE;
	}
	
	/* Get the actual nanomsg URI, without the prefix */
	actual_uri = PROTOCOLSTR_REMOVE_PREFIX(nanomsgsrc->uri);
	GST_DEBUG_OBJECT(nanomsgsrc, "URI without the prefix: %s", actual_uri);

	/* Cleanup any existing sockets before initializing new ones */
	gst_nanomsgsrc_shutdown_sockets(nanomsgsrc);


	/* Set up the control pipe file descriptors */
	if (G_UNLIKELY(pipe(nanomsgsrc->ctrl_fds) < 0))
	{
		GST_ERROR_OBJECT(nanomsgsrc, "could not create control pipe: %s", strerror(errno));
		goto failure;
	}


	/* The actual SP socket setup */

	/* Create a SP socket, using the currently configured protocol */
	if (G_UNLIKELY((nanomsgsrc->main_fd = nn_socket(AF_SP, nanomsgsrc->protocol)) < 0))
	{
		GST_ERROR_OBJECT(nanomsgsrc, "could not create SP socket: %s", strerror(errno));
		goto failure;
	}

	/* Configure the socket with the given URI */
	rc = 0;
	switch (nanomsgsrc->protocol)
	{
		case NN_PULL:
			rc = nn_bind(nanomsgsrc->main_fd, actual_uri);
			break;

		case NN_SUB:
			rc = (rc < 0) ? rc : nn_setsockopt(nanomsgsrc->main_fd, NN_SUB, NN_SUB_SUBSCRIBE, (nanomsgsrc->subscription_topic != NULL ? nanomsgsrc->subscription_topic : ""), 0);
			rc = (rc < 0) ? rc : nn_connect(nanomsgsrc->main_fd, actual_uri);
			break;

		default:
			GST_ERROR_OBJECT(nanomsgsrc, "invalid protocol value %d", nanomsgsrc->protocol);
			g_assert_not_reached();
	}

	if (G_UNLIKELY(rc < 0))
	{
		GST_ERROR_OBJECT(nanomsgsrc, "could not configure the SP socket: %s", strerror(errno));
		goto failure;
	}

	/* Retrieve the watch FD for use with poll() */
	if (G_UNLIKELY(nn_getsockopt(nanomsgsrc->main_fd, NN_SOL_SOCKET, NN_RCVFD, (char*)&(nanomsgsrc->watch_fd), &watch_fd_size)) < 0)
	{
		GST_ERROR_OBJECT(nanomsgsrc, "could not retrieve watch file descriptor: %s", strerror(errno));
		goto failure;
	}


	/* Misc settings */

	if (G_UNLIKELY(!gst_nanomsgsrc_update_rcvbufsize(nanomsgsrc, nanomsgsrc->rcvbufsize)))
		goto failure;

	{
		int ipv4only = nanomsgsrc->ipv4only ? 1 : 0;
		if (G_UNLIKELY(nn_setsockopt(nanomsgsrc->main_fd, NN_SOL_SOCKET, NN_IPV4ONLY, (char const*)&(ipv4only), sizeof(ipv4only))) < 0)
		{
			GST_ERROR_OBJECT(nanomsgsrc, "could not configure IPV4ONLY flag: %s", strerror(errno));
			goto failure;
		}
	}


	/* Make sure flushing is disabled in the beginning */
	nanomsgsrc->flushing = FALSE;


	/* All done */
	GST_DEBUG_OBJECT(nanomsgsrc, "initialized SP socket with URI %s", actual_uri);

	return TRUE;


failure:
	gst_nanomsgsrc_shutdown_sockets(nanomsgsrc);
	return FALSE;
}
Esempio n. 9
0
int main (int argc, const char *argv[])
{
    int rc;
    int sb;
    int sc;
    int sb2;
    int opt;
    size_t sz;
    int i;
    char any_address[128];

    test_addr_from (socket_address, "ws", "127.0.0.1",
            get_test_port (argc, argv));

    test_addr_from (any_address, "ws", "*",
            get_test_port (argc, argv));

    /*  Try closing bound but unconnected socket. */
    sb = test_socket (AF_SP, NN_PAIR);
    test_bind (sb, any_address);
    test_close (sb);

    /*  Try closing a TCP socket while it not connected. At the same time
        test specifying the local address for the connection. */
    sc = test_socket (AF_SP, NN_PAIR);
    test_connect (sc, socket_address);
    test_close (sc);

    /*  Open the socket anew. */
    sc = test_socket (AF_SP, NN_PAIR);

    /*  Check socket options. */
    sz = sizeof (opt);
    rc = nn_getsockopt (sc, NN_WS, NN_WS_MSG_TYPE, &opt, &sz);
    errno_assert (rc == 0);
    nn_assert (sz == sizeof (opt));
    nn_assert (opt == NN_WS_MSG_TYPE_BINARY);

    /*  Default port 80 should be assumed if not explicitly declared. */
    rc = nn_connect (sc, "ws://127.0.0.1");
    errno_assert (rc >= 0);

    /*  Try using invalid address strings. */
    rc = nn_connect (sc, "ws://*:");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "ws://*:1000000");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "ws://*:some_port");
    nn_assert (rc < 0);
    rc = nn_connect (sc, "ws://eth10000;127.0.0.1:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == ENODEV);

    rc = nn_bind (sc, "ws://127.0.0.1:");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_bind (sc, "ws://127.0.0.1:1000000");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_bind (sc, "ws://eth10000:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == ENODEV);

    rc = nn_connect (sc, "ws://:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "ws://-hostname:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "ws://abc.123.---.#:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "ws://[::1]:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "ws://abc.123.:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "ws://abc...123:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "ws://.123:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);

    test_close (sc);

    sb = test_socket (AF_SP, NN_PAIR);
    test_bind (sb, socket_address);
    sc = test_socket (AF_SP, NN_PAIR);
    test_connect (sc, socket_address);

    /*  Ping-pong test. */
    for (i = 0; i != 100; ++i) {

        test_send (sc, "ABC");
        test_recv (sb, "ABC");

        test_send (sb, "DEF");
        test_recv (sc, "DEF");
    }

    /*  Batch transfer test. */
    for (i = 0; i != 100; ++i) {
        test_send (sc, "0123456789012345678901234567890123456789");
    }
    for (i = 0; i != 100; ++i) {
        test_recv (sb, "0123456789012345678901234567890123456789");
    }

    test_close (sc);
    test_close (sb);

    /*  Test two sockets binding to the same address. */
    sb = test_socket (AF_SP, NN_PAIR);
    test_bind (sb, socket_address);
    sb2 = test_socket (AF_SP, NN_PAIR);

    rc = nn_bind (sb2, socket_address);
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EADDRINUSE);
    test_close(sb);
    test_close(sb2);

    /*  Test that NN_RCVMAXSIZE can be -1, but not lower */
    sb = test_socket (AF_SP, NN_PAIR);
    opt = -1;
    rc = nn_setsockopt (sb, NN_SOL_SOCKET, NN_RCVMAXSIZE, &opt, sizeof (opt));
    nn_assert (rc >= 0);
    opt = -2;
    rc = nn_setsockopt (sb, NN_SOL_SOCKET, NN_RCVMAXSIZE, &opt, sizeof (opt));
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    test_close (sb);

    /*  Test NN_RCVMAXSIZE limit */
    sb = test_socket (AF_SP, NN_PAIR);
    test_bind (sb, socket_address);
    sc = test_socket (AF_SP, NN_PAIR);
    test_connect (sc, socket_address);
    opt = 1000;
    test_setsockopt (sc, NN_SOL_SOCKET, NN_SNDTIMEO, &opt, sizeof (opt));
    nn_assert (opt == 1000);
    opt = 1000;
    test_setsockopt (sb, NN_SOL_SOCKET, NN_RCVTIMEO, &opt, sizeof (opt));
    nn_assert (opt == 1000);
    opt = 4;
    test_setsockopt (sb, NN_SOL_SOCKET, NN_RCVMAXSIZE, &opt, sizeof (opt));
    test_send (sc, "ABC");
    test_recv (sb, "ABC");
    test_send (sc, "ABCD");
    test_recv (sb, "ABCD");
    test_send (sc, "ABCDE");
    test_drop (sb, ETIMEDOUT);

    /*  Increase the size limit, reconnect, then try sending again. The reason a
        reconnect is necessary is because after a protocol violation, the
        connecting socket will not continue automatic reconnection attempts. */
    opt = 5;
    test_setsockopt (sb, NN_SOL_SOCKET, NN_RCVMAXSIZE, &opt, sizeof (opt));
    test_connect (sc, socket_address);
    test_send (sc, "ABCDE");
    test_recv (sb, "ABCDE");
    test_close (sb);
    test_close (sc);

    test_text ();

    /*  Test closing a socket that is waiting to connect. */
    sc = test_socket (AF_SP, NN_PAIR);
    test_connect (sc, socket_address);
    nn_sleep (100);
    test_close (sc);

    return 0;
}
void *subscriber(void *args)
{
    pthread_detach(pthread_self());
    srand(time(NULL));

    pubsub_info *info = (pubsub_info *) args;
    char *ip = info->broker_ip;
    int sub_port = info->send_port;
    int report_port = info->recv_port;
    int num_channels = info->num_channels;
    char **channels = info->channels;
    int verbose = info->verbose;

    char sub_addr[SIZE32], report_addr[SIZE32];
    memset(sub_addr, '\0', SIZE32);
    memset(report_addr, '\0', SIZE32);
    sprintf(sub_addr, "tcp://%s:%d", ip, sub_port);
    sprintf(report_addr, "tcp://%s:%d", ip, report_port);

    int rc, opt = 1;
    int sub_fd, report_fd;

    sub_fd = nn_socket(AF_SP, NN_SUB);
    assert(sub_fd != -1);
    rc = nn_connect(sub_fd, sub_addr);
    assert(rc >= 0);

    report_fd = nn_socket(AF_SP, NN_PUSH);
    assert(report_fd != -1);
    rc = nn_setsockopt(report_fd, NN_TCP, NN_TCP_NODELAY, &opt, sizeof(opt));
    assert(rc == 0);
    rc = nn_connect(report_fd, report_addr);
    assert(rc >= 0);

    int i;
    for (i = 0; i < num_channels; i++) {
        rc = nn_setsockopt(sub_fd, NN_SUB, NN_SUB_SUBSCRIBE, channels[i], strlen(channels[i]));
        assert(rc >= 0);
    }

    int bytes = -1, messages = 0;
    INT64 now, last;
    get_timestamp(&last);
    while (1) {
        char *buf = NULL;
        bytes = nn_recv(sub_fd, &buf, NN_MSG, 0);
        assert (bytes >= 0);
        nn_freemsg (buf);

        messages++;
        get_timestamp(&now);
        if (now - last > 1000) {
            if (verbose) {
                printf("%d msg/sec\n", messages);
            }
            char *msg = (char *) malloc(SIZE16);
            int len = sprintf(msg, "%s %d", "metrics", messages);
            msg[len++] = '\0';
            bytes = nn_send(report_fd, msg, len, 0);
            assert(bytes == len);
            last = now;
            messages = 0;
            free(msg);
        }
    }
    nn_shutdown(sub_fd, 0);
    nn_shutdown(report_fd, 0);

    return NULL;
}
Esempio n. 11
0
int main ()
{
    int rc;
    int sb;
    int sc;
    int i;
    char buf [3];

    /*  Create a simple topology. */
    sc = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sc != -1);
    rc = nn_connect (sc, SOCKET_ADDRESS);
    errno_assert (rc >= 0);
    sb = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sb != -1);
    rc = nn_bind (sb, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    /*  Try a duplicate bind. It should fail. */
    rc = nn_bind (sc, SOCKET_ADDRESS);
    nn_assert (rc < 0 && errno == EADDRINUSE);

    /*  Ping-pong test. */
    for (i = 0; i != 100; ++i) {

        rc = nn_send (sc, "ABC", 3, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);

        rc = nn_recv (sb, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);

        rc = nn_send (sb, "DEFG", 4, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 4);

        rc = nn_recv (sc, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 4);
    }

    /*  Batch transfer test. */
    for (i = 0; i != 100; ++i) {

        rc = nn_send (sc, "XYZ", 3, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);

        rc = nn_recv (sb, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);
    }

    rc = nn_close (sc);
    errno_assert (rc == 0);
    rc = nn_close (sb);
    errno_assert (rc == 0);

    return 0;
}
int main(int argc, char *argv[])
{
    char *broker_ip = strdup("127.0.0.1");
    int recv_port = 5562;
    int send_port = 5561;

    int run_seconds = 10;
    int num_channels = 50;
    int msg_size = 20;
    int num_clients = get_cpu_count() / 2;
    num_clients = num_clients > 0 ? num_clients : 1;

    int verbose = 0;

    int opt;
    while ((opt = getopt(argc, argv, "b:r:s:t:S:C:vh")) != -1) {
        switch (opt) {
        case 'b':
            free(broker_ip);
            broker_ip = strdup(optarg);
            break;
        case 'r':
            recv_port = atoi(optarg);
            break;
        case 's':
            send_port = atoi(optarg);
            break;
        case 't':
            run_seconds = atoi(optarg);
            break;
        case 'S':
            msg_size = atoi(optarg);
            break;
        case 'C':
            num_clients = atoi(optarg);
            break;
        case 'v':
            verbose = 1;
            break;
        case 'h':
            usage();
            exit(EXIT_SUCCESS);
        default:
            fprintf(stderr, "Try 'nanomsg_pubsub_cliet -h' for more information");
            exit(EXIT_FAILURE);
        }
    }

    int i;
    char **channels = (char **) malloc(sizeof(char *) * num_channels);
    for (i = 0; i < num_channels; i++) {
        channels[i] = (char *) malloc(SIZE8);
        memset(channels[i], '\0', SIZE8);
        sprintf(channels[i], "%d", i);
    }
    pubsub_info *info = (pubsub_info *) malloc(sizeof(pubsub_info));
    info->broker_ip = broker_ip;
    info->recv_port = recv_port;
    info->send_port = send_port;
    info->msg_size = msg_size;
    info->num_channels = num_channels;
    info->channels = channels;
    info->verbose = verbose;

    pthread_t *pub_threads = (pthread_t *) malloc(sizeof(pthread_t) * num_clients);
    for (i = 0; i < num_clients; i++) {
        pthread_create(&pub_threads[i], NULL, publisher, (void *)info);
    }

    sleep(1);

    pthread_t *sub_threads = (pthread_t *) malloc(sizeof(pthread_t) * num_clients);
    for (i = 0; i < num_clients; i++) {
        pthread_create(&sub_threads[i], NULL, subscriber, (void *)info);
    }

    int rc;
    int metrics_fd;
    metrics_fd = nn_socket(AF_SP, NN_SUB);
    assert(metrics_fd != -1);
    char sub_addr[SIZE32];
    rc = sprintf(sub_addr, "tcp://%s:%d", broker_ip, send_port);
    sub_addr[rc] = '\0';
    rc = nn_connect(metrics_fd, sub_addr);
    assert(rc >= 0);
    rc = nn_setsockopt(metrics_fd, NN_SUB, NN_SUB_SUBSCRIBE, "metrics", 7);
    assert(rc == 0);

    INT64 start, now;
    get_timestamp(&start);
    int *stats = (int *) malloc(sizeof(int) * num_clients * run_seconds);
    int cnt = 0;
    while (1) {
        get_timestamp(&now);
        if (now - start > run_seconds * 1000) {
            break;
        }
        char *msg = NULL;

        int bytes = nn_recv(metrics_fd, &msg, NN_MSG, 0);
        assert (bytes >= 0);
        char *start = strchr(msg, ' ') + 1;
        stats[cnt++] = atoi(start);

        nn_freemsg (msg);
    }
    printf("%d median msg/sec\n", get_median(stats, cnt));

    free(broker_ip);
    free(info);
    free(stats);
    printf("done!\n");
    return 0;
}
Esempio n. 13
0
int ss_nn_queue_create(json_object* items, nn_queue_t* nn_queue) {
    // int rv;
    int so_value;
    char* value = NULL;
    
    memset(nn_queue, 0, sizeof(nn_queue_t));
    
    value = ss_json_string_get(items, "nm_url");
    if (value == NULL) {
        fprintf(stderr, "nm_url is null\n");
        goto error_out;
    }
    strlcpy(nn_queue->url, value, sizeof(nn_queue->url));
    je_free(value);
    
    value = ss_json_string_get(items, "nm_type");
    if (value == NULL) {
        fprintf(stderr, "nm_type is null\n");
        goto error_out;
    }
    if      (!strcasecmp(value, "BUS"))        nn_queue->type = NN_BUS;
    else if (!strcasecmp(value, "PAIR"))       nn_queue->type = NN_PAIR;
    else if (!strcasecmp(value, "PUSH"))       nn_queue->type = NN_PUSH;
    else if (!strcasecmp(value, "PULL"))       nn_queue->type = NN_PULL;
    else if (!strcasecmp(value, "PUB"))        nn_queue->type = NN_PUB;
    else if (!strcasecmp(value, "SUB"))        nn_queue->type = NN_SUB;
    else if (!strcasecmp(value, "REQ"))        nn_queue->type = NN_REQ;
    else if (!strcasecmp(value, "REP"))        nn_queue->type = NN_REP;
    else if (!strcasecmp(value, "SURVEYOR"))   nn_queue->type = NN_SURVEYOR;
    else if (!strcasecmp(value, "RESPONDENT")) nn_queue->type = NN_RESPONDENT;
    else {
        fprintf(stderr, "unknown nm_type %s\n", value);
        goto error_out;
    }
    je_free(value);
    
    value = ss_json_string_get(items, "nm_format");
    if      (!strcasecmp(value, "metadata")) nn_queue->format = NN_FORMAT_METADATA;
    else if (!strcasecmp(value, "packet"))   nn_queue->format = NN_FORMAT_PACKET;
    else {
        fprintf(stderr, "unknown nm_format %s\n", value);
        goto error_out;
    }
    je_free(value);
    
    nn_queue->conn = nn_socket(AF_SP, nn_queue->type);
    if (nn_queue->conn < 0) {
        fprintf(stderr, "could not allocate nm queue socket: %s\n", nn_strerror(nn_errno()));
        goto error_out;
    }
    so_value = 0;
    /*
    rv = nn_setsockopt(nn_queue->conn, NN_SOL_SOCKET, NN_IPV4ONLY, &so_value, sizeof(so_value));
    if (rv != 0) {
        fprintf(stderr, "could not enable nm ipv6 support: %s\n", nn_strerror(nn_errno()));
        goto error_out;
    }
    */
    nn_queue->remote_id = nn_connect(nn_queue->conn, nn_queue->url);
    if (nn_queue->remote_id < 0) {
        fprintf(stderr, "could not connect nm queue socket: %s\n", nn_strerror(nn_errno()));
        goto error_out;
    }
    
    fprintf(stderr, "created nm_queue type %s url %s\n", ss_nn_queue_type_dump(nn_queue->type), nn_queue->url);
    return 0;
    
    error_out:
    if (nn_queue) ss_nn_queue_destroy(nn_queue);
    if (value) je_free(value);
    return -1;
}
Esempio n. 14
0
/* Transport implementation */
int janus_nanomsg_init(janus_transport_callbacks *callback, const char *config_path) {
	if(g_atomic_int_get(&stopping)) {
		/* Still stopping from before */
		return -1;
	}
	if(callback == NULL || config_path == NULL) {
		/* Invalid arguments */
		return -1;
	}

	/* This is the callback we'll need to invoke to contact the gateway */
	gateway = callback;

	/* Read configuration */
	char filename[255];
	g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_NANOMSG_PACKAGE);
	JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
	janus_config *config = janus_config_parse(filename);
	if(config != NULL) {
		/* Handle configuration */
		janus_config_print(config);

		janus_config_item *item = janus_config_get_item_drilldown(config, "general", "json");
		if(item && item->value) {
			/* Check how we need to format/serialize the JSON output */
			if(!strcasecmp(item->value, "indented")) {
				/* Default: indented, we use three spaces for that */
				json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER;
			} else if(!strcasecmp(item->value, "plain")) {
				/* Not indented and no new lines, but still readable */
				json_format = JSON_INDENT(0) | JSON_PRESERVE_ORDER;
			} else if(!strcasecmp(item->value, "compact")) {
				/* Compact, so no spaces between separators */
				json_format = JSON_COMPACT | JSON_PRESERVE_ORDER;
			} else {
				JANUS_LOG(LOG_WARN, "Unsupported JSON format option '%s', using default (indented)\n", item->value);
				json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER;
			}
		}

		/* Check if we need to send events to handlers */
		janus_config_item *events = janus_config_get_item_drilldown(config, "general", "events");
		if(events != NULL && events->value != NULL)
			notify_events = janus_is_true(events->value);
		if(!notify_events && callback->events_is_enabled()) {
			JANUS_LOG(LOG_WARN, "Notification of events to handlers disabled for %s\n", JANUS_NANOMSG_NAME);
		}

		/* First of all, initialize the pipeline for writeable notifications */
		write_nfd[0] = nn_socket(AF_SP, NN_PULL);
		write_nfd[1] = nn_socket(AF_SP, NN_PUSH);
		if(nn_bind(write_nfd[0], "inproc://janus") < 0) {
			JANUS_LOG(LOG_WARN, "Error configuring internal Nanomsg pipeline... %d (%s)\n", errno, nn_strerror(errno));
			return -1;	/* No point in keeping the plugin loaded */
		}
		if(nn_connect(write_nfd[1], "inproc://janus") < 0) {
			JANUS_LOG(LOG_WARN, "Error configuring internal Nanomsg pipeline...%d (%s)\n", errno, nn_strerror(errno));
			return -1;	/* No point in keeping the plugin loaded */
		}

		/* Setup the Janus API Nanomsg server(s) */
		item = janus_config_get_item_drilldown(config, "general", "enabled");
		if(!item || !item->value || !janus_is_true(item->value)) {
			JANUS_LOG(LOG_WARN, "Nanomsg server disabled (Janus API)\n");
		} else {
			item = janus_config_get_item_drilldown(config, "general", "address");
			const char *address = item && item->value ? item->value : NULL;
			item = janus_config_get_item_drilldown(config, "general", "mode");
			const char *mode = item && item->value ? item->value : NULL;
			if(mode == NULL)
				mode = "bind";
			nfd = nn_socket(AF_SP, NN_PAIR);
			if(nfd < 0) {
				JANUS_LOG(LOG_ERR, "Error creating Janus API Nanomsg socket: %d (%s)\n", errno, nn_strerror(errno));
			} else {
				if(!strcasecmp(mode, "bind")) {
					/* Bind to this address */
					nfd_addr = nn_bind(nfd, address);
					if(nfd_addr < 0) {
						JANUS_LOG(LOG_ERR, "Error binding Janus API Nanomsg socket to address '%s': %d (%s)\n",
							address, errno, nn_strerror(errno));
						nn_close(nfd);
						nfd = -1;
					}
				} else if(!strcasecmp(mode, "connect")) {
					/* Connect to this address */
					nfd_addr = nn_connect(nfd, address);
					if(nfd_addr < 0) {
						JANUS_LOG(LOG_ERR, "Error connecting Janus API Nanomsg socket to address '%s': %d (%s)\n",
							address, errno, nn_strerror(errno));
						nn_close(nfd);
						nfd = -1;
					}
				} else {
					/* Unsupported mode */
					JANUS_LOG(LOG_ERR, "Unsupported mode '%s'\n", mode);
					nn_close(nfd);
					nfd = -1;
				}
			}
		}
		/* Do the same for the Admin API, if enabled */
		item = janus_config_get_item_drilldown(config, "admin", "admin_enabled");
		if(!item || !item->value || !janus_is_true(item->value)) {
			JANUS_LOG(LOG_WARN, "Nanomsg server disabled (Admin API)\n");
		} else {
			item = janus_config_get_item_drilldown(config, "admin", "admin_address");
			const char *address = item && item->value ? item->value : NULL;
			item = janus_config_get_item_drilldown(config, "general", "admin_mode");
			const char *mode = item && item->value ? item->value : NULL;
			if(mode == NULL)
				mode = "bind";
			admin_nfd = nn_socket(AF_SP, NN_PAIR);
			if(admin_nfd < 0) {
				JANUS_LOG(LOG_ERR, "Error creating Admin API Nanomsg socket: %d (%s)\n", errno, nn_strerror(errno));
			} else {
				if(!strcasecmp(mode, "bind")) {
					/* Bind to this address */
					admin_nfd_addr = nn_bind(admin_nfd, address);
					if(admin_nfd_addr < 0) {
						JANUS_LOG(LOG_ERR, "Error binding Admin API Nanomsg socket to address '%s': %d (%s)\n",
							address, errno, nn_strerror(errno));
						nn_close(admin_nfd);
						admin_nfd = -1;
					}
				} else if(!strcasecmp(mode, "connect")) {
					/* Connect to this address */
					admin_nfd_addr = nn_connect(admin_nfd, address);
					if(admin_nfd_addr < 0) {
						JANUS_LOG(LOG_ERR, "Error connecting Admin API Nanomsg socket to address '%s': %d (%s)\n",
							address, errno, nn_strerror(errno));
						nn_close(admin_nfd);
						admin_nfd = -1;
					}
				} else {
					/* Unsupported mode */
					JANUS_LOG(LOG_ERR, "Unsupported mode '%s'\n", mode);
					nn_close(admin_nfd);
					admin_nfd = -1;
				}
			}
		}
	}
	janus_config_destroy(config);
	config = NULL;
	if(nfd < 0 && admin_nfd < 0) {
		JANUS_LOG(LOG_WARN, "No Nanomsg server started, giving up...\n");
		return -1;	/* No point in keeping the plugin loaded */
	}

	/* Create the clients */
	memset(&client, 0, sizeof(janus_nanomsg_client));
	if(nfd > -1) {
		client.admin = FALSE;
		client.messages = g_async_queue_new();
		/* Create a transport instance as well */
		client.ts = janus_transport_session_create(&client, NULL);
		/* Notify handlers about this new transport */
		if(notify_events && gateway->events_is_enabled()) {
			json_t *info = json_object();
			json_object_set_new(info, "event", json_string("created"));
			json_object_set_new(info, "admin_api", json_false());
			json_object_set_new(info, "socket", json_integer(nfd));
			gateway->notify_event(&janus_nanomsg_transport, client.ts, info);
		}
	}
	memset(&admin_client, 0, sizeof(janus_nanomsg_client));
	if(admin_nfd > -1) {
		admin_client.admin = TRUE;
		admin_client.messages = g_async_queue_new();
		/* Create a transport instance as well */
		admin_client.ts = janus_transport_session_create(&admin_client, NULL);
		/* Notify handlers about this new transport */
		if(notify_events && gateway->events_is_enabled()) {
			json_t *info = json_object();
			json_object_set_new(info, "event", json_string("created"));
			json_object_set_new(info, "admin_api", json_true());
			json_object_set_new(info, "socket", json_integer(admin_nfd));
			gateway->notify_event(&janus_nanomsg_transport, admin_client.ts, info);
		}
	}

	/* Start the Nanomsg service thread */
	GError *error = NULL;
	nanomsg_thread = g_thread_try_new("nanomsg thread", &janus_nanomsg_thread, NULL, &error);
	if(!nanomsg_thread) {
		g_atomic_int_set(&initialized, 0);
		JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Nanomsg thread...\n", error->code, error->message ? error->message : "??");
		return -1;
	}

	/* Done */
	g_atomic_int_set(&initialized, 1);
	JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_NANOMSG_NAME);
	return 0;
}
Esempio n. 15
0
 void NanoSocket::Connect(const std::string& address) throw()
 {
   if (nn_connect(m_socket, address.c_str()) < 0)
     throw NanoException{};
 }
Esempio n. 16
0
File: tcp.c Progetto: Droppe/nanomsg
int main ()
{
    int rc;
    int sb;
    int sc;
    int i;
    char buf [3];
    int opt;
    size_t sz;

    /*  Try closing bound but unconnected socket. */
#if 0
    sb = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sb >= 0);
    rc = nn_bind (sb, SOCKET_ADDRESS);
    errno_assert (rc > 0);
    rc = nn_close (sb);
    errno_assert (rc == 0);
#endif

    /*  Try closing a TCP socket while it not connected. At the same time
        test specifying the local address for connection. */
    sc = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sc != -1);
    rc = nn_connect (sc, "tcp://127.0.0.1;127.0.0.1:5555");
    errno_assert (rc >= 0);
    rc = nn_close (sc);
    errno_assert (rc == 0);

    /*  Open the socket anew. */
    sc = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sc != -1);

    /*  Check NODELAY socket option. */
    sz = sizeof (opt);
    rc = nn_getsockopt (sc, NN_TCP, NN_TCP_NODELAY, &opt, &sz);
    errno_assert (rc == 0);
    nn_assert (sz == sizeof (opt));
    nn_assert (opt == 0);
    opt = 2;
    rc = nn_setsockopt (sc, NN_TCP, NN_TCP_NODELAY, &opt, sizeof (opt));
    nn_assert (rc < 0 && nn_errno () == EINVAL);
    opt = 1;
    rc = nn_setsockopt (sc, NN_TCP, NN_TCP_NODELAY, &opt, sizeof (opt));
    errno_assert (rc == 0);
    sz = sizeof (opt);
    rc = nn_getsockopt (sc, NN_TCP, NN_TCP_NODELAY, &opt, &sz);
    errno_assert (rc == 0);
    nn_assert (sz == sizeof (opt));
    nn_assert (opt == 1);

    /*  Try using invalid address strings. */
    rc = nn_connect (sc, "tcp://*:");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "tcp://*:1000000");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_connect (sc, "tcp://*:some_port");
    nn_assert (rc < 0);
    rc = nn_connect (sc, "tcp://eth10000;127.0.0.1:5555");
    nn_assert (rc < 0);    
    errno_assert (nn_errno () == ENODEV);
    rc = nn_bind (sc, "tcp://127.0.0.1:");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_bind (sc, "tcp://127.0.0.1:1000000");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == EINVAL);
    rc = nn_bind (sc, "tcp://eth10000:5555");
    nn_assert (rc < 0);
    errno_assert (nn_errno () == ENODEV);

    /*  Connect correctly. Do so before binding the peer socket. */
    rc = nn_connect (sc, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    /*  Leave enough time for at least on re-connect attempt. */
    nn_sleep (200);

    sb = nn_socket (AF_SP, NN_PAIR);
    errno_assert (sb != -1);
    rc = nn_bind (sb, SOCKET_ADDRESS);
    errno_assert (rc >= 0);

    /*  Ping-pong test. */
    for (i = 0; i != 100; ++i) {

        rc = nn_send (sc, "ABC", 3, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);

        rc = nn_recv (sb, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);

        rc = nn_send (sb, "DEF", 3, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);

        rc = nn_recv (sc, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 3);
    }

    /*  Batch transfer test. */
    for (i = 0; i != 100; ++i) {
        rc = nn_send (sc, "0123456789012345678901234567890123456789", 40, 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 40);
    }
    for (i = 0; i != 100; ++i) {
        rc = nn_recv (sb, buf, sizeof (buf), 0);
        errno_assert (rc >= 0);
        nn_assert (rc == 40);
    }

    rc = nn_close (sc);
    errno_assert (rc == 0);
    rc = nn_close (sb);
    errno_assert (rc == 0);

    return 0;
}