void zcert_test (bool verbose) { printf (" * zcert: "); #if (ZMQ_VERSION_MAJOR == 4) // @selftest // Create temporary directory for test files # define TESTDIR ".test_zcert" zsys_dir_create (TESTDIR); // Create a simple certificate with metadata zcert_t *cert = zcert_new (); # if defined (HAVE_LIBSODIUM) zcert_set_meta (cert, "email", "*****@*****.**"); zcert_set_meta (cert, "name", "Pieter Hintjens"); zcert_set_meta (cert, "organization", "iMatix Corporation"); zcert_set_meta (cert, "version", "%d", 1); assert (streq (zcert_meta (cert, "email"), "*****@*****.**")); zlist_t *keys = zcert_meta_keys (cert); assert (zlist_size (keys) == 4); zlist_destroy (&keys); // Check the dup and eq methods zcert_t *shadow = zcert_dup (cert); assert (zcert_eq (cert, shadow)); zcert_destroy (&shadow); // Check we can save and load certificate zcert_save (cert, TESTDIR "/mycert.txt"); assert (zsys_file_exists (TESTDIR "/mycert.txt")); assert (zsys_file_exists (TESTDIR "/mycert.txt_secret")); // Load certificate, will in fact load secret one shadow = zcert_load (TESTDIR "/mycert.txt"); assert (shadow); assert (zcert_eq (cert, shadow)); zcert_destroy (&shadow); // Delete secret certificate, load public one int rc = zsys_file_delete (TESTDIR "/mycert.txt_secret"); assert (rc == 0); shadow = zcert_load (TESTDIR "/mycert.txt"); // 32-byte null key encodes as 40 '0' characters assert (streq (zcert_secret_txt (shadow), "0000000000000000000000000000000000000000")); zcert_destroy (&shadow); zcert_destroy (&cert); # else // Libsodium isn't installed; should have returned NULL assert (cert == NULL); # endif // Delete all test files zdir_t *dir = zdir_new (TESTDIR, NULL); zdir_remove (dir, true); zdir_destroy (&dir); // @end #endif printf ("OK\n"); }
static zsync_node_t * zsync_node_new () { int rc; zsync_node_t *self = (zsync_node_t *) zmalloc (sizeof (zsync_node_t)); self->ctx = zctx_new (); assert (self->ctx); self->zyre = zyre_new (self->ctx); assert (self->zyre); // Obtain permanent UUID self->own_uuid = zuuid_new (); if (zsys_file_exists (UUID_FILE)) { // Read uuid from file zfile_t *uuid_file = zfile_new (".", UUID_FILE); int rc = zfile_input (uuid_file); // open file for reading assert (rc == 0); zchunk_t *uuid_chunk = zfile_read (uuid_file, 16, 0); assert (zchunk_size (uuid_chunk) == 16); // make sure read succeeded zuuid_set (self->own_uuid, zchunk_data (uuid_chunk)); zfile_destroy (&uuid_file); } else { // Write uuid to file zfile_t *uuid_file = zfile_new (".", UUID_FILE); rc = zfile_output (uuid_file); // open file for writing assert (rc == 0); zchunk_t *uuid_bin = zchunk_new ( zuuid_data (self->own_uuid), 16); rc = zfile_write (uuid_file, uuid_bin, 0); assert (rc == 0); zfile_destroy (&uuid_file); } // Obtain peers and states self->peers = zlist_new (); if (zsys_file_exists (PEER_STATES_FILE)) { zhash_t *peer_states = zhash_new (); int rc = zhash_load (peer_states, PEER_STATES_FILE); assert (rc == 0); zlist_t *uuids = zhash_keys (peer_states); char *uuid = zlist_first (uuids); while (uuid) { char * state_str = zhash_lookup (peer_states, uuid); uint64_t state; sscanf (state_str, "%"SCNd64, &state); zlist_append (self->peers, zsync_peer_new (uuid, state)); uuid = zlist_next (uuids); } } self->zyre_peers = zhash_new (); self->terminated = false; return self; }
zchunk_t * get_chunk (char *path, uint64_t chunk_size, uint64_t offset) { printf("[ST] GET CHUNK\n"); char *path_new = malloc(strlen("./syncfolder/") + strlen(path) + 1); path_new[0] = '\0'; strcat(path_new, "./syncfolder/"); strcat(path_new, path); if (zsys_file_exists (path_new)) { printf("[ST] File exist\n"); zfile_t *file = zfile_new (".", path_new); if (zfile_is_readable (file)) { printf("[ST] File read\n"); zfile_input (file); if (zfile_size (path_new) > offset) { zchunk_t *chunk = zfile_read (file, chunk_size, offset); zfile_destroy (&file); return chunk; } else { return NULL; } } } else { printf("[ST] File %s not exist\n", path_new); } return NULL; }
JNIEXPORT jboolean JNICALL Java_org_zeromq_czmq_Zsys__1_1fileExists (JNIEnv *env, jclass c, jstring filename) { char *filename_ = (char *) (*env)->GetStringUTFChars (env, filename, NULL); jboolean file_exists_ = (jboolean) zsys_file_exists (filename_); (*env)->ReleaseStringUTFChars (env, filename, filename_); return file_exists_; }
int zsys_test (bool verbose) { printf (" * zsys: "); // @selftest zsys_handler_reset (); zsys_handler_set (NULL); zsys_handler_set (NULL); zsys_handler_reset (); zsys_handler_reset (); int 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); rc = zsys_dir_create ("%s/%s", ".", ".testsys/subdir"); assert (rc == 0); when = zsys_file_modified ("./.testsys/subdir"); assert (when > 0); rc = zsys_dir_delete ("%s/%s", ".", ".testsys/subdir"); assert (rc == 0); rc = zsys_dir_delete ("%s/%s", ".", ".testsys"); assert (rc == 0); 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 = s_vprintf ("%s %02x", "Hello", 16); assert (streq (string, "Hello 10")); zstr_free (&string); char *str64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,."; int num10 = 1234567890; string = s_vprintf ("%s%s%s%s%d", str64, str64, str64, str64, num10); assert (strlen (string) == (4 * 64 + 10)); zstr_free (&string); // @end printf ("OK\n"); return 0; }
int main(int argc, char * const *argv) { setvbuf(stdout, NULL, _IOLBF, 0); setvbuf(stderr, NULL, _IOLBF, 0); process_arguments(argc, argv); // load config if (!zsys_file_exists(config_file_name)) { fprintf(stderr, "[W] missing config file: %s\n", config_file_name); config = zconfig_new("", NULL); } else if (zsys_file_exists(config_file_name)) { // load config config_file_init(); config = zconfig_load((char*)config_file_name); } // configure graylog endpoint if (interface == NULL) interface = zconfig_resolve(config, "/graylog/endpoint", DEFAULT_INTERFACE); // set inbound high-water-mark if (rcv_hwm == -1) rcv_hwm = atoi(zconfig_resolve(config, "/logjam/high_water_mark", DEFAULT_RCV_HWM_STR)); // set outbound high-water-mark if (snd_hwm == -1) snd_hwm = atoi(zconfig_resolve(config, "/graylog/high_water_mark", DEFAULT_SND_HWM_STR)); if (!quiet) printf("[I] started %s\n" "[I] interface %s\n" "[I] rcv-hwm: %d\n" "[I] snd-hwm: %d\n" , argv[0], interface, rcv_hwm, snd_hwm); return graylog_forwarder_run_controller_loop(config, hosts, subscriptions, rcv_hwm, snd_hwm); }
int zsys_test (bool verbose) { printf (" * zsys: "); // @selftest zsys_handler_reset (); zsys_handler_set (NULL); zsys_handler_set (NULL); zsys_handler_reset (); zsys_handler_reset (); int 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); rc = zsys_dir_create ("%s/%s", ".", ".testsys/subdir"); assert (rc == 0); when = zsys_file_modified ("./.testsys/subdir"); assert (when > 0); rc = zsys_dir_delete ("%s/%s", ".", ".testsys/subdir"); assert (rc == 0); char *string = s_vprintf ("%s %02x", "Hello", 16); assert (streq (string, "Hello 10")); free (string); // @end printf ("OK\n"); return 0; }
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()); }
int main(int argc, char * const *argv) { int rc = 0; process_arguments(argc, argv); setvbuf(stdout, NULL, _IOLBF, 0); setvbuf(stderr, NULL, _IOLBF, 0); if (!quiet) printf("[I] started %s\n" "[I] sub-port: %d\n" "[I] push-port: %d\n" "[I] io-threads: %lu\n" "[I] rcv-hwm: %d\n" "[I] snd-hwm: %d\n" , argv[0], pull_port, pub_port, io_threads, rcv_hwm, snd_hwm); // load config config_file_exists = zsys_file_exists(config_file_name); if (config_file_exists) { config_file_init(); config = zconfig_load((char*)config_file_name); } // set global config zsys_init(); zsys_set_rcvhwm(10000); zsys_set_sndhwm(10000); zsys_set_pipehwm(1000); zsys_set_linger(100); zsys_set_io_threads(io_threads); // create socket to receive messages on zsock_t *receiver = zsock_new(ZMQ_SUB); assert_x(receiver != NULL, "sub socket creation failed", __FILE__, __LINE__); zsock_set_rcvhwm(receiver, rcv_hwm); // bind externally char* host = zlist_first(hosts); while (host) { if (!quiet) printf("[I] connecting to: %s\n", host); rc = zsock_connect(receiver, "%s", host); assert_x(rc == 0, "sub socket connect failed", __FILE__, __LINE__); host = zlist_next(hosts); } tracker = device_tracker_new(hosts, receiver); // create socket for publishing zsock_t *publisher = zsock_new(ZMQ_PUSH); assert_x(publisher != NULL, "pub socket creation failed", __FILE__, __LINE__); zsock_set_sndhwm(publisher, snd_hwm); rc = zsock_bind(publisher, "tcp://%s:%d", "*", pub_port); assert_x(rc == pub_port, "pub socket bind failed", __FILE__, __LINE__); // create compressor sockets zsock_t *compressor_input = zsock_new(ZMQ_PUSH); assert_x(compressor_input != NULL, "compressor input socket creation failed", __FILE__, __LINE__); rc = zsock_bind(compressor_input, "inproc://compressor-input"); assert_x(rc==0, "compressor input socket bind failed", __FILE__, __LINE__); zsock_t *compressor_output = zsock_new(ZMQ_PULL); assert_x(compressor_output != NULL, "compressor output socket creation failed", __FILE__, __LINE__); rc = zsock_bind(compressor_output, "inproc://compressor-output"); assert_x(rc==0, "compressor output socket bind failed", __FILE__, __LINE__); // create compressor agents zactor_t *compressors[MAX_COMPRESSORS]; for (size_t i = 0; i < num_compressors; i++) compressors[i] = message_decompressor_new(i); // set up event loop zloop_t *loop = zloop_new(); assert(loop); zloop_set_verbose(loop, 0); // calculate statistics every 1000 ms int timer_id = zloop_timer(loop, 1000, 0, timer_event, NULL); assert(timer_id != -1); // setup handler for the receiver socket publisher_state_t publisher_state = { .receiver = zsock_resolve(receiver), .publisher = zsock_resolve(publisher), .compressor_input = zsock_resolve(compressor_input), .compressor_output = zsock_resolve(compressor_output), }; // setup handler for compression results rc = zloop_reader(loop, compressor_output, read_zmq_message_and_forward, &publisher_state); assert(rc == 0); zloop_reader_set_tolerant(loop, compressor_output); // setup handdler for messages incoming from the outside or rabbit_listener rc = zloop_reader(loop, receiver, read_zmq_message_and_forward, &publisher_state); assert(rc == 0); zloop_reader_set_tolerant(loop, receiver); // initialize clock global_time = zclock_time(); // setup subscriptions if (subscriptions == NULL || zlist_size(subscriptions) == 0) { if (!quiet) printf("[I] subscribing to all log messages\n"); zsock_set_subscribe(receiver, ""); } else { char *subscription = zlist_first(subscriptions); while (subscription) { if (!quiet) printf("[I] subscribing to %s\n", subscription); zsock_set_subscribe(receiver, subscription); subscription = zlist_next(subscriptions); } zsock_set_subscribe(receiver, "heartbeat"); } // run the loop if (!zsys_interrupted) { if (verbose) printf("[I] starting main event loop\n"); bool should_continue_to_run = getenv("CPUPROFILE") != NULL; do { rc = zloop_start(loop); should_continue_to_run &= errno == EINTR && !zsys_interrupted; log_zmq_error(rc, __FILE__, __LINE__); } while (should_continue_to_run); if (verbose) printf("[I] main event zloop terminated with return code %d\n", rc); } zloop_destroy(&loop); assert(loop == NULL); if (!quiet) { printf("[I] received %zu messages\n", received_messages_count); printf("[I] shutting down\n"); } zlist_destroy(&hosts); zlist_destroy(&subscriptions); zsock_destroy(&receiver); zsock_destroy(&publisher); zsock_destroy(&compressor_input); zsock_destroy(&compressor_output); device_tracker_destroy(&tracker); for (size_t i = 0; i < num_compressors; i++) zactor_destroy(&compressors[i]); zsys_shutdown(); if (!quiet) printf("[I] terminated\n"); return rc; }
bool zfile_exists (const char *filename) { return zsys_file_exists (filename); }
/// // Return 1 if file exists, else zero bool QmlZsysAttached::fileExists (const QString &filename) { return zsys_file_exists (filename.toUtf8().data()); };
// 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); }
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"); }
/// // Return 1 if file exists, else zero bool QZsys::fileExists (const QString &filename) { bool rv = zsys_file_exists (filename.toUtf8().data()); return rv; }
void zfile_test (bool verbose) { printf (" * zfile: "); // @selftest const char *SELFTEST_DIR_RW = "src/selftest-rw"; const char *testbasedir = "this"; const char *testsubdir = "is/a/test"; const char *testfile = "bilbo"; const char *testlink = "bilbo.ln"; char *basedirpath = NULL; // subdir in a test, under SELFTEST_DIR_RW char *dirpath = NULL; // subdir in a test, under basedirpath char *filepath = NULL; // pathname to testfile in a test, in dirpath char *linkpath = NULL; // pathname to testlink in a test, in dirpath basedirpath = zsys_sprintf ("%s/%s", SELFTEST_DIR_RW, testbasedir); assert (basedirpath); dirpath = zsys_sprintf ("%s/%s", basedirpath, testsubdir); assert (dirpath); filepath = zsys_sprintf ("%s/%s", dirpath, testfile); assert (filepath); linkpath = zsys_sprintf ("%s/%s", dirpath, testlink); assert (linkpath); // This subtest is specifically for NULL as current directory, so // no SELFTEST_DIR_RW here; testfile should have no slashes inside. // Normally tests clean up in zfile_destroy(), but if a selftest run // dies e.g. on assert(), workspace remains dirty. Better clean it up. if (zfile_exists (testfile) ) { if (verbose) zsys_debug ("zfile_test() has to remove ./%s that should not have been here", testfile); zfile_delete (testfile); } zfile_t *file = zfile_new (NULL, testfile); assert (file); assert (streq (zfile_filename (file, "."), testfile)); assert (zfile_is_readable (file) == false); zfile_destroy (&file); // Create a test file in some random subdirectory if (verbose) zsys_debug ("zfile_test() at timestamp %" PRIi64 ": " "Creating new zfile %s", zclock_time(), filepath ); if (zfile_exists (filepath) ) { if (verbose) zsys_debug ("zfile_test() has to remove %s that should not have been here", filepath); zfile_delete (filepath); } file = zfile_new (dirpath, testfile); assert (file); int rc = zfile_output (file); assert (rc == 0); zchunk_t *chunk = zchunk_new (NULL, 100); assert (chunk); zchunk_fill (chunk, 0, 100); // Write 100 bytes at position 1,000,000 in the file if (verbose) zsys_debug ("zfile_test() at timestamp %" PRIi64 ": " "Writing 100 bytes at position 1,000,000 in the file", zclock_time() ); rc = zfile_write (file, chunk, 1000000); if (verbose) zsys_debug ("zfile_test() at timestamp %" PRIi64 ": " "Wrote 100 bytes at position 1,000,000 in the file, result code %d", zclock_time(), rc ); assert (rc == 0); zchunk_destroy (&chunk); zfile_close (file); assert (zfile_is_readable (file)); assert (zfile_cursize (file) == 1000100); if (verbose) zsys_debug ("zfile_test() at timestamp %" PRIi64 ": " "Testing if file is NOT stable (is younger than 1 sec)", zclock_time() ); assert (!zfile_is_stable (file)); if (verbose) zsys_debug ("zfile_test() at timestamp %" PRIi64 ": " "Passed the lag-dependent tests", zclock_time() ); assert (zfile_digest (file)); // Now truncate file from outside int handle = open (filepath, O_WRONLY | O_TRUNC | O_BINARY, 0); assert (handle >= 0); rc = write (handle, "Hello, World\n", 13); assert (rc == 13); close (handle); assert (zfile_has_changed (file)); #ifdef CZMQ_BUILD_DRAFT_API zclock_sleep ((int)zsys_file_stable_age_msec() + 50); #else zclock_sleep (5050); #endif assert (zfile_has_changed (file)); assert (!zfile_is_stable (file)); zfile_restat (file); assert (zfile_is_stable (file)); assert (streq (zfile_digest (file), "4AB299C8AD6ED14F31923DD94F8B5F5CB89DFB54")); // Check we can read from file rc = zfile_input (file); assert (rc == 0); chunk = zfile_read (file, 1000100, 0); assert (chunk); assert (zchunk_size (chunk) == 13); zchunk_destroy (&chunk); zfile_close (file); // Check we can read lines from file rc = zfile_input (file); assert (rc == 0); const char *line = zfile_readln (file); assert (streq (line, "Hello, World")); line = zfile_readln (file); assert (line == NULL); zfile_close (file); // Try some fun with symbolic links zfile_t *link = zfile_new (dirpath, testlink); assert (link); rc = zfile_output (link); assert (rc == 0); fprintf (zfile_handle (link), "%s\n", filepath); zfile_destroy (&link); link = zfile_new (dirpath, testlink); assert (link); rc = zfile_input (link); assert (rc == 0); chunk = zfile_read (link, 1000100, 0); assert (chunk); assert (zchunk_size (chunk) == 13); zchunk_destroy (&chunk); zfile_destroy (&link); // Remove file and directory zdir_t *dir = zdir_new (basedirpath, NULL); assert (dir); assert (zdir_cursize (dir) == 26); zdir_remove (dir, true); assert (zdir_cursize (dir) == 0); zdir_destroy (&dir); // Check we can no longer read from file assert (zfile_is_readable (file)); zfile_restat (file); assert (!zfile_is_readable (file)); rc = zfile_input (file); assert (rc == -1); zfile_destroy (&file); // This set of tests is done, free the strings for reuse zstr_free (&basedirpath); zstr_free (&dirpath); zstr_free (&filepath); zstr_free (&linkpath); const char *eof_checkfile = "eof_checkfile"; filepath = zsys_sprintf ("%s/%s", SELFTEST_DIR_RW, eof_checkfile); assert (filepath); if (zfile_exists (filepath) ) { if (verbose) zsys_debug ("zfile_test() has to remove %s that should not have been here", filepath); zfile_delete (filepath); } zstr_free (&filepath); file = zfile_new (SELFTEST_DIR_RW, eof_checkfile); assert (file); // 1. Write something first rc = zfile_output (file); assert (rc == 0); chunk = zchunk_new ("123456789", 9); assert (chunk); rc = zfile_write (file, chunk, 0); assert (rc == 0); zchunk_destroy (&chunk); zfile_close (file); assert (zfile_cursize (file) == 9); // 2. Read the written something rc = zfile_input (file); assert (rc != -1); // try to read more bytes than there is in the file chunk = zfile_read (file, 1000, 0); assert (zfile_eof(file)); assert (zchunk_streq (chunk, "123456789")); zchunk_destroy (&chunk); // reading is ok chunk = zfile_read (file, 5, 0); assert (!zfile_eof(file)); assert (zchunk_streq (chunk, "12345")); zchunk_destroy (&chunk); // read from non zero offset until the end chunk = zfile_read (file, 5, 5); assert (zfile_eof(file)); assert (zchunk_streq (chunk, "6789")); zchunk_destroy (&chunk); zfile_remove (file); zfile_close (file); zfile_destroy (&file); #ifdef CZMQ_BUILD_DRAFT_API zfile_t *tempfile = zfile_tmp (); assert (tempfile); assert (zfile_filename (tempfile, NULL)); assert (zsys_file_exists (zfile_filename (tempfile, NULL))); zchunk_t *tchunk = zchunk_new ("HELLO", 6); assert (zfile_write (tempfile, tchunk, 0) == 0); zchunk_destroy (&tchunk); char *filename = strdup (zfile_filename (tempfile, NULL)); zfile_destroy (&tempfile); assert (!zsys_file_exists (filename)); zstr_free (&filename); #endif // CZMQ_BUILD_DRAFT_API #if defined (__WINDOWS__) zsys_shutdown(); #endif // @end printf ("OK\n"); }