示例#1
0
文件: zcert.c 项目: drmplanet/kdlenv
void
zcert_apply (zcert_t *self, void *zocket)
{
    assert (self);
#if (ZMQ_VERSION_MAJOR == 4)
    if (zsys_has_curve ()) {
        zsocket_set_curve_secretkey_bin (zocket, self->secret_key);
        zsocket_set_curve_publickey_bin (zocket, self->public_key);
    }
#endif
}
示例#2
0
void MessageProcessor::init(int port, zcert_t* transportKey)
{
    if (port == 0) {
        OT_FAIL;
    }
    if (!zsys_has_curve()) {
        Log::vError("Error: libzmq has no libsodium support");
        OT_FAIL;
    }
    zstr_sendx(zmqAuth_, "CURVE", CURVE_ALLOW_ANY, NULL);
    zsock_wait(zmqAuth_);
    zsock_set_zap_domain(zmqSocket_, "global");
    zsock_set_curve_server(zmqSocket_, 1);
    zcert_apply(transportKey, zmqSocket_);
    zsock_bind(zmqSocket_, "tcp://*:%d", port);
}
示例#3
0
文件: zcert.c 项目: PSG-Luna/czmq
zcert_t *
zcert_new (void)
{
    byte public_key [32] = { 0 };
    byte secret_key [32] = { 0 };

#if (ZMQ_VERSION_MAJOR == 4)
    if (zsys_has_curve ()) {
        char public_txt [41];
        char secret_txt [41];
        int rc = zmq_curve_keypair (public_txt, secret_txt);
        if (rc != 0)
            return NULL;
        zmq_z85_decode (public_key, public_txt);
        zmq_z85_decode (secret_key, secret_txt);
    }
#endif
    return zcert_new_from (public_key, secret_key);
}
示例#4
0
void
zauth_test (bool verbose)
{
    printf (" * zauth: ");
#if (ZMQ_VERSION_MAJOR == 4)
    if (verbose)
        printf ("\n");

    //  @selftest
    //  Create temporary directory for test files
#   define TESTDIR ".test_zauth"
    zsys_dir_create (TESTDIR);

    //  Check there's no authentication
    zsock_t *server = zsock_new (ZMQ_PUSH);
    assert (server);
    zsock_t *client = zsock_new (ZMQ_PULL);
    assert (client);
    bool success = s_can_connect (&server, &client);
    assert (success);

    //  Install the authenticator
    zactor_t *auth = zactor_new (zauth, NULL);
    assert (auth);
    if (verbose) {
        zstr_sendx (auth, "VERBOSE", NULL);
        zsock_wait (auth);
    }
    //  Check there's no authentication on a default NULL server
    success = s_can_connect (&server, &client);
    assert (success);

    //  When we set a domain on the server, we switch on authentication
    //  for NULL sockets, but with no policies, the client connection
    //  will be allowed.
    zsock_set_zap_domain (server, "global");
    success = s_can_connect (&server, &client);
    assert (success);

    //  Blacklist 127.0.0.1, connection should fail
    zsock_set_zap_domain (server, "global");
    zstr_sendx (auth, "DENY", "127.0.0.1", NULL);
    zsock_wait (auth);
    success = s_can_connect (&server, &client);
    assert (!success);

    //  Whitelist our address, which overrides the blacklist
    zsock_set_zap_domain (server, "global");
    zstr_sendx (auth, "ALLOW", "127.0.0.1", NULL);
    zsock_wait (auth);
    success = s_can_connect (&server, &client);
    assert (success);

    //  Try PLAIN authentication
    zsock_set_plain_server (server, 1);
    zsock_set_plain_username (client, "admin");
    zsock_set_plain_password (client, "Password");
    success = s_can_connect (&server, &client);
    assert (!success);

    FILE *password = fopen (TESTDIR "/password-file", "w");
    assert (password);
    fprintf (password, "admin=Password\n");
    fclose (password);
    zsock_set_plain_server (server, 1);
    zsock_set_plain_username (client, "admin");
    zsock_set_plain_password (client, "Password");
    zstr_sendx (auth, "PLAIN", TESTDIR "/password-file", NULL);
    zsock_wait (auth);
    success = s_can_connect (&server, &client);
    assert (success);

    zsock_set_plain_server (server, 1);
    zsock_set_plain_username (client, "admin");
    zsock_set_plain_password (client, "Bogus");
    success = s_can_connect (&server, &client);
    assert (!success);

    if (zsys_has_curve ()) {
        //  Try CURVE authentication
        //  We'll create two new certificates and save the client public
        //  certificate on disk; in a real case we'd transfer this securely
        //  from the client machine to the server machine.
        zcert_t *server_cert = zcert_new ();
        assert (server_cert);
        zcert_t *client_cert = zcert_new ();
        assert (client_cert);
        char *server_key = zcert_public_txt (server_cert);

        //  Test without setting-up any authentication
        zcert_apply (server_cert, server);
        zcert_apply (client_cert, client);
        zsock_set_curve_server (server, 1);
        zsock_set_curve_serverkey (client, server_key);
        success = s_can_connect (&server, &client);
        assert (!success);

        //  Test CURVE_ALLOW_ANY
        zcert_apply (server_cert, server);
        zcert_apply (client_cert, client);
        zsock_set_curve_server (server, 1);
        zsock_set_curve_serverkey (client, server_key);
        zstr_sendx (auth, "CURVE", CURVE_ALLOW_ANY, NULL);
        zsock_wait (auth);
        success = s_can_connect (&server, &client);
        assert (success);

        //  Test full client authentication using certificates
        zcert_apply (server_cert, server);
        zcert_apply (client_cert, client);
        zsock_set_curve_server (server, 1);
        zsock_set_curve_serverkey (client, server_key);
        zcert_save_public (client_cert, TESTDIR "/mycert.txt");
        zstr_sendx (auth, "CURVE", TESTDIR, NULL);
        zsock_wait (auth);
        success = s_can_connect (&server, &client);
        assert (success);

        zcert_destroy (&server_cert);
        zcert_destroy (&client_cert);
    }
    //  Remove the authenticator and check a normal connection works
    zactor_destroy (&auth);
    success = s_can_connect (&server, &client);
    assert (success);

    zsock_destroy (&client);
    zsock_destroy (&server);

    //  Delete all test files
    zdir_t *dir = zdir_new (TESTDIR, NULL);
    assert (dir);
    zdir_remove (dir, true);
    zdir_destroy (&dir);
    //  @end
#endif
    printf ("OK\n");
}
示例#5
0
JNIEXPORT jboolean JNICALL
Java_org_zeromq_czmq_Zsys__1_1hasCurve (JNIEnv *env, jclass c)
{
    jboolean has_curve_ = (jboolean) zsys_has_curve ();
    return has_curve_;
}
void ZeroMQEngine::Initialize(const string endPoint, const string instanceName, const string instanceID)
{
    zcert_t* localCertificate = nullptr;

    // Handle common security initialization for server and client instances
    if (SecurityEnabled())
    {
        if (!zsys_has_curve())
            throw runtime_error("Failed to locate needed curve security libraries, cannot initialize ZeroMQ security");
        
        string localCertDirectory = CURVECERTLOCALDIR "/";
        string publicCertFileName;
        string privateCertFileName;
        
        // Make sure certificate store directories exist
        if (zsys_dir_create(CURVECERTLOCALDIR) != 0)
            throw runtime_error("Failed to create local curve security store, cannot initialize ZeroMQ security");

        if (zsys_dir_create(CURVECERTREMOTEDIR) != 0)
            throw runtime_error("Failed to create remote curve security store, cannot initialize ZeroMQ security");
        
        // Derive certificate file names based on engine mode
        if (ServerMode())
        {
            publicCertFileName = localCertDirectory + SVRPUBCERTFILENAME;
            privateCertFileName = localCertDirectory + SVRPVTCERTFILENAME;
        }
        else
        {
            publicCertFileName = localCertDirectory + instanceName + PUBCERTFILENAMEEXT;
            privateCertFileName = localCertDirectory + instanceName + PVTCERTFILENAMEEXT;
        }
        
        // See if private certificate already exists
        if (zsys_file_exists(privateCertFileName.c_str()))
        {
            // Load existing local certificate
            localCertificate = zcert_load(privateCertFileName.c_str());
            
            if (localCertificate == nullptr)
                throw runtime_error("Failed to load local curve certificate, cannot initialize ZeroMQ security");
        }
        else
        {
            // Create a new full certificate (public + private)
            localCertificate = zcert_new();
            
            if (localCertificate == nullptr)
                throw runtime_error("Failed to create local curve certificate, cannot initialize ZeroMQ security");

            zcert_set_meta(localCertificate, "name", instanceName.c_str());
            zcert_set_meta(localCertificate, "id", instanceID.c_str());
            zcert_set_meta(localCertificate, "type", ServerMode() ? "server" : "client");
            
            // Persist certificates for future runs
            if (zcert_save_public(localCertificate, publicCertFileName.c_str()) != 0)
                throw runtime_error("Failed to save local curve public certificate, cannot initialize ZeroMQ security");
            
            if (zcert_save_secret(localCertificate, privateCertFileName.c_str()) != 0)
                throw runtime_error("Failed to save local curve private certificate, cannot initialize ZeroMQ security");
        }        
    }
    
    // Create new ZeroMQ engine instance
    if (ServerMode())
        m_instance = new ZeroMQServer(m_bufferReceivedCallback, SecurityEnabled(), InactiveClientTimeout(), VerboseOutput(), ConnectionID(), localCertificate);
    else
        m_instance = new ZeroMQClient(m_bufferReceivedCallback, SecurityEnabled(), InactiveClientTimeout(), VerboseOutput(), ConnectionID(), localCertificate);

    m_instance->Initialize(endPoint, instanceName, instanceID);

    log_info("\nEstablished ZeroMQ socket [%s]\n", ConnectionID().ToString().c_str());
}
示例#7
0
文件: QmlZsys.cpp 项目: taotetek/czmq
///
//  Returns true if the underlying libzmq supports CURVE security.
//  Uses a heuristic probe according to the version of libzmq being used.
bool QmlZsysAttached::hasCurve () {
    return zsys_has_curve ();
};
示例#8
0
文件: zgossip.c 项目: taotetek/czmq
void
zgossip_test (bool verbose)
{
    printf (" * zgossip: ");
    if (verbose)
        printf ("\n");

    //  @selftest
    //  Test basic client-to-server operation of the protocol
    zactor_t *server = zactor_new (zgossip, "server");
    assert (server);
    if (verbose)
        zstr_send (server, "VERBOSE");
    zstr_sendx (server, "BIND", "inproc://zgossip", NULL);

    zsock_t *client = zsock_new (ZMQ_DEALER);
    assert (client);
    zsock_set_rcvtimeo (client, 2000);
    int rc = zsock_connect (client, "inproc://zgossip");
    assert (rc == 0);

    //  Send HELLO, which gets no message
    zgossip_msg_t *message = zgossip_msg_new ();
    zgossip_msg_set_id (message, ZGOSSIP_MSG_HELLO);
    zgossip_msg_send (message, client);

    //  Send PING, expect PONG back
    zgossip_msg_set_id (message, ZGOSSIP_MSG_PING);
    zgossip_msg_send (message, client);
    zgossip_msg_recv (message, client);
    assert (zgossip_msg_id (message) == ZGOSSIP_MSG_PONG);
    zgossip_msg_destroy (&message);

    zactor_destroy (&server);
    zsock_destroy (&client);

    //  Test peer-to-peer operations
    zactor_t *base = zactor_new (zgossip, "base");
    assert (base);
    if (verbose)
        zstr_send (base, "VERBOSE");
    //  Set a 100msec timeout on clients so we can test expiry
    zstr_sendx (base, "SET", "server/timeout", "100", NULL);
    zstr_sendx (base, "BIND", "inproc://base", NULL);

    zactor_t *alpha = zactor_new (zgossip, "alpha");
    assert (alpha);
    zstr_sendx (alpha, "CONNECT", "inproc://base", NULL);
    zstr_sendx (alpha, "PUBLISH", "inproc://alpha-1", "service1", NULL);
    zstr_sendx (alpha, "PUBLISH", "inproc://alpha-2", "service2", NULL);

    zactor_t *beta = zactor_new (zgossip, "beta");
    assert (beta);
    zstr_sendx (beta, "CONNECT", "inproc://base", NULL);
    zstr_sendx (beta, "PUBLISH", "inproc://beta-1", "service1", NULL);
    zstr_sendx (beta, "PUBLISH", "inproc://beta-2", "service2", NULL);

    //  got nothing
    zclock_sleep (200);

    zstr_send (alpha, "STATUS");
    char *command, *status, *key, *value;

    zstr_recvx (alpha, &command, &key, &value, NULL);
    assert (streq (command, "DELIVER"));
    assert (streq (key, "inproc://alpha-1"));
    assert (streq (value, "service1"));
    zstr_free (&command);
    zstr_free (&key);
    zstr_free (&value);

    zstr_recvx (alpha, &command, &key, &value, NULL);
    assert (streq (command, "DELIVER"));
    assert (streq (key, "inproc://alpha-2"));
    assert (streq (value, "service2"));
    zstr_free (&command);
    zstr_free (&key);
    zstr_free (&value);

    zstr_recvx (alpha, &command, &key, &value, NULL);
    assert (streq (command, "DELIVER"));
    assert (streq (key, "inproc://beta-1"));
    assert (streq (value, "service1"));
    zstr_free (&command);
    zstr_free (&key);
    zstr_free (&value);

    zstr_recvx (alpha, &command, &key, &value, NULL);
    assert (streq (command, "DELIVER"));
    assert (streq (key, "inproc://beta-2"));
    assert (streq (value, "service2"));
    zstr_free (&command);
    zstr_free (&key);
    zstr_free (&value);

    zstr_recvx (alpha, &command, &status, NULL);
    assert (streq (command, "STATUS"));
    assert (atoi (status) == 4);
    zstr_free (&command);
    zstr_free (&status);

    zactor_destroy (&base);
    zactor_destroy (&alpha);
    zactor_destroy (&beta);

#ifdef CZMQ_BUILD_DRAFT_API
    //  DRAFT-API: Security
    // curve
    if (zsys_has_curve()) {
        if (verbose)
            printf("testing CURVE support");
        zclock_sleep (2000);
        zactor_t *auth = zactor_new(zauth, NULL);
        assert (auth);
        if (verbose) {
            zstr_sendx (auth, "VERBOSE", NULL);
            zsock_wait (auth);
        }
        zstr_sendx(auth,"ALLOW","127.0.0.1",NULL);
        zsock_wait(auth);
        zstr_sendx (auth, "CURVE", CURVE_ALLOW_ANY, NULL);
        zsock_wait (auth);

        server = zactor_new (zgossip, "server");
        if (verbose)
            zstr_send (server, "VERBOSE");
        assert (server);

        zcert_t *client1_cert = zcert_new ();
        zcert_t *server_cert = zcert_new ();

        zstr_sendx (server, "SET PUBLICKEY", zcert_public_txt (server_cert), NULL);
        zstr_sendx (server, "SET SECRETKEY", zcert_secret_txt (server_cert), NULL);
        zstr_sendx (server, "ZAP DOMAIN", "TEST", NULL);

        zstr_sendx (server, "BIND", "tcp://127.0.0.1:*", NULL);
        zstr_sendx (server, "PORT", NULL);
        zstr_recvx (server, &command, &value, NULL);
        assert (streq (command, "PORT"));
        int port = atoi (value);
        zstr_free (&command);
        zstr_free (&value);
        char endpoint [32];
        sprintf (endpoint, "tcp://127.0.0.1:%d", port);

        zactor_t *client1 = zactor_new (zgossip, "client");
        if (verbose)
            zstr_send (client1, "VERBOSE");
        assert (client1);

        zstr_sendx (client1, "SET PUBLICKEY", zcert_public_txt (client1_cert), NULL);
        zstr_sendx (client1, "SET SECRETKEY", zcert_secret_txt (client1_cert), NULL);
        zstr_sendx (client1, "ZAP DOMAIN", "TEST", NULL);

        const char *public_txt = zcert_public_txt (server_cert);
        zstr_sendx (client1, "CONNECT", endpoint, public_txt, NULL);
        zstr_sendx (client1, "PUBLISH", "tcp://127.0.0.1:9001", "service1", NULL);

        zclock_sleep (500);

        zstr_send (server, "STATUS");
        zclock_sleep (500);

        zstr_recvx (server, &command, &key, &value, NULL);
        assert (streq (command, "DELIVER"));
        assert (streq (value, "service1"));

        zstr_free (&command);
        zstr_free (&key);
        zstr_free (&value);

        zstr_sendx (client1, "$TERM", NULL);
        zstr_sendx (server, "$TERM", NULL);

        zclock_sleep(500);

        zcert_destroy (&client1_cert);
        zcert_destroy (&server_cert);

        zactor_destroy (&client1);
        zactor_destroy (&server);
        zactor_destroy (&auth);
    }
#endif

#if defined (__WINDOWS__)
    zsys_shutdown();
#endif

    //  @end
    printf ("OK\n");
}
示例#9
0
// Authentication test procedure for zproxy sockets - matches zauth_test steps
static void
zproxy_test_authentication (int selected_sockets, bool verbose)
{
#   define TESTDIR ".test_zproxy"
#   define TESTPWDS TESTDIR "/password-file"
#   define TESTCERT TESTDIR "/mycert.txt"
#   define TESTFRONTEND (selected_sockets & FRONTEND_SOCKET)
#   define TESTBACKEND (selected_sockets & BACKEND_SOCKET)

    // Demarcate test boundaries
    zsys_info ("zproxy: TEST authentication type=%s%s%s", 
        TESTFRONTEND? "FRONTEND": "", 
        TESTFRONTEND && TESTBACKEND? "+": "", 
        TESTBACKEND? "BACKEND": "");

    //  Create temporary directory for test files
    zsys_dir_create (TESTDIR);

    // Clear out any test files from previous run
    if (zsys_file_exists (TESTPWDS))
        zsys_file_delete (TESTPWDS);
    if (zsys_file_exists (TESTCERT))
        zsys_file_delete (TESTCERT);

    zactor_t *proxy = NULL;
    zsock_t *faucet = NULL;
    zsock_t *sink = NULL;
    char *frontend = NULL;
    char *backend = NULL;

    //  Check there's no authentication
    s_create_test_sockets (&proxy, &faucet, &sink, verbose);
    s_bind_proxy_sockets (proxy, &frontend, &backend);
    bool success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
    assert (success);

    // Install the authenticator
    zactor_t *auth = zactor_new (zauth, NULL);
    assert (auth);
    if (verbose) {
        zstr_sendx (auth, "VERBOSE", NULL);
        zsock_wait (auth);
    }

    // Check there's no authentication on a default NULL server
    s_bind_proxy_sockets (proxy, &frontend, &backend);
    success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
    assert (success);

    // When we set a domain on the server, we switch on authentication
    // for NULL sockets, but with no policies, the client connection
    // will be allowed.
    s_send_proxy_command (proxy, "DOMAIN", selected_sockets, "global", NULL);
    s_bind_proxy_sockets (proxy, &frontend, &backend);
    success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
    assert (success);

    // Blacklist 127.0.0.1, connection should fail
    s_send_proxy_command (proxy, "DOMAIN", selected_sockets, "global", NULL);
    s_bind_proxy_sockets (proxy, &frontend, &backend);
    zstr_sendx (auth, "DENY", "127.0.0.1", NULL);
    zsock_wait (auth);
    success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
    assert (!success);

    // Whitelist our address, which overrides the blacklist
    s_send_proxy_command (proxy, "DOMAIN", selected_sockets, "global", NULL);
    s_bind_proxy_sockets (proxy, &frontend, &backend);
    zstr_sendx (auth, "ALLOW", "127.0.0.1", NULL);
    zsock_wait (auth);
    success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
    assert (success);

    // Try PLAIN authentication

    // Test negative case (no server-side passwords defined)
    s_send_proxy_command (proxy, "PLAIN", selected_sockets, NULL);
    s_bind_proxy_sockets (proxy, &frontend, &backend);
    s_configure_plain_auth (faucet, sink, selected_sockets, "admin", "Password");
    success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
    assert (!success);

    // Test positive case (server-side passwords defined)
    FILE *password = fopen (TESTPWDS, "w");
    assert (password);
    fprintf (password, "admin=Password\n");
    fclose (password);
    s_send_proxy_command (proxy, "PLAIN", selected_sockets, NULL);
    s_bind_proxy_sockets (proxy, &frontend, &backend);
    s_configure_plain_auth (faucet, sink, selected_sockets, "admin", "Password");
    zstr_sendx (auth, "PLAIN", TESTPWDS, NULL);
    zsock_wait (auth);
    success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
    assert (success);

    // Test negative case (bad client password)
    s_send_proxy_command (proxy, "PLAIN", selected_sockets, NULL);
    s_bind_proxy_sockets (proxy, &frontend, &backend);
    s_configure_plain_auth (faucet, sink, selected_sockets, "admin", "Bogus");
    success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
    assert (!success);

    if (zsys_has_curve ()) {
        // We'll create two new certificates and save the client public
        // certificate on disk
        zcert_t *server_cert = zcert_new ();
        assert (server_cert);
        zcert_t *client_cert = zcert_new ();
        assert (client_cert);
        char *public_key = zcert_public_txt (server_cert);
        char *secret_key = zcert_secret_txt (server_cert);

        // Try CURVE authentication

        // Test without setting-up any authentication
        s_send_proxy_command (proxy, "CURVE", selected_sockets, public_key, secret_key, NULL);
        s_bind_proxy_sockets (proxy, &frontend, &backend);
        s_configure_curve_auth (faucet, sink, selected_sockets, client_cert, public_key);
        success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
        assert (!success);

        // Test CURVE_ALLOW_ANY
        s_send_proxy_command (proxy, "CURVE", selected_sockets, public_key, secret_key, NULL);
        s_bind_proxy_sockets (proxy, &frontend, &backend);
        s_configure_curve_auth (faucet, sink, selected_sockets, client_cert, public_key);
        zstr_sendx (auth, "CURVE", CURVE_ALLOW_ANY, NULL);
        zsock_wait (auth);
        success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
        assert (success);

        // Test with client certificate file in authentication folder
        s_send_proxy_command (proxy, "CURVE", selected_sockets, public_key, secret_key, NULL);
        s_bind_proxy_sockets (proxy, &frontend, &backend);
        s_configure_curve_auth (faucet, sink, selected_sockets, client_cert, public_key);
        zcert_save_public (client_cert, TESTCERT);
        zstr_sendx (auth, "CURVE", TESTDIR, NULL);
        zsock_wait (auth);
        success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
        assert (success);

        zcert_destroy (&server_cert);
        zcert_destroy (&client_cert);
    }

    // Remove the authenticator and check a normal connection works
    zactor_destroy (&auth);
    s_bind_proxy_sockets (proxy, &frontend, &backend);
    success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose);
    assert (success);

    zsock_destroy (&faucet);
    zsock_destroy (&sink);
    zactor_destroy (&proxy);
    zstr_free (&frontend);
    zstr_free (&backend);
}
示例#10
0
文件: zyre.c 项目: sphaero/zyre
void
zyre_test (bool verbose)
{
    printf (" * zyre: ");
    if (verbose)
        printf ("\n");

    //  @selftest
    //  We'll use inproc gossip discovery so that this works without networking

    uint64_t version = zyre_version ();
    assert ((version / 10000) % 100 == ZYRE_VERSION_MAJOR);
    assert ((version / 100) % 100 == ZYRE_VERSION_MINOR);
    assert (version % 100 == ZYRE_VERSION_PATCH);

    //  Create two nodes
    zyre_t *node1 = zyre_new ("node1");
    assert (node1);
    assert (streq (zyre_name (node1), "node1"));
    zyre_set_header (node1, "X-HELLO", "World");
    if (verbose)
        zyre_set_verbose (node1);

    //  Set inproc endpoint for this node
    int rc = zyre_set_endpoint (node1, "inproc://zyre-node1");
    assert (rc == 0);
    //  Set up gossip network for this node
    zyre_gossip_bind (node1, "inproc://gossip-hub");
    rc = zyre_start (node1);
    assert (rc == 0);

    zyre_t *node2 = zyre_new ("node2");
    assert (node2);
    assert (streq (zyre_name (node2), "node2"));
    if (verbose)
        zyre_set_verbose (node2);

    //  Set inproc endpoint for this node
    //  First, try to use existing name, it'll fail
    rc = zyre_set_endpoint (node2, "inproc://zyre-node1");
    assert (rc == -1);
    //  Now use available name and confirm that it succeeds
    rc = zyre_set_endpoint (node2, "inproc://zyre-node2");
    assert (rc == 0);

    //  Set up gossip network for this node
    zyre_gossip_connect (node2, "inproc://gossip-hub");
    rc = zyre_start (node2);
    assert (rc == 0);
    assert (strneq (zyre_uuid (node1), zyre_uuid (node2)));

    zyre_join (node1, "GLOBAL");
    zyre_join (node2, "GLOBAL");

    //  Give time for them to interconnect
    zclock_sleep (250);
    if (verbose)
        zyre_dump (node1);

    zlist_t *peers = zyre_peers (node1);
    assert (peers);
    assert (zlist_size (peers) == 1);
    zlist_destroy (&peers);

    zyre_join (node1, "node1 group of one");
    zyre_join (node2, "node2 group of one");

    // Give them time to join their groups
    zclock_sleep (250);

    zlist_t *own_groups = zyre_own_groups (node1);
    assert (own_groups);
    assert (zlist_size (own_groups) == 2);
    zlist_destroy (&own_groups);

    zlist_t *peer_groups = zyre_peer_groups (node1);
    assert (peer_groups);
    assert (zlist_size (peer_groups) == 2);
    zlist_destroy (&peer_groups);

    char *value = zyre_peer_header_value (node2, zyre_uuid (node1), "X-HELLO");
    assert (streq (value, "World"));
    zstr_free (&value);

    //  One node shouts to GLOBAL
    zyre_shouts (node1, "GLOBAL", "Hello, World");

    //  Second node should receive ENTER, JOIN, and SHOUT
    zmsg_t *msg = zyre_recv (node2);
    assert (msg);
    char *command = zmsg_popstr (msg);
    assert (streq (command, "ENTER"));
    zstr_free (&command);
    assert (zmsg_size (msg) == 4);
    char *peerid = zmsg_popstr (msg);
    char *name = zmsg_popstr (msg);
    assert (streq (name, "node1"));
    zstr_free (&name);
    zframe_t *headers_packed = zmsg_pop (msg);

    char *address = zmsg_popstr (msg);
    char *endpoint = zyre_peer_address (node2, peerid);
    assert (streq (address, endpoint));
    zstr_free (&peerid);
    zstr_free (&endpoint);
    zstr_free (&address);

    assert (headers_packed);
    zhash_t *headers = zhash_unpack (headers_packed);
    assert (headers);
    zframe_destroy (&headers_packed);
    assert (streq ((char *) zhash_lookup (headers, "X-HELLO"), "World"));
    zhash_destroy (&headers);
    zmsg_destroy (&msg);

    msg = zyre_recv (node2);
    assert (msg);
    command = zmsg_popstr (msg);
    assert (streq (command, "JOIN"));
    zstr_free (&command);
    assert (zmsg_size (msg) == 3);
    zmsg_destroy (&msg);

    msg = zyre_recv (node2);
    assert (msg);
    command = zmsg_popstr (msg);
    assert (streq (command, "JOIN"));
    zstr_free (&command);
    assert (zmsg_size (msg) == 3);
    zmsg_destroy (&msg);

    msg = zyre_recv (node2);
    assert (msg);
    command = zmsg_popstr (msg);
    assert (streq (command, "SHOUT"));
    zstr_free (&command);
    zmsg_destroy (&msg);

    zyre_stop (node2);

    msg = zyre_recv (node2);
    assert (msg);
    command = zmsg_popstr (msg);
    assert (streq (command, "STOP"));
    zstr_free (&command);
    zmsg_destroy (&msg);

    zyre_stop (node1);

    zyre_destroy (&node1);
    zyre_destroy (&node2);

    printf ("OK\n");

#ifdef ZYRE_BUILD_DRAFT_API
    if (zsys_has_curve()){

        printf (" * zyre-curve: ");
        if (verbose)
            printf ("\n");

        if (verbose)
            zsys_debug("----------------TESTING CURVE --------------");

        zactor_t *speaker = zactor_new (zbeacon, NULL);
        assert (speaker);
        if (verbose)
            zstr_sendx (speaker, "VERBOSE", NULL);

        // ensuring we have a broadcast address
        zsock_send (speaker, "si", "CONFIGURE", 9999);
        char *hostname = zstr_recv (speaker);
        if (!*hostname) {
            printf ("OK (skipping test, no UDP broadcasting)\n");
            zactor_destroy (&speaker);
            freen (hostname);
            return;
        }
        freen (hostname);
        zactor_destroy (&speaker);


        // zap setup
        zactor_t *auth = zactor_new(zauth, NULL);
        assert (auth);

        if (verbose) {
            zstr_sendx(auth, "VERBOSE", NULL);
            zsock_wait(auth);
        }

        zstr_sendx (auth, "CURVE", CURVE_ALLOW_ANY, NULL);
        zsock_wait (auth);

        zyre_t *node3 = zyre_new ("node3");
        zyre_t *node4 = zyre_new ("node4");

        assert (node3);
        assert (node4);

        zyre_set_verbose (node3);
        zyre_set_verbose (node4);

        zyre_set_zap_domain(node3, "TEST");
        zyre_set_zap_domain(node4, "TEST");

        zsock_set_rcvtimeo(node3->inbox, 10000);
        zsock_set_rcvtimeo(node4->inbox, 10000);

        zcert_t *node3_cert = zcert_new ();
        zcert_t *node4_cert = zcert_new ();

        assert (node3_cert);
        assert (node4_cert);

        zyre_set_zcert(node3, node3_cert);
        zyre_set_zcert(node4, node4_cert);

        zyre_set_header(node3, "X-PUBLICKEY", "%s", zcert_public_txt(node3_cert));
        zyre_set_header(node4, "X-PUBLICKEY", "%s", zcert_public_txt(node4_cert));

        // test beacon
        if (verbose)
            zsys_debug ("----------------TESTING BEACON----------------");

        rc = zyre_start(node3);
        assert (rc == 0);

        rc = zyre_start(node4);
        assert (rc == 0);

        zyre_join (node3, "GLOBAL");
        zyre_join (node4, "GLOBAL");

        zclock_sleep (1500);

        if (verbose) {
            zyre_dump (node3);
            zyre_dump (node4);
        }

        zyre_shouts (node3, "GLOBAL", "Hello, World");

        //  Second node should receive ENTER, JOIN, and SHOUT
        msg = zyre_recv (node4);
        assert (msg);
        command = zmsg_popstr (msg);
        assert (streq (command, "ENTER"));
        zstr_free (&command);

        char *peerid = zmsg_popstr (msg);
        assert (peerid);
        name = zmsg_popstr (msg);
        assert (streq (name, "node3"));
        zmsg_destroy (&msg);

        msg = zyre_recv (node4);
        assert (msg);
        command = zmsg_popstr (msg);
        assert (streq (command, "JOIN"));
        zstr_free (&command);
        zmsg_destroy(&msg);

        msg = zyre_recv (node4);
        assert (msg);
        command = zmsg_popstr (msg);
        assert (streq (command, "SHOUT"));
        zstr_free (&command);
        zmsg_destroy(&msg);

        zyre_leave(node3, "GLOBAL");
        zyre_leave(node4, "GLOBAL");

        zstr_free (&name);
        zstr_free (&peerid);
        zstr_free (&command);

        zyre_stop (node3);
        zyre_stop (node4);

        // give things a chance to settle...
        zclock_sleep (250);

        zyre_destroy(&node3);
        zyre_destroy(&node4);

        zcert_destroy(&node3_cert);
        zcert_destroy(&node4_cert);

        // test gossip
        if (verbose)
            zsys_debug ("----------------TESTING GOSSIP----------------");

        zyre_t *node5 = zyre_new ("node5");
        zyre_t *node6 = zyre_new ("node6");

        assert (node5);
        assert (node6);

        if (verbose) {
            zyre_set_verbose (node5);
            zyre_set_verbose (node6);
        }

        // if it takes more than 10s, something probably went terribly wrong
        zsock_set_rcvtimeo(node5->inbox, 10000);
        zsock_set_rcvtimeo(node6->inbox, 10000);

        zcert_t *node5_cert = zcert_new ();
        zcert_t *node6_cert = zcert_new ();

        assert (node5_cert);
        assert (node6_cert);

        zyre_set_zcert(node5, node5_cert);
        zyre_set_zcert(node6, node6_cert);

        zyre_set_header(node5, "X-PUBLICKEY", "%s", zcert_public_txt(node5_cert));
        zyre_set_header(node6, "X-PUBLICKEY", "%s", zcert_public_txt(node6_cert));

        const char *gossip_cert = zcert_public_txt (node5_cert);

        // TODO- need to add zyre_gossip_port functions to get port from gossip bind(?)
        zyre_gossip_bind(node5, "tcp://127.0.0.1:9001");
        zyre_gossip_connect_curve(node6, gossip_cert, "tcp://127.0.0.1:9001");

        zyre_start(node5);
        zsock_wait(node5);
        zyre_start(node6);
        zsock_wait(node6);

        zyre_join (node5, "GLOBAL");
        zyre_join (node6, "GLOBAL");

        // give things a chance to settle...
        zclock_sleep (1500);

        if (verbose) {
            zyre_dump (node5);
            zyre_dump (node6);
        }

        zyre_shouts (node5, "GLOBAL", "Hello, World");

        //  Second node should receive ENTER, JOIN, and SHOUT
        msg = zyre_recv (node6);
        assert (msg);
        command = zmsg_popstr (msg);
        zsys_info(command);
        assert (streq (command, "ENTER"));
        zstr_free (&command);

        peerid = zmsg_popstr (msg);
        assert (peerid);
        name = zmsg_popstr (msg);
        zmsg_destroy (&msg);

        assert (streq (name, "node5"));
        zstr_free (&name);

        zyre_leave(node5, "GLOBAL");
        zyre_leave(node6, "GLOBAL");

        zyre_stop (node5);
        zyre_stop (node6);

        // give things a chance to settle...
        zclock_sleep (250);

        zstr_free (&peerid);

        zcert_destroy (&node5_cert);
        zcert_destroy (&node6_cert);

        zyre_destroy(&node5);
        zyre_destroy(&node6);
        zactor_destroy(&auth);

        printf ("OK\n");

    }
#endif
}
示例#11
0
文件: zsys.c 项目: wysman/czmq
void
zsys_test (bool verbose)
{
    printf (" * zsys: ");
    if (verbose)
        printf ("\n");

    //  @selftest
    zsys_catch_interrupts ();

    //  Check capabilities without using the return value
    int rc = zsys_has_curve ();

    if (verbose) {
        char *hostname = zsys_hostname ();
        zsys_info ("host name is %s", hostname);
        free (hostname);
        zsys_info ("system limit is %zd ZeroMQ sockets", zsys_socket_limit ());
    }
    zsys_set_io_threads (1);
    zsys_set_max_sockets (0);
    zsys_set_linger (0);
    zsys_set_sndhwm (1000);
    zsys_set_rcvhwm (1000);
    zsys_set_pipehwm (2500);
    assert (zsys_pipehwm () == 2500);

    zsys_set_ipv6 (0);

    rc = zsys_file_delete ("nosuchfile");
    assert (rc == -1);

    bool rc_bool = zsys_file_exists ("nosuchfile");
    assert (rc_bool != true);

    rc = (int) zsys_file_size ("nosuchfile");
    assert (rc == -1);

    time_t when = zsys_file_modified (".");
    assert (when > 0);

    mode_t mode = zsys_file_mode (".");
    assert (S_ISDIR (mode));
    assert (mode & S_IRUSR);
    assert (mode & S_IWUSR);

    zsys_file_mode_private ();
    rc = zsys_dir_create ("%s/%s", ".", ".testsys/subdir");
    assert (rc == 0);
    when = zsys_file_modified ("./.testsys/subdir");
    assert (when > 0);
    assert (!zsys_file_stable ("./.testsys/subdir"));
    rc = zsys_dir_delete ("%s/%s", ".", ".testsys/subdir");
    assert (rc == 0);
    rc = zsys_dir_delete ("%s/%s", ".", ".testsys");
    assert (rc == 0);
    zsys_file_mode_default ();

    int major, minor, patch;
    zsys_version (&major, &minor, &patch);
    assert (major == CZMQ_VERSION_MAJOR);
    assert (minor == CZMQ_VERSION_MINOR);
    assert (patch == CZMQ_VERSION_PATCH);

    char *string = zsys_sprintf ("%s %02x", "Hello", 16);
    assert (streq (string, "Hello 10"));
    free (string);

    char *str64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,.";
    int num10 = 1234567890;
    string = zsys_sprintf ("%s%s%s%s%d", str64, str64, str64, str64, num10);
    assert (strlen (string) == (4 * 64 + 10));
    free (string);

    //  Test logging system
    zsys_set_logident ("czmq_selftest");
    zsys_set_logsender ("inproc://logging");
    void *logger = zsys_socket (ZMQ_SUB, NULL, 0);
    assert (logger);
    rc = zsocket_connect (logger, "inproc://logging");
    assert (rc == 0);
    rc = zmq_setsockopt (logger, ZMQ_SUBSCRIBE, "", 0);
    assert (rc == 0);

    if (verbose) {
        zsys_error ("This is an %s message", "error");
        zsys_warning ("This is a %s message", "warning");
        zsys_notice ("This is a %s message", "notice");
        zsys_info ("This is a %s message", "info");
        zsys_debug ("This is a %s message", "debug");
        zsys_set_logident ("hello, world");
        zsys_info ("This is a %s message", "info");
        zsys_debug ("This is a %s message", "debug");

        //  Check that logsender functionality is working
        char *received = zstr_recv (logger);
        assert (received);
        zstr_free (&received);
    }
    zsys_close (logger, NULL, 0);
    //  @end

    printf ("OK\n");
}
示例#12
0
///
//  Returns true if the underlying libzmq supports CURVE security.
//  Uses a heuristic probe according to the version of libzmq being used.
bool QZsys::hasCurve ()
{
    bool rv = zsys_has_curve ();
    return rv;
}
示例#13
0
celix_status_t pubsubAdmin_create(bundle_context_pt context, pubsub_admin_pt *admin) {
	celix_status_t status = CELIX_SUCCESS;

#ifdef BUILD_WITH_ZMQ_SECURITY
	if (!zsys_has_curve()){
		printf("PSA_ZMQ: zeromq curve unsupported\n");
		return CELIX_SERVICE_EXCEPTION;
	}
#endif

	*admin = calloc(1, sizeof(**admin));

	if (!*admin) {
		status = CELIX_ENOMEM;
	}
	else{

		const char *ip = NULL;
		char *detectedIp = NULL;
		(*admin)->bundle_context= context;
		(*admin)->localPublications = hashMap_create(utils_stringHash, NULL, utils_stringEquals, NULL);
		(*admin)->subscriptions = hashMap_create(utils_stringHash, NULL, utils_stringEquals, NULL);
		(*admin)->pendingSubscriptions = hashMap_create(utils_stringHash, NULL, utils_stringEquals, NULL);
		(*admin)->externalPublications = hashMap_create(utils_stringHash, NULL, utils_stringEquals, NULL);
		(*admin)->topicSubscriptionsPerSerializer = hashMap_create(NULL, NULL, NULL, NULL);
		(*admin)->topicPublicationsPerSerializer  = hashMap_create(NULL, NULL, NULL, NULL);
		arrayList_create(&((*admin)->noSerializerSubscriptions));
		arrayList_create(&((*admin)->noSerializerPublications));
		arrayList_create(&((*admin)->serializerList));

		celixThreadMutex_create(&(*admin)->localPublicationsLock, NULL);
		celixThreadMutex_create(&(*admin)->subscriptionsLock, NULL);
		celixThreadMutex_create(&(*admin)->externalPublicationsLock, NULL);
		celixThreadMutex_create(&(*admin)->serializerListLock, NULL);
		celixThreadMutex_create(&(*admin)->usedSerializersLock, NULL);

		celixThreadMutexAttr_create(&(*admin)->noSerializerPendingsAttr);
		celixThreadMutexAttr_settype(&(*admin)->noSerializerPendingsAttr, CELIX_THREAD_MUTEX_RECURSIVE);
		celixThreadMutex_create(&(*admin)->noSerializerPendingsLock, &(*admin)->noSerializerPendingsAttr);

		celixThreadMutexAttr_create(&(*admin)->pendingSubscriptionsAttr);
		celixThreadMutexAttr_settype(&(*admin)->pendingSubscriptionsAttr, CELIX_THREAD_MUTEX_RECURSIVE);
		celixThreadMutex_create(&(*admin)->pendingSubscriptionsLock, &(*admin)->pendingSubscriptionsAttr);

		if (logHelper_create(context, &(*admin)->loghelper) == CELIX_SUCCESS) {
			logHelper_start((*admin)->loghelper);
		}

		bundleContext_getProperty(context,PSA_IP , &ip);

#ifndef ANDROID
		if (ip == NULL) {
			const char *interface = NULL;

			bundleContext_getProperty(context, PSA_ITF, &interface);
			if (pubsubAdmin_getIpAdress(interface, &detectedIp) != CELIX_SUCCESS) {
				logHelper_log((*admin)->loghelper, OSGI_LOGSERVICE_WARNING, "PSA_ZMQ: Could not retrieve IP adress for interface %s", interface);
			}

			ip = detectedIp;
		}
#endif

		if (ip != NULL) {
			logHelper_log((*admin)->loghelper, OSGI_LOGSERVICE_INFO, "PSA_ZMQ: Using %s for service annunciation", ip);
			(*admin)->ipAddress = strdup(ip);
		}
		else {
			logHelper_log((*admin)->loghelper, OSGI_LOGSERVICE_WARNING, "PSA_ZMQ: No IP address for service annunciation set. Using %s", DEFAULT_IP);
			(*admin)->ipAddress = strdup(DEFAULT_IP);
		}

		if (detectedIp != NULL) {
			free(detectedIp);
		}

		const char* basePortStr = NULL;
		const char* maxPortStr = NULL;
		char* endptrBase = NULL;
		char* endptrMax = NULL;
		bundleContext_getPropertyWithDefault(context, PSA_ZMQ_BASE_PORT, "PSA_ZMQ_DEFAULT_BASE_PORT", &basePortStr);
		bundleContext_getPropertyWithDefault(context, PSA_ZMQ_MAX_PORT, "PSA_ZMQ_DEFAULT_MAX_PORT", &maxPortStr);
		(*admin)->basePort = strtol(basePortStr, &endptrBase, 10);
		(*admin)->maxPort = strtol(maxPortStr, &endptrMax, 10);
		if (*endptrBase != '\0') {
			(*admin)->basePort = PSA_ZMQ_DEFAULT_BASE_PORT;
		}
		if (*endptrMax != '\0') {
			(*admin)->maxPort = PSA_ZMQ_DEFAULT_MAX_PORT;
		}

		printf("PSA Using base port %u to max port %u\n", (*admin)->basePort, (*admin)->maxPort);

		// Disable Signal Handling by CZMQ
		setenv("ZSYS_SIGHANDLER", "false", true);

		const char *nrZmqThreads = NULL;
		bundleContext_getProperty(context, "PSA_NR_ZMQ_THREADS", &nrZmqThreads);

		if(nrZmqThreads != NULL) {
			char *endPtr = NULL;
			unsigned int nrThreads = strtoul(nrZmqThreads, &endPtr, 10);
			if(endPtr != nrZmqThreads && nrThreads > 0 && nrThreads < 50) {
				zsys_set_io_threads(nrThreads);
				logHelper_log((*admin)->loghelper, OSGI_LOGSERVICE_INFO, "PSA_ZMQ: Using %d threads for ZMQ", nrThreads);
				printf("PSA_ZMQ: Using %d threads for ZMQ\n", nrThreads);
			}
		}

#ifdef BUILD_WITH_ZMQ_SECURITY
		// Setup authenticator
		zactor_t* auth = zactor_new (zauth, NULL);
		zstr_sendx(auth, "VERBOSE", NULL);

		// Load all public keys of subscribers into the application
		// This step is done for authenticating subscribers
		char curve_folder_path[MAX_KEY_FOLDER_PATH_LENGTH];
		char* keys_bundle_dir = pubsub_getKeysBundleDir(context);
		snprintf(curve_folder_path, MAX_KEY_FOLDER_PATH_LENGTH, "%s/META-INF/keys/subscriber/public", keys_bundle_dir);
		zstr_sendx (auth, "CURVE", curve_folder_path, NULL);
		free(keys_bundle_dir);

		(*admin)->zmq_auth = auth;
#endif

	}

	return status;
}