README.md
1
2[![GitHub release](https://img.shields.io/github/release/zeromq/czmq.svg)](https://github.com/zeromq/czmq/releases)
3[![OBS draft](https://img.shields.io/badge/OBS%20master-draft-yellow.svg)](http://software.opensuse.org/download.html?project=network%3Amessaging%3Azeromq%3Agit-draft&package=czmq)
4[![OBS stable](https://img.shields.io/badge/OBS%20master-stable-yellow.svg)](http://software.opensuse.org/download.html?project=network%3Amessaging%3Azeromq%3Agit-stable&package=czmq)
5<a target="_blank" href="http://webchat.freenode.net?channels=%23zeromq&uio=d4"><img src="https://cloud.githubusercontent.com/assets/493242/14886493/5c660ea2-0d51-11e6-8249-502e6c71e9f2.png" height = "20" /></a>
6[![license](https://img.shields.io/github/license/zeromq/czmq.svg)](https://github.com/zeromq/czmq/blob/master/LICENSE)
7
8# CZMQ - High-level C binding for ØMQ
9
10| Linux & MacOSX | Windows |
11|:--------------:|:--------:|
12|[![Build Status](https://travis-ci.org/zeromq/czmq.png?branch=master)](https://travis-ci.org/zeromq/czmq)|[![Build status](https://ci.appveyor.com/api/projects/status/q7y22juu3pnl5wq6?svg=true)](https://ci.appveyor.com/project/zeromq/czmq)|
13
14## Contents
15
16
17**[Overview](#overview)**
18
19**[Scope and Goals](#scope-and-goals)**
20
21**[Ownership and License](#ownership-and-license)**
22
23**[Using CZMQ](#using-czmq)**
24
25**[Building and Installing](#building-and-installing)**
26
27**[Building on Windows](#building-on-windows)**
28
29**[Linking with an Application](#linking-with-an-application)**
30
31**[Use from Other Languages](#use-from-other-languages)**
32
33**[API v3 Summary](#api-v3-summary)**
34* [zactor - simple actor framework](#zactor---simple-actor-framework)
35* [zauth - authentication for ZeroMQ security mechanisms](#zauth---authentication-for-zeromq-security-mechanisms)
36* [zbeacon - LAN discovery and presence](#zbeacon---lan-discovery-and-presence)
37* [zcert - work with CURVE security certificates](#zcert---work-with-curve-security-certificates)
38* [zcertstore - work with CURVE security certificate stores](#zcertstore---work-with-curve-security-certificate-stores)
39* [zchunk - work with memory chunks](#zchunk---work-with-memory-chunks)
40* [zclock - millisecond clocks and delays](#zclock---millisecond-clocks-and-delays)
41* [zconfig - work with config files written in rfc.zeromq.org/spec:4/ZPL.](#zconfig---work-with-config-files-written-in-rfczeromqorgspec4zpl)
42* [zdigest - provides hashing functions (SHA-1 at present)](#zdigest---provides-hashing-functions-sha-1-at-present)
43* [zdir - work with file-system directories](#zdir---work-with-file-system-directories)
44* [zdir_patch - work with directory patches](#zdir_patch---work-with-directory-patches)
45* [zfile - provides methods to work with files in a portable fashion.](#zfile---provides-methods-to-work-with-files-in-a-portable-fashion)
46* [zframe - working with single message frames](#zframe---working-with-single-message-frames)
47* [zgossip - decentralized configuration management](#zgossip---decentralized-configuration-management)
48* [zhash - simple generic hash container](#zhash---simple-generic-hash-container)
49* [zhashx - extended generic hash container](#zhashx---extended-generic-hash-container)
50* [ziflist - list of network interfaces available on system](#ziflist---list-of-network-interfaces-available-on-system)
51* [zlist - simple generic list container](#zlist---simple-generic-list-container)
52* [zlistx - extended generic list container](#zlistx---extended-generic-list-container)
53* [zloop - event-driven reactor](#zloop---event-driven-reactor)
54* [zmonitor - socket event monitor](#zmonitor---socket-event-monitor)
55* [zmsg - working with multipart messages](#zmsg---working-with-multipart-messages)
56* [zpoller - trivial socket poller class](#zpoller---trivial-socket-poller-class)
57* [zproc - process configuration and status](#zproc---process-configuration-and-status)
58* [zproxy - run a steerable proxy in the background](#zproxy---run-a-steerable-proxy-in-the-background)
59* [zrex - work with regular expressions](#zrex---work-with-regular-expressions)
60* [zsock - high-level socket API that hides libzmq contexts and sockets](#zsock---high-level-socket-api-that-hides-libzmq-contexts-and-sockets)
61* [zstr - sending and receiving strings](#zstr---sending-and-receiving-strings)
62* [zsys - system-level methods](#zsys---system-level-methods)
63* [ztimerset - timer set](#ztimerset---timer-set)
64* [ztrie - simple trie for tokenizable strings](#ztrie---simple-trie-for-tokenizable-strings)
65* [zuuid - UUID support class](#zuuid---uuid-support-class)
66
67**[Error Handling](#error-handling)**
68
69**[CZMQ Actors](#czmq-actors)**
70
71**[Under the Hood](#under-the-hood)**
72
73**[Adding a New Class](#adding-a-new-class)**
74
75**[Documentation](#documentation)**
76
77**[Development](#development)**
78
79**[Porting CZMQ](#porting-czmq)**
80
81**[Hints to Contributors](#hints-to-contributors)**
82
83**[Code Generation](#code-generation)**
84
85**[This Document](#this-document)**
86
87## Overview
88
89### Scope and Goals
90
91CZMQ has these goals:
92
93* To wrap the ØMQ core API in semantics that lead to shorter, more readable applications.
94* To hide as far as possible the differences between different versions of ØMQ (2.x, 3.x, 4.x).
95* To provide a space for development of more sophisticated API semantics.
96* To wrap the ØMQ security features with high-level tools and APIs.
97* To become the basis for other language bindings built on top of CZMQ.
98
99CZMQ grew out of concepts developed in [ØMQ - The Guide](http://zguide.zeromq.org).
100
101<center>
102<img src="https://github.com/zeromq/czmq/raw/master/images/README_1.png" alt="1">
103</center>
104
105### Ownership and License
106
107The contributors are listed in AUTHORS. This project uses the MPL v2 license, see LICENSE.
108
109CZMQ uses the [C4.1 (Collective Code Construction Contract)](http://rfc.zeromq.org/spec:22) process for contributions.
110
111CZMQ uses the [CLASS (C Language Style for Scalabilty)](http://rfc.zeromq.org/spec:21) guide for code style.
112
113To report an issue, use the [CZMQ issue tracker](https://github.com/zeromq/czmq/issues) at github.com.
114
115## Using CZMQ
116
117### Building and Installing
118
119To start with, you need at least these packages:
120
121* {{git-all}} -- git is how we share code with other people.
122
123* {{build-essential}}, {{libtool}}, {{pkg-config}} - the C compiler and related tools.
124
125* {{autotools-dev}}, {{autoconf}}, {{automake}} - the GNU autoconf makefile generators.
126
127* {{cmake}} - the CMake makefile generators (an alternative to autoconf).
128
129Plus some others:
130
131* {{uuid-dev}}, {{libpcre3-dev}} - utility libraries.
132
133* {{valgrind}} - a useful tool for checking your code.
134
135* {{pkg-config}} - an optional useful tool to make building with dependencies easier.
136
137Which we install like this (using the Debian-style apt-get package manager):
138
139 sudo apt-get update
140 sudo apt-get install -y \
141 git-all build-essential libtool \
142 pkg-config autotools-dev autoconf automake cmake \
143 uuid-dev libpcre3-dev valgrind
144
145 # only execute this next line if interested in updating the man pages as well (adds to build time):
146 sudo apt-get install -y asciidoc
147
148Here's how to build CZMQ from GitHub (building from packages is very similar, you don't clone a repo but unpack a tarball), including the libzmq (ZeroMQ core) library (NOTE: skip ldconfig on OSX):
149
150 git clone git://github.com/zeromq/libzmq.git
151 cd libzmq
152 ./autogen.sh
153 # do not specify "--with-libsodium" if you prefer to use internal tweetnacl security implementation (recommended for development)
154 ./configure --with-libsodium
155 make check
156 sudo make install
157 sudo ldconfig
158 cd ..
159
160 git clone git://github.com/zeromq/czmq.git
161 cd czmq
162 ./autogen.sh && ./configure && make check
163 sudo make install
164 sudo ldconfig
165 cd ..
166
167In general CZMQ works best with the latest libzmq master. If you already have an older version of libzmq installed on your system, e.g. in /usr/, then you can install libzmq master to your home directory ($HOME/local):
168
169 # Building libzmq in our home directory
170 ./configure --prefix=$HOME/local
171
172And then to build CZMQ against this installation of libzmq:
173
174 export CFLAGS=-I$HOME/local/include
175 export LDFLAGS=-L$HOME/local/lib64
176 export PKG_CONFIG_PATH=$HOME/local/lib64/pkgconfig
177 ./configure
178
179NOTE: the PKG_CONFIG_PATH is not mandatory, and the actual directory might be different. If you cannot or do not want to use pkg-config, please make sure to MANUALLY add all the necessary CFLAGS and LDFLAGS from all dependencies (for example -DZMQ_BUILD_DRAFT_API=1 if you want the DRAFT APIs).
180
181You will need the pkg-config, libtool, and autoreconf packages. After building, run the CZMQ selftests:
182
183 make check
184
185
186### Building on Windows
187
188To start with, you need MS Visual Studio (C/C++). The free community edition works well.
189
190Then, install git, and make sure it works from a DevStudio command prompt:
191
192```
193git
194```
195
196Now let's build CZMQ from GitHub:
197
198```
199 git clone --depth 1 -b stable https://github.com/jedisct1/libsodium.git
200 cd libsodium\builds\msvc\build
201 buildall.bat
202 cd ..\..\..\..
203
204 :: if libsodium is on disk, the Windows build of libzmq will automatically use it
205 git clone git://github.com/zeromq/libzmq.git
206 cd libzmq\builds\msvc
207 configure.bat
208 cd build
209 buildall.bat
210 cd ..\..\..\..
211
212 git clone git://github.com/zeromq/czmq.git
213 cd czmq\builds\msvc
214 configure.bat
215 cd build
216 buildall.bat
217 cd ..\..\..\..
218```
219
220Let's test by running `czmq_selftest`:
221
222```
223 czmq>dir/s/b czmq_selftest.exe
224 czmq\builds\msvc\vs2013\DebugDEXE\czmq_selftest.exe
225 czmq\builds\msvc\vs2013\DebugLEXE\czmq_selftest.exe
226 czmq\builds\msvc\vs2013\DebugSEXE\czmq_selftest.exe
227 czmq\builds\msvc\vs2013\ReleaseDEXE\czmq_selftest.exe
228 czmq\builds\msvc\vs2013\ReleaseLEXE\czmq_selftest.exe
229 czmq\builds\msvc\vs2013\ReleaseSEXE\czmq_selftest.exe
230 czmq\builds\msvc\vs2013\x64\DebugDEXE\czmq_selftest.exe
231 czmq\builds\msvc\vs2013\x64\DebugLEXE\czmq_selftest.exe
232 czmq\builds\msvc\vs2013\x64\DebugSEXE\czmq_selftest.exe
233 czmq\builds\msvc\vs2013\x64\ReleaseDEXE\czmq_selftest.exe
234 czmq\builds\msvc\vs2013\x64\ReleaseLEXE\czmq_selftest.exe
235 czmq\builds\msvc\vs2013\x64\ReleaseSEXE\czmq_selftest.exe
236
237 :: select your choice and run it
238 czmq\builds\msvc\vs2013\x64\ReleaseDEXE\czmq_selftest.exe
239```
240
241### Linking with an Application
242
243Include `czmq.h` in your application and link with libczmq. Here is a typical gcc link command:
244
245 gcc myapp.c -o myapp -lczmq -lzmq
246
247### Use from Other Languages
248
249This is a list of auto-generated bindings:
250
251* https://github.com/zeromq/czmq/tree/master/bindings/jni - Java
252* https://github.com/zeromq/czmq/tree/master/bindings/nodejs - NodeJS
253* https://github.com/zeromq/czmq/tree/master/bindings/python - Python
254* https://github.com/zeromq/czmq/tree/master/bindings/python_cffi - Python (cffi)
255* https://github.com/zeromq/czmq/tree/master/bindings/qml - QML
256* https://github.com/zeromq/czmq/tree/master/bindings/qt - Qt
257* https://github.com/zeromq/czmq/tree/master/bindings/ruby - Ruby (FFI)
258
259This is a list of known higher-level wrappers around CZMQ:
260
261* https://github.com/1100110/CZMQ - D bindings
262* https://github.com/methodmissing/rbczmq - Ruby
263* https://github.com/paddor/cztop - Ruby, based on generated FFI binding
264* https://github.com/zeromq/pyczmq - Python
265* https://github.com/lhope/cl-czmq - Common Lisp
266* https://github.com/fmp88/ocaml-czmq - Ocaml
267* https://github.com/gar1t/erlang-czmq - Erlang
268* https://github.com/mtortonesi/ruby-czmq-ffi - Ruby FFI
269* https://github.com/zeromq/goczmq - Go
270
271### API v3 Summary
272
273This is the API provided by CZMQ v3.x, in alphabetical order.
274
275#### zactor - simple actor framework
276
277The zactor class provides a simple actor framework. It replaces the
278CZMQ zthread class, which had a complex API that did not fit the CLASS
279standard. A CZMQ actor is implemented as a thread plus a PAIR-PAIR
280pipe. The constructor and destructor are always synchronized, so the
281caller can be sure all resources are created, and destroyed, when these
282calls complete. (This solves a major problem with zthread, that a caller
283could not be sure when a child thread had finished.)
284
285A zactor_t instance acts like a zsock_t and you can pass it to any CZMQ
286method that would take a zsock_t argument, including methods in zframe,
287zmsg, zstr, and zpoller. (zloop somehow escaped and needs catching.)
288
289An actor function MUST call zsock_signal (pipe) when initialized
290and MUST listen to pipe and exit on $TERM command.
291
292Please add '@discuss' section in './../src/zactor.c'.
293
294This is the class interface:
295
296```h
297 // This is a stable class, and may not change except for emergencies. It
298 // is provided in stable builds.
299 // This class has draft methods, which may change over time. They are not
300 // in stable releases, by default. Use --enable-drafts to enable.
301 // Actors get a pipe and arguments from caller
302 typedef void (zactor_fn) (
303 zsock_t *pipe, void *args);
304
305 // Create a new actor passing arbitrary arguments reference.
306 CZMQ_EXPORT zactor_t *
307 zactor_new (zactor_fn task, void *args);
308
309 // Destroy an actor.
310 CZMQ_EXPORT void
311 zactor_destroy (zactor_t **self_p);
312
313 // Send a zmsg message to the actor, take ownership of the message
314 // and destroy when it has been sent.
315 CZMQ_EXPORT int
316 zactor_send (zactor_t *self, zmsg_t **msg_p);
317
318 // Receive a zmsg message from the actor. Returns NULL if the actor
319 // was interrupted before the message could be received, or if there
320 // was a timeout on the actor.
321 // Caller owns return value and must destroy it when done.
322 CZMQ_EXPORT zmsg_t *
323 zactor_recv (zactor_t *self);
324
325 // Probe the supplied object, and report if it looks like a zactor_t.
326 CZMQ_EXPORT bool
327 zactor_is (void *self);
328
329 // Probe the supplied reference. If it looks like a zactor_t instance,
330 // return the underlying libzmq actor handle; else if it looks like
331 // a libzmq actor handle, return the supplied value.
332 CZMQ_EXPORT void *
333 zactor_resolve (void *self);
334
335 // Return the actor's zsock handle. Use this when you absolutely need
336 // to work with the zsock instance rather than the actor.
337 CZMQ_EXPORT zsock_t *
338 zactor_sock (zactor_t *self);
339
340 // Self test of this class.
341 CZMQ_EXPORT void
342 zactor_test (bool verbose);
343
344 #ifdef CZMQ_BUILD_DRAFT_API
345 // Function to be called on zactor_destroy. Default behavior is to send zmsg_t with string "$TERM" in a first frame.
346 //
347 // An example - to send $KTHXBAI string
348 //
349 // if (zstr_send (self->pipe, "$KTHXBAI") == 0)
350 // zsock_wait (self->pipe);
351 typedef void (zactor_destructor_fn) (
352 zactor_t *self);
353
354 // *** Draft method, for development use, may change without warning ***
355 // Change default destructor by custom function. Actor MUST be able to handle new message instead of default $TERM.
356 CZMQ_EXPORT void
357 zactor_set_destructor (zactor_t *self, zactor_destructor_fn destructor);
358
359 #endif // CZMQ_BUILD_DRAFT_API
360```
361Please add '@interface' section in './../src/zactor.c'.
362
363This is the class self test code:
364
365```c
366 zactor_t *actor = zactor_new (echo_actor, "Hello, World");
367 assert (actor);
368 zstr_sendx (actor, "ECHO", "This is a string", NULL);
369 char *string = zstr_recv (actor);
370 assert (streq (string, "This is a string"));
371 free (string);
372 zactor_destroy (&actor);
373
374 // custom destructor
375 // KTHXBAI_actor ends on "$KTHXBAI" string
376 zactor_t *KTHXBAI = zactor_new (KTHXBAI_actor, NULL);
377 assert (KTHXBAI);
378 // which is the one sent by KTHXBAI_destructor
379 zactor_set_destructor (KTHXBAI, KTHXBAI_destructor);
380 zactor_destroy (&KTHXBAI);
381
382 #if defined (__WINDOWS__)
383 zsys_shutdown();
384 #endif
385```
386
387#### zauth - authentication for ZeroMQ security mechanisms
388
389A zauth actor takes over authentication for all incoming connections in
390its context. You can whitelist or blacklist peers based on IP address,
391and define policies for securing PLAIN, CURVE, and GSSAPI connections.
392
393This class replaces zauth_v2, and is meant for applications that use the
394CZMQ v3 API (meaning, zsock).
395
396This is the class interface:
397
398```h
399 #define CURVE_ALLOW_ANY "*"
400
401 // CZMQ v3 API (for use with zsock, not zsocket, which is deprecated).
402 //
403 // Create new zauth actor instance. This installs authentication on all
404 // zsock sockets. Until you add policies, all incoming NULL connections are
405 // allowed (classic ZeroMQ behaviour), and all PLAIN and CURVE connections
406 // are denied:
407 //
408 // zactor_t *auth = zactor_new (zauth, NULL);
409 //
410 // Destroy zauth instance. This removes authentication and allows all
411 // connections to pass, without authentication:
412 //
413 // zactor_destroy (&auth);
414 //
415 // Note that all zauth commands are synchronous, so your application always
416 // waits for a signal from the actor after each command.
417 //
418 // Enable verbose logging of commands and activity. Verbose logging can help
419 // debug non-trivial authentication policies:
420 //
421 // zstr_send (auth, "VERBOSE");
422 // zsock_wait (auth);
423 //
424 // Allow (whitelist) a list of IP addresses. For NULL, all clients from
425 // these addresses will be accepted. For PLAIN and CURVE, they will be
426 // allowed to continue with authentication. You can call this method
427 // multiple times to whitelist more IP addresses. If you whitelist one
428 // or more addresses, any non-whitelisted addresses are treated as
429 // blacklisted:
430 //
431 // zstr_sendx (auth, "ALLOW", "127.0.0.1", "127.0.0.2", NULL);
432 // zsock_wait (auth);
433 //
434 // Deny (blacklist) a list of IP addresses. For all security mechanisms,
435 // this rejects the connection without any further authentication. Use
436 // either a whitelist, or a blacklist, not not both. If you define both
437 // a whitelist and a blacklist, only the whitelist takes effect:
438 //
439 // zstr_sendx (auth, "DENY", "192.168.0.1", "192.168.0.2", NULL);
440 // zsock_wait (auth);
441 //
442 // Configure PLAIN authentication using a plain-text password file. You can
443 // modify the password file at any time; zauth will reload it automatically
444 // if modified externally:
445 //
446 // zstr_sendx (auth, "PLAIN", filename, NULL);
447 // zsock_wait (auth);
448 //
449 // Configure CURVE authentication, using a directory that holds all public
450 // client certificates, i.e. their public keys. The certificates must be in
451 // zcert_save format. You can add and remove certificates in that directory
452 // at any time. To allow all client keys without checking, specify
453 // CURVE_ALLOW_ANY for the directory name:
454 //
455 // zstr_sendx (auth, "CURVE", directory, NULL);
456 // zsock_wait (auth);
457 //
458 // Configure GSSAPI authentication, using an underlying mechanism (usually
459 // Kerberos) to establish a secure context and perform mutual authentication:
460 //
461 // zstr_sendx (auth, "GSSAPI", NULL);
462 // zsock_wait (auth);
463 //
464 // This is the zauth constructor as a zactor_fn:
465 CZMQ_EXPORT void
466 zauth (zsock_t *pipe, void *certstore);
467
468 // Selftest
469 CZMQ_EXPORT void
470 zauth_test (bool verbose);
471```
472Please add '@interface' section in './../src/zauth.c'.
473
474This is the class self test code:
475
476```c
477 // Create temporary directory for test files
478 # define TESTDIR ".test_zauth"
479 zsys_dir_create (TESTDIR);
480
481 // Check there's no authentication
482 zsock_t *server = zsock_new (ZMQ_PULL);
483 assert (server);
484 zsock_t *client = zsock_new (ZMQ_PUSH);
485 assert (client);
486 bool success = s_can_connect (&server, &client, true);
487 assert (success);
488
489 // Install the authenticator
490 zactor_t *auth = zactor_new (zauth, NULL);
491 assert (auth);
492 if (verbose) {
493 zstr_sendx (auth, "VERBOSE", NULL);
494 zsock_wait (auth);
495 }
496 // Check there's no authentication on a default NULL server
497 success = s_can_connect (&server, &client, true);
498 assert (success);
499
500 // When we set a domain on the server, we switch on authentication
501 // for NULL sockets, but with no policies, the client connection
502 // will be allowed.
503 zsock_set_zap_domain (server, "global");
504 success = s_can_connect (&server, &client, true);
505 assert (success);
506
507 // Blacklist 127.0.0.1, connection should fail
508 zsock_set_zap_domain (server, "global");
509 zstr_sendx (auth, "DENY", "127.0.0.1", NULL);
510 zsock_wait (auth);
511 success = s_can_connect (&server, &client, true);
512 assert (!success);
513
514 // Whitelist our address, which overrides the blacklist
515 zsock_set_zap_domain (server, "global");
516 zstr_sendx (auth, "ALLOW", "127.0.0.1", NULL);
517 zsock_wait (auth);
518 success = s_can_connect (&server, &client, true);
519 assert (success);
520
521 // Try PLAIN authentication
522 zsock_set_plain_server (server, 1);
523 zsock_set_plain_username (client, "admin");
524 zsock_set_plain_password (client, "Password");
525 success = s_can_connect (&server, &client, true);
526 assert (!success);
527
528 FILE *password = fopen (TESTDIR "/password-file", "w");
529 assert (password);
530 fprintf (password, "admin=Password\n");
531 fclose (password);
532 zsock_set_plain_server (server, 1);
533 zsock_set_plain_username (client, "admin");
534 zsock_set_plain_password (client, "Password");
535 zstr_sendx (auth, "PLAIN", TESTDIR "/password-file", NULL);
536 zsock_wait (auth);
537 success = s_can_connect (&server, &client, true);
538 assert (success);
539
540 zsock_set_plain_server (server, 1);
541 zsock_set_plain_username (client, "admin");
542 zsock_set_plain_password (client, "Bogus");
543 success = s_can_connect (&server, &client, true);
544 assert (!success);
545
546 if (zsys_has_curve ()) {
547 // Try CURVE authentication
548 // We'll create two new certificates and save the client public
549 // certificate on disk; in a real case we'd transfer this securely
550 // from the client machine to the server machine.
551 zcert_t *server_cert = zcert_new ();
552 assert (server_cert);
553 zcert_t *client_cert = zcert_new ();
554 assert (client_cert);
555 const char *server_key = zcert_public_txt (server_cert);
556
557 // Test without setting-up any authentication
558 zcert_apply (server_cert, server);
559 zcert_apply (client_cert, client);
560 zsock_set_curve_server (server, 1);
561 zsock_set_curve_serverkey (client, server_key);
562 success = s_can_connect (&server, &client, true);
563 assert (!success);
564
565 // Test CURVE_ALLOW_ANY
566 zcert_apply (server_cert, server);
567 zcert_apply (client_cert, client);
568 zsock_set_curve_server (server, 1);
569 zsock_set_curve_serverkey (client, server_key);
570 zstr_sendx (auth, "CURVE", CURVE_ALLOW_ANY, NULL);
571 zsock_wait (auth);
572 success = s_can_connect (&server, &client, true);
573 assert (success);
574
575 // Test full client authentication using certificates
576 zcert_set_meta (client_cert, "Hello", "%s", "World!");
577 zcert_apply (server_cert, server);
578 zcert_apply (client_cert, client);
579 zsock_set_curve_server (server, 1);
580 zsock_set_curve_serverkey (client, server_key);
581 zcert_save_public (client_cert, TESTDIR "/mycert.txt");
582 zstr_sendx (auth, "CURVE", TESTDIR, NULL);
583 zsock_wait (auth);
584 success = s_can_connect (&server, &client, false);
585 assert (success);
586
587 #if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (4, 1, 0))
588 // Test send/recv certificate metadata
589 zframe_t *frame = zframe_recv (server);
590 assert (frame != NULL);
591 const char *meta = zframe_meta (frame, "Hello");
592 assert (meta != NULL);
593 assert (streq (meta, "World!"));
594 zframe_destroy (&frame);
595 s_renew_sockets(&server, &client);
596 #endif
597
598 zcert_destroy (&server_cert);
599 zcert_destroy (&client_cert);
600
601 // Test custom zcertstore
602 zcertstore_t *certstore = zcertstore_new (NULL);
603 zcertstore_set_loader (certstore, s_test_loader, NULL, NULL);
604 zactor_destroy(&auth);
605 auth = zactor_new (zauth, certstore);
606 assert (auth);
607 if (verbose) {
608 zstr_sendx (auth, "VERBOSE", NULL);
609 zsock_wait (auth);
610 }
611
612 byte public_key [32] = { 105, 76, 150, 58, 214, 191, 218, 65, 50, 172,
613 131, 188, 247, 211, 136, 170, 227, 26, 57, 170,
614 185, 63, 246, 225, 177, 230, 12, 8, 134, 136,
615 105, 106 };
616 byte secret_key [32] = { 245, 217, 172, 73, 106, 28, 195, 17, 218, 132,
617 135, 209, 99, 240, 98, 232, 7, 137, 244, 100,
618 242, 23, 29, 114, 70, 223, 83, 1, 113, 207,
619 132, 149 };
620 zcert_t *shared_cert = zcert_new_from (public_key, secret_key);
621 assert (shared_cert);
622 zcert_apply (shared_cert, server);
623 zcert_apply (shared_cert, client);
624 zsock_set_curve_server (server, 1);
625 zsock_set_curve_serverkey (client, "x?T*N/1Y{8goubv{Ts}#&#f}TXJ//DVe#D2HkoLU");
626 success = s_can_connect (&server, &client, true);
627 assert (success);
628 zcert_destroy (&shared_cert);
629 }
630 // Remove the authenticator and check a normal connection works
631 zactor_destroy (&auth);
632 success = s_can_connect (&server, &client, true);
633 assert (success);
634
635 zsock_destroy (&client);
636 zsock_destroy (&server);
637
638 // Delete all test files
639 zdir_t *dir = zdir_new (TESTDIR, NULL);
640 assert (dir);
641 zdir_remove (dir, true);
642 zdir_destroy (&dir);
643 #endif
644
645 #if defined (__WINDOWS__)
646 zsys_shutdown();
647 #endif
648
649```
650
651#### zbeacon - LAN discovery and presence
652
653The zbeacon class implements a peer-to-peer discovery service for local
654networks. A beacon can broadcast and/or capture service announcements
655using UDP messages on the local area network. This implementation uses
656IPv4 UDP broadcasts. You can define the format of your outgoing beacons,
657and set a filter that validates incoming beacons. Beacons are sent and
658received asynchronously in the background.
659
660This class replaces zbeacon_v2, and is meant for applications that use
661the CZMQ v3 API (meaning, zsock).
662
663This is the class interface:
664
665```h
666 // Create new zbeacon actor instance:
667 //
668 // zactor_t *beacon = zactor_new (zbeacon, NULL);
669 //
670 // Destroy zbeacon instance:
671 //
672 // zactor_destroy (&beacon);
673 //
674 // Enable verbose logging of commands and activity:
675 //
676 // zstr_send (beacon, "VERBOSE");
677 //
678 // Configure beacon to run on specified UDP port, and return the name of
679 // the host, which can be used as endpoint for incoming connections. To
680 // force the beacon to operate on a given interface, set the environment
681 // variable ZSYS_INTERFACE, or call zsys_set_interface() before creating
682 // the beacon. If the system does not support UDP broadcasts (lacking a
683 // workable interface), returns an empty hostname:
684 //
685 // // Pictures: 's' = C string, 'i' = int
686 // zsock_send (beacon, "si", "CONFIGURE", port_number);
687 // char *hostname = zstr_recv (beacon);
688 //
689 // Start broadcasting a beacon at a specified interval in msec. The beacon
690 // data can be at most UDP_FRAME_MAX bytes; this constant is defined in
691 // zsys.h to be 255:
692 //
693 // // Pictures: 'b' = byte * data + size_t size
694 // zsock_send (beacon, "sbi", "PUBLISH", data, size, interval);
695 //
696 // Stop broadcasting the beacon:
697 //
698 // zstr_sendx (beacon, "SILENCE", NULL);
699 //
700 // Start listening to beacons from peers. The filter is used to do a prefix
701 // match on received beacons, to remove junk. Note that any received data
702 // that is identical to our broadcast beacon_data is discarded in any case.
703 // If the filter size is zero, we get all peer beacons:
704 //
705 // zsock_send (beacon, "sb", "SUBSCRIBE", filter_data, filter_size);
706 //
707 // Stop listening to other peers
708 //
709 // zstr_sendx (beacon, "UNSUBSCRIBE", NULL);
710 //
711 // Receive next beacon from a peer. Received beacons are always a 2-frame
712 // message containing the ipaddress of the sender, and then the binary
713 // beacon data as published by the sender:
714 //
715 // zmsg_t *msg = zmsg_recv (beacon);
716 //
717 // This is the zbeacon constructor as a zactor_fn:
718 CZMQ_EXPORT void
719 zbeacon (zsock_t *pipe, void *unused);
720
721 // Self test of this class
722 CZMQ_EXPORT void
723 zbeacon_test (bool verbose);
724```
725Please add '@interface' section in './../src/zbeacon.c'.
726
727This is the class self test code:
728
729```c
730 // Test 1 - two beacons, one speaking, one listening
731 // Create speaker beacon to broadcast our service
732 zactor_t *speaker = zactor_new (zbeacon, NULL);
733 assert (speaker);
734 if (verbose)
735 zstr_sendx (speaker, "VERBOSE", NULL);
736
737 zsock_send (speaker, "si", "CONFIGURE", 9999);
738 char *hostname = zstr_recv (speaker);
739 if (!*hostname) {
740 printf ("OK (skipping test, no UDP broadcasting)\n");
741 zactor_destroy (&speaker);
742 free (hostname);
743 return;
744 }
745 free (hostname);
746
747 // Create listener beacon on port 9999 to lookup service
748 zactor_t *listener = zactor_new (zbeacon, NULL);
749 assert (listener);
750 if (verbose)
751 zstr_sendx (listener, "VERBOSE", NULL);
752 zsock_send (listener, "si", "CONFIGURE", 9999);
753 hostname = zstr_recv (listener);
754 assert (*hostname);
755 free (hostname);
756
757 // We will broadcast the magic value 0xCAFE
758 byte announcement [2] = { 0xCA, 0xFE };
759 zsock_send (speaker, "sbi", "PUBLISH", announcement, 2, 100);
760 // We will listen to anything (empty subscription)
761 zsock_send (listener, "sb", "SUBSCRIBE", "", 0);
762
763 // Wait for at most 1/2 second if there's no broadcasting
764 zsock_set_rcvtimeo (listener, 500);
765 char *ipaddress = zstr_recv (listener);
766 if (ipaddress) {
767 zframe_t *content = zframe_recv (listener);
768 assert (zframe_size (content) == 2);
769 assert (zframe_data (content) [0] == 0xCA);
770 assert (zframe_data (content) [1] == 0xFE);
771 zframe_destroy (&content);
772 zstr_free (&ipaddress);
773 zstr_sendx (speaker, "SILENCE", NULL);
774 }
775 zactor_destroy (&listener);
776 zactor_destroy (&speaker);
777
778 // Test subscription filter using a 3-node setup
779 zactor_t *node1 = zactor_new (zbeacon, NULL);
780 assert (node1);
781 zsock_send (node1, "si", "CONFIGURE", 5670);
782 hostname = zstr_recv (node1);
783 assert (*hostname);
784 free (hostname);
785
786 zactor_t *node2 = zactor_new (zbeacon, NULL);
787 assert (node2);
788 zsock_send (node2, "si", "CONFIGURE", 5670);
789 hostname = zstr_recv (node2);
790 assert (*hostname);
791 free (hostname);
792
793 zactor_t *node3 = zactor_new (zbeacon, NULL);
794 assert (node3);
795 zsock_send (node3, "si", "CONFIGURE", 5670);
796 hostname = zstr_recv (node3);
797 assert (*hostname);
798 free (hostname);
799
800 zsock_send (node1, "sbi", "PUBLISH", "NODE/1", 6, 250);
801 zsock_send (node2, "sbi", "PUBLISH", "NODE/2", 6, 250);
802 zsock_send (node3, "sbi", "PUBLISH", "RANDOM", 6, 250);
803 zsock_send (node1, "sb", "SUBSCRIBE", "NODE", 4);
804
805 // Poll on three API sockets at once
806 zpoller_t *poller = zpoller_new (node1, node2, node3, NULL);
807 assert (poller);
808 int64_t stop_at = zclock_mono () + 1000;
809 while (zclock_mono () < stop_at) {
810 long timeout = (long) (stop_at - zclock_mono ());
811 if (timeout < 0)
812 timeout = 0;
813 void *which = zpoller_wait (poller, timeout * ZMQ_POLL_MSEC);
814 if (which) {
815 assert (which == node1);
816 char *ipaddress, *received;
817 zstr_recvx (node1, &ipaddress, &received, NULL);
818 assert (streq (received, "NODE/2"));
819 zstr_free (&ipaddress);
820 zstr_free (&received);
821 }
822 }
823 zpoller_destroy (&poller);
824
825 // Stop listening
826 zstr_sendx (node1, "UNSUBSCRIBE", NULL);
827
828 // Stop all node broadcasts
829 zstr_sendx (node1, "SILENCE", NULL);
830 zstr_sendx (node2, "SILENCE", NULL);
831 zstr_sendx (node3, "SILENCE", NULL);
832
833 // Destroy the test nodes
834 zactor_destroy (&node1);
835 zactor_destroy (&node2);
836 zactor_destroy (&node3);
837
838 #if defined (__WINDOWS__)
839 zsys_shutdown();
840 #endif
841```
842
843#### zcert - work with CURVE security certificates
844
845The zcert class provides a way to create and work with security
846certificates for the ZMQ CURVE mechanism. A certificate contains a
847public + secret key pair, plus metadata. It can be used as a
848temporary object in memory, or persisted to disk. On disk, a
849certificate is stored as two files. One is public and contains only
850the public key. The second is secret and contains both keys. The
851two have the same filename, with the secret file adding "_secret".
852To exchange certificates, send the public file via some secure route.
853Certificates are not signed but are text files that can be verified by
854eye.
855
856Certificates are stored in the ZPL (ZMQ RFC 4) format. They have two
857sections, "metadata" and "curve". The first contains a list of 'name =
858value' pairs, one per line. Values may be enclosed in quotes. The curve
859section has a 'public-key = keyvalue' and, for secret certificates, a
860'secret-key = keyvalue' line. The keyvalue is a Z85-encoded CURVE key.
861
862This is the class interface:
863
864```h
865 // This is a stable class, and may not change except for emergencies. It
866 // is provided in stable builds.
867 // This class has draft methods, which may change over time. They are not
868 // in stable releases, by default. Use --enable-drafts to enable.
869 // Create and initialize a new certificate in memory
870 CZMQ_EXPORT zcert_t *
871 zcert_new (void);
872
873 // Accepts public/secret key pair from caller
874 CZMQ_EXPORT zcert_t *
875 zcert_new_from (const byte *public_key, const byte *secret_key);
876
877 // Load certificate from file
878 CZMQ_EXPORT zcert_t *
879 zcert_load (const char *filename);
880
881 // Destroy a certificate in memory
882 CZMQ_EXPORT void
883 zcert_destroy (zcert_t **self_p);
884
885 // Return public part of key pair as 32-byte binary string
886 CZMQ_EXPORT const byte *
887 zcert_public_key (zcert_t *self);
888
889 // Return secret part of key pair as 32-byte binary string
890 CZMQ_EXPORT const byte *
891 zcert_secret_key (zcert_t *self);
892
893 // Return public part of key pair as Z85 armored string
894 CZMQ_EXPORT const char *
895 zcert_public_txt (zcert_t *self);
896
897 // Return secret part of key pair as Z85 armored string
898 CZMQ_EXPORT const char *
899 zcert_secret_txt (zcert_t *self);
900
901 // Set certificate metadata from formatted string.
902 CZMQ_EXPORT void
903 zcert_set_meta (zcert_t *self, const char *name, const char *format, ...) CHECK_PRINTF (3);
904
905 // Get metadata value from certificate; if the metadata value doesn't
906 // exist, returns NULL.
907 CZMQ_EXPORT const char *
908 zcert_meta (zcert_t *self, const char *name);
909
910 // Get list of metadata fields from certificate. Caller is responsible for
911 // destroying list. Caller should not modify the values of list items.
912 CZMQ_EXPORT zlist_t *
913 zcert_meta_keys (zcert_t *self);
914
915 // Save full certificate (public + secret) to file for persistent storage
916 // This creates one public file and one secret file (filename + "_secret").
917 CZMQ_EXPORT int
918 zcert_save (zcert_t *self, const char *filename);
919
920 // Save public certificate only to file for persistent storage
921 CZMQ_EXPORT int
922 zcert_save_public (zcert_t *self, const char *filename);
923
924 // Save secret certificate only to file for persistent storage
925 CZMQ_EXPORT int
926 zcert_save_secret (zcert_t *self, const char *filename);
927
928 // Apply certificate to socket, i.e. use for CURVE security on socket.
929 // If certificate was loaded from public file, the secret key will be
930 // undefined, and this certificate will not work successfully.
931 CZMQ_EXPORT void
932 zcert_apply (zcert_t *self, void *socket);
933
934 // Return copy of certificate; if certificate is NULL or we exhausted
935 // heap memory, returns NULL.
936 // Caller owns return value and must destroy it when done.
937 CZMQ_EXPORT zcert_t *
938 zcert_dup (zcert_t *self);
939
940 // Return true if two certificates have the same keys
941 CZMQ_EXPORT bool
942 zcert_eq (zcert_t *self, zcert_t *compare);
943
944 // Print certificate contents to stdout
945 CZMQ_EXPORT void
946 zcert_print (zcert_t *self);
947
948 // Self test of this class
949 CZMQ_EXPORT void
950 zcert_test (bool verbose);
951
952 #ifdef CZMQ_BUILD_DRAFT_API
953 // *** Draft method, for development use, may change without warning ***
954 // Unset certificate metadata.
955 CZMQ_EXPORT void
956 zcert_unset_meta (zcert_t *self, const char *name);
957
958 #endif // CZMQ_BUILD_DRAFT_API
959```
960Please add '@interface' section in './../src/zcert.c'.
961
962This is the class self test code:
963
964```c
965 // Create temporary directory for test files
966 # define TESTDIR ".test_zcert"
967 zsys_dir_create (TESTDIR);
968
969 // Create a simple certificate with metadata
970 zcert_t *cert = zcert_new ();
971 assert (cert);
972 zcert_set_meta (cert, "email", "ph@imatix.com");
973 zcert_set_meta (cert, "name", "Pieter Hintjens");
974 zcert_set_meta (cert, "organization", "iMatix Corporation");
975 zcert_set_meta (cert, "version", "%d", 1);
976 zcert_set_meta (cert, "delete_me", "now");
977 zcert_unset_meta (cert, "delete_me");
978 assert (streq (zcert_meta (cert, "email"), "ph@imatix.com"));
979 zlist_t *keys = zcert_meta_keys (cert);
980 assert (zlist_size (keys) == 4);
981 zlist_destroy (&keys);
982
983 // Check the dup and eq methods
984 zcert_t *shadow = zcert_dup (cert);
985 assert (zcert_eq (cert, shadow));
986 zcert_destroy (&shadow);
987
988 // Check we can save and load certificate
989 zcert_save (cert, TESTDIR "/mycert.txt");
990 assert (zsys_file_exists (TESTDIR "/mycert.txt"));
991 assert (zsys_file_exists (TESTDIR "/mycert.txt_secret"));
992
993 // Load certificate, will in fact load secret one
994 shadow = zcert_load (TESTDIR "/mycert.txt");
995 assert (shadow);
996 assert (zcert_eq (cert, shadow));
997 zcert_destroy (&shadow);
998
999 // Delete secret certificate, load public one
1000 int rc = zsys_file_delete (TESTDIR "/mycert.txt_secret");
1001 assert (rc == 0);
1002 shadow = zcert_load (TESTDIR "/mycert.txt");
1003
1004 // 32-byte null key encodes as 40 '0' characters
1005 assert (streq (zcert_secret_txt (shadow), FORTY_ZEROES));
1006
1007 zcert_destroy (&shadow);
1008 zcert_destroy (&cert);
1009
1010 // Delete all test files
1011 zdir_t *dir = zdir_new (TESTDIR, NULL);
1012 assert (dir);
1013 zdir_remove (dir, true);
1014 zdir_destroy (&dir);
1015
1016 #if defined (__WINDOWS__)
1017 zsys_shutdown();
1018 #endif
1019```
1020
1021#### zcertstore - work with CURVE security certificate stores
1022
1023To authenticate new clients using the ZeroMQ CURVE security mechanism,
1024we have to check that the client's public key matches a key we know and
1025accept. There are numerous ways to store accepted client public keys.
1026The mechanism CZMQ implements is "certificates" (plain text files) held
1027in a "certificate store" (a disk directory). This class works with such
1028certificate stores, and lets you easily load them from disk, and check
1029if a given client public key is known or not. The zcert class does the
1030work of managing a single certificate.
1031
1032The certificate store can be memory-only, in which case you can load it
1033yourself by inserting certificate objects one by one, or it can be loaded
1034from disk, in which case you can add, modify, or remove certificates on
1035disk at any time, and the store will detect such changes and refresh
1036itself automatically. In most applications you won't use this class
1037directly but through the zauth class, which provides a high-level API for
1038authentication (and manages certificate stores for you). To actually
1039create certificates on disk, use the zcert class in code, or the
1040tools/zmakecert.c command line tool, or any text editor. The format of a
1041certificate file is defined in the zcert man page.
1042
1043This is the class interface:
1044
1045```h
1046 // This is a stable class, and may not change except for emergencies. It
1047 // is provided in stable builds.
1048 // This class has draft methods, which may change over time. They are not
1049 // in stable releases, by default. Use --enable-drafts to enable.
1050 // Create a new certificate store from a disk directory, loading and
1051 // indexing all certificates in that location. The directory itself may be
1052 // absent, and created later, or modified at any time. The certificate store
1053 // is automatically refreshed on any zcertstore_lookup() call. If the
1054 // location is specified as NULL, creates a pure-memory store, which you
1055 // can work with by inserting certificates at runtime.
1056 CZMQ_EXPORT zcertstore_t *
1057 zcertstore_new (const char *location);
1058
1059 // Destroy a certificate store object in memory. Does not affect anything
1060 // stored on disk.
1061 CZMQ_EXPORT void
1062 zcertstore_destroy (zcertstore_t **self_p);
1063
1064 // Look up certificate by public key, returns zcert_t object if found,
1065 // else returns NULL. The public key is provided in Z85 text format.
1066 CZMQ_EXPORT zcert_t *
1067 zcertstore_lookup (zcertstore_t *self, const char *public_key);
1068
1069 // Insert certificate into certificate store in memory. Note that this
1070 // does not save the certificate to disk. To do that, use zcert_save()
1071 // directly on the certificate. Takes ownership of zcert_t object.
1072 CZMQ_EXPORT void
1073 zcertstore_insert (zcertstore_t *self, zcert_t **cert_p);
1074
1075 // Print list of certificates in store to logging facility
1076 CZMQ_EXPORT void
1077 zcertstore_print (zcertstore_t *self);
1078
1079 // Self test of this class
1080 CZMQ_EXPORT void
1081 zcertstore_test (bool verbose);
1082
1083 #ifdef CZMQ_BUILD_DRAFT_API
1084 // Loaders retrieve certificates from an arbitrary source.
1085 typedef void (zcertstore_loader) (
1086 zcertstore_t *self);
1087
1088 // Destructor for loader state.
1089 typedef void (zcertstore_destructor) (
1090 void **self_p);
1091
1092 // *** Draft method, for development use, may change without warning ***
1093 // Override the default disk loader with a custom loader fn.
1094 CZMQ_EXPORT void
1095 zcertstore_set_loader (zcertstore_t *self, zcertstore_loader loader, zcertstore_destructor destructor, void *state);
1096
1097 // *** Draft method, for development use, may change without warning ***
1098 // Empty certificate hashtable. This wrapper exists to be friendly to bindings,
1099 // which don't usually have access to struct internals.
1100 CZMQ_EXPORT void
1101 zcertstore_empty (zcertstore_t *self);
1102
1103 #endif // CZMQ_BUILD_DRAFT_API
1104```
1105Please add '@interface' section in './../src/zcertstore.c'.
1106
1107This is the class self test code:
1108
1109```c
1110 // Create temporary directory for test files
1111 # define TESTDIR ".test_zcertstore"
1112 zsys_dir_create (TESTDIR);
1113
1114 // Load certificate store from disk; it will be empty
1115 zcertstore_t *certstore = zcertstore_new (TESTDIR);
1116 assert (certstore);
1117
1118 // Create a single new certificate and save to disk
1119 zcert_t *cert = zcert_new ();
1120 assert (cert);
1121 char *client_key = strdup (zcert_public_txt (cert));
1122 assert (client_key);
1123 zcert_set_meta (cert, "name", "John Doe");
1124 zcert_save (cert, TESTDIR "/mycert.txt");
1125 zcert_destroy (&cert);
1126
1127 // Check that certificate store refreshes as expected
1128 cert = zcertstore_lookup (certstore, client_key);
1129 assert (cert);
1130 assert (streq (zcert_meta (cert, "name"), "John Doe"));
1131
1132 // Test custom loader
1133 test_loader_state *state = (test_loader_state *) zmalloc (sizeof (test_loader_state));
1134 state->index = 0;
1135 zcertstore_set_loader (certstore, s_test_loader, s_test_destructor, (void *)state);
1136 #if (ZMQ_VERSION_MAJOR >= 4)
1137 cert = zcertstore_lookup (certstore, client_key);
1138 assert (cert == NULL);
1139 cert = zcertstore_lookup (certstore, "abcdefghijklmnopqrstuvwxyzabcdefghijklmn");
1140 assert (cert);
1141 #endif
1142
1143 free (client_key);
1144
1145 if (verbose)
1146 zcertstore_print (certstore);
1147 zcertstore_destroy (&certstore);
1148
1149 // Delete all test files
1150 zdir_t *dir = zdir_new (TESTDIR, NULL);
1151 assert (dir);
1152 zdir_remove (dir, true);
1153 zdir_destroy (&dir);
1154
1155 #if defined (__WINDOWS__)
1156 zsys_shutdown();
1157 #endif
1158```
1159
1160#### zchunk - work with memory chunks
1161
1162The zchunk class works with variable sized blobs. Not as efficient as
1163ZeroMQ's messages but they do less weirdness and so are easier to understand.
1164The chunk class has methods to read and write chunks from disk.
1165
1166Please add '@discuss' section in './../src/zchunk.c'.
1167
1168This is the class interface:
1169
1170```h
1171 // This is a stable class, and may not change except for emergencies. It
1172 // is provided in stable builds.
1173 // Create a new chunk of the specified size. If you specify the data, it
1174 // is copied into the chunk. If you do not specify the data, the chunk is
1175 // allocated and left empty, and you can then add data using zchunk_append.
1176 CZMQ_EXPORT zchunk_t *
1177 zchunk_new (const void *data, size_t size);
1178
1179 // Destroy a chunk
1180 CZMQ_EXPORT void
1181 zchunk_destroy (zchunk_t **self_p);
1182
1183 // Resizes chunk max_size as requested; chunk_cur size is set to zero
1184 CZMQ_EXPORT void
1185 zchunk_resize (zchunk_t *self, size_t size);
1186
1187 // Return chunk cur size
1188 CZMQ_EXPORT size_t
1189 zchunk_size (zchunk_t *self);
1190
1191 // Return chunk max size
1192 CZMQ_EXPORT size_t
1193 zchunk_max_size (zchunk_t *self);
1194
1195 // Return chunk data
1196 CZMQ_EXPORT byte *
1197 zchunk_data (zchunk_t *self);
1198
1199 // Set chunk data from user-supplied data; truncate if too large. Data may
1200 // be null. Returns actual size of chunk
1201 CZMQ_EXPORT size_t
1202 zchunk_set (zchunk_t *self, const void *data, size_t size);
1203
1204 // Fill chunk data from user-supplied octet
1205 CZMQ_EXPORT size_t
1206 zchunk_fill (zchunk_t *self, byte filler, size_t size);
1207
1208 // Append user-supplied data to chunk, return resulting chunk size. If the
1209 // data would exceeded the available space, it is truncated. If you want to
1210 // grow the chunk to accommodate new data, use the zchunk_extend method.
1211 CZMQ_EXPORT size_t
1212 zchunk_append (zchunk_t *self, const void *data, size_t size);
1213
1214 // Append user-supplied data to chunk, return resulting chunk size. If the
1215 // data would exceeded the available space, the chunk grows in size.
1216 CZMQ_EXPORT size_t
1217 zchunk_extend (zchunk_t *self, const void *data, size_t size);
1218
1219 // Copy as much data from 'source' into the chunk as possible; returns the
1220 // new size of chunk. If all data from 'source' is used, returns exhausted
1221 // on the source chunk. Source can be consumed as many times as needed until
1222 // it is exhausted. If source was already exhausted, does not change chunk.
1223 CZMQ_EXPORT size_t
1224 zchunk_consume (zchunk_t *self, zchunk_t *source);
1225
1226 // Returns true if the chunk was exhausted by consume methods, or if the
1227 // chunk has a size of zero.
1228 CZMQ_EXPORT bool
1229 zchunk_exhausted (zchunk_t *self);
1230
1231 // Read chunk from an open file descriptor
1232 // Caller owns return value and must destroy it when done.
1233 CZMQ_EXPORT zchunk_t *
1234 zchunk_read (FILE *handle, size_t bytes);
1235
1236 // Write chunk to an open file descriptor
1237 CZMQ_EXPORT int
1238 zchunk_write (zchunk_t *self, FILE *handle);
1239
1240 // Try to slurp an entire file into a chunk. Will read up to maxsize of
1241 // the file. If maxsize is 0, will attempt to read the entire file and
1242 // fail with an assertion if that cannot fit into memory. Returns a new
1243 // chunk containing the file data, or NULL if the file could not be read.
1244 // Caller owns return value and must destroy it when done.
1245 CZMQ_EXPORT zchunk_t *
1246 zchunk_slurp (const char *filename, size_t maxsize);
1247
1248 // Create copy of chunk, as new chunk object. Returns a fresh zchunk_t
1249 // object, or null if there was not enough heap memory. If chunk is null,
1250 // returns null.
1251 // Caller owns return value and must destroy it when done.
1252 CZMQ_EXPORT zchunk_t *
1253 zchunk_dup (zchunk_t *self);
1254
1255 // Return chunk data encoded as printable hex string. Caller must free
1256 // string when finished with it.
1257 // Caller owns return value and must destroy it when done.
1258 CZMQ_EXPORT char *
1259 zchunk_strhex (zchunk_t *self);
1260
1261 // Return chunk data copied into freshly allocated string
1262 // Caller must free string when finished with it.
1263 // Caller owns return value and must destroy it when done.
1264 CZMQ_EXPORT char *
1265 zchunk_strdup (zchunk_t *self);
1266
1267 // Return TRUE if chunk body is equal to string, excluding terminator
1268 CZMQ_EXPORT bool
1269 zchunk_streq (zchunk_t *self, const char *string);
1270
1271 // Transform zchunk into a zframe that can be sent in a message.
1272 // Caller owns return value and must destroy it when done.
1273 CZMQ_EXPORT zframe_t *
1274 zchunk_pack (zchunk_t *self);
1275
1276 // Transform a zframe into a zchunk.
1277 // Caller owns return value and must destroy it when done.
1278 CZMQ_EXPORT zchunk_t *
1279 zchunk_unpack (zframe_t *frame);
1280
1281 // Calculate SHA1 digest for chunk, using zdigest class.
1282 CZMQ_EXPORT const char *
1283 zchunk_digest (zchunk_t *self);
1284
1285 // Dump chunk to FILE stream, for debugging and tracing.
1286 CZMQ_EXPORT void
1287 zchunk_fprint (zchunk_t *self, FILE *file);
1288
1289 // Dump message to stderr, for debugging and tracing.
1290 // See zchunk_fprint for details
1291 CZMQ_EXPORT void
1292 zchunk_print (zchunk_t *self);
1293
1294 // Probe the supplied object, and report if it looks like a zchunk_t.
1295 CZMQ_EXPORT bool
1296 zchunk_is (void *self);
1297
1298 // Self test of this class.
1299 CZMQ_EXPORT void
1300 zchunk_test (bool verbose);
1301
1302```
1303Please add '@interface' section in './../src/zchunk.c'.
1304
1305This is the class self test code:
1306
1307```c
1308 zchunk_t *chunk = zchunk_new ("1234567890", 10);
1309 assert (chunk);
1310 assert (zchunk_size (chunk) == 10);
1311 assert (memcmp (zchunk_data (chunk), "1234567890", 10) == 0);
1312 zchunk_destroy (&chunk);
1313
1314 chunk = zchunk_new (NULL, 10);
1315 assert (chunk);
1316 zchunk_append (chunk, "12345678", 8);
1317 zchunk_append (chunk, "90ABCDEF", 8);
1318 zchunk_append (chunk, "GHIJKLMN", 8);
1319 assert (memcmp (zchunk_data (chunk), "1234567890", 10) == 0);
1320 assert (zchunk_size (chunk) == 10);
1321 assert (zchunk_streq (chunk, "1234567890"));
1322 assert (streq (zchunk_digest (chunk), "01B307ACBA4F54F55AAFC33BB06BBBF6CA803E9A"));
1323 char *string = zchunk_strdup (chunk);
1324 assert (streq (string, "1234567890"));
1325 free (string);
1326 string = zchunk_strhex (chunk);
1327 assert (streq (string, "31323334353637383930"));
1328 free (string);
1329
1330 zframe_t *frame = zchunk_pack (chunk);
1331 assert (frame);
1332
1333 zchunk_t *chunk2 = zchunk_unpack (frame);
1334 assert (chunk2);
1335 assert (memcmp (zchunk_data (chunk2), "1234567890", 10) == 0);
1336 zframe_destroy (&frame);
1337 zchunk_destroy (&chunk2);
1338
1339 zchunk_t *copy = zchunk_dup (chunk);
1340 assert (copy);
1341 assert (memcmp (zchunk_data (copy), "1234567890", 10) == 0);
1342 assert (zchunk_size (copy) == 10);
1343 zchunk_destroy (©);
1344 zchunk_destroy (&chunk);
1345
1346 chunk = zchunk_new (NULL, 0);
1347 zchunk_extend (chunk, "12345678", 8);
1348 zchunk_extend (chunk, "90ABCDEF", 8);
1349 zchunk_extend (chunk, "GHIJKLMN", 8);
1350 assert (zchunk_size (chunk) == 24);
1351 assert (zchunk_streq (chunk, "1234567890ABCDEFGHIJKLMN"));
1352 zchunk_destroy (&chunk);
1353
1354 copy = zchunk_new ("1234567890abcdefghij", 20);
1355 assert (copy);
1356 chunk = zchunk_new (NULL, 8);
1357 assert (chunk);
1358 zchunk_consume (chunk, copy);
1359 assert (!zchunk_exhausted (copy));
1360 assert (memcmp (zchunk_data (chunk), "12345678", 8) == 0);
1361 zchunk_set (chunk, NULL, 0);
1362 zchunk_consume (chunk, copy);
1363 assert (!zchunk_exhausted (copy));
1364 assert (memcmp (zchunk_data (chunk), "90abcdef", 8) == 0);
1365 zchunk_set (chunk, NULL, 0);
1366 zchunk_consume (chunk, copy);
1367 assert (zchunk_exhausted (copy));
1368 assert (zchunk_size (chunk) == 4);
1369 assert (memcmp (zchunk_data (chunk), "ghij", 4) == 0);
1370 zchunk_destroy (©);
1371 zchunk_destroy (&chunk);
1372
1373 #if defined (__WINDOWS__)
1374 zsys_shutdown();
1375 #endif
1376```
1377
1378#### zclock - millisecond clocks and delays
1379
1380The zclock class provides essential sleep and system time functions,
1381used to slow down threads for testing, and calculate timers for polling.
1382Wraps the non-portable system calls in a simple portable API.
1383
1384The Win32 Sleep() call defaults to 16ms resolution unless the system
1385timer resolution is increased with a call to timeBeginPeriod() permitting
13861ms granularity.
1387
1388This is the class interface:
1389
1390```h
1391 // This is a stable class, and may not change except for emergencies. It
1392 // is provided in stable builds.
1393 // Sleep for a number of milliseconds
1394 CZMQ_EXPORT void
1395 zclock_sleep (int msecs);
1396
1397 // Return current system clock as milliseconds. Note that this clock can
1398 // jump backwards (if the system clock is changed) so is unsafe to use for
1399 // timers and time offsets. Use zclock_mono for that instead.
1400 CZMQ_EXPORT int64_t
1401 zclock_time (void);
1402
1403 // Return current monotonic clock in milliseconds. Use this when you compute
1404 // time offsets. The monotonic clock is not affected by system changes and
1405 // so will never be reset backwards, unlike a system clock.
1406 CZMQ_EXPORT int64_t
1407 zclock_mono (void);
1408
1409 // Return current monotonic clock in microseconds. Use this when you compute
1410 // time offsets. The monotonic clock is not affected by system changes and
1411 // so will never be reset backwards, unlike a system clock.
1412 CZMQ_EXPORT int64_t
1413 zclock_usecs (void);
1414
1415 // Return formatted date/time as fresh string. Free using zstr_free().
1416 // Caller owns return value and must destroy it when done.
1417 CZMQ_EXPORT char *
1418 zclock_timestr (void);
1419
1420 // Self test of this class.
1421 CZMQ_EXPORT void
1422 zclock_test (bool verbose);
1423
1424```
1425Please add '@interface' section in './../src/zclock.c'.
1426
1427This is the class self test code:
1428
1429```c
1430 int64_t start = zclock_time ();
1431 zclock_sleep (10);
1432 assert ((zclock_time () - start) >= 10);
1433 start = zclock_mono ();
1434 int64_t usecs = zclock_usecs ();
1435 zclock_sleep (10);
1436 assert ((zclock_mono () - start) >= 10);
1437 assert ((zclock_usecs () - usecs) >= 10000);
1438 char *timestr = zclock_timestr ();
1439 if (verbose)
1440 puts (timestr);
1441 free (timestr);
1442
1443 #if defined (__WINDOWS__)
1444 zsys_shutdown();
1445 #endif
1446```
1447
1448#### zconfig - work with config files written in rfc.zeromq.org/spec:4/ZPL.
1449
1450Lets applications load, work with, and save configuration files.
1451This implements rfc.zeromq.org/spec:4/ZPL, which is a simple structured
1452text format for configuration files.
1453
1454Here is an example ZPL stream and corresponding config structure:
1455
1456 context
1457 iothreads = 1
1458 verbose = 1 # Ask for a trace
1459 main
1460 type = zqueue # ZMQ_DEVICE type
1461 frontend
1462 option
1463 hwm = 1000
1464 swap = 25000000 # 25MB
1465 bind = 'inproc://addr1'
1466 bind = 'ipc://addr2'
1467 backend
1468 bind = inproc://addr3
1469
1470 root Down = child
1471 | Across = next
1472 v
1473 context-->main
1474 | |
1475 | v
1476 | type=queue-->frontend-->backend
1477 | | |
1478 | | v
1479 | | bind=inproc://addr3
1480 | v
1481 | option-->bind=inproc://addr1-->bind=ipc://addr2
1482 | |
1483 | v
1484 | hwm=1000-->swap=25000000
1485 v
1486 iothreads=1-->verbose=false
1487
1488This is the class interface:
1489
1490```h
1491 // This is a stable class, and may not change except for emergencies. It
1492 // is provided in stable builds.
1493 //
1494 typedef int (zconfig_fct) (
1495 zconfig_t *self, void *arg, int level);
1496
1497 // Create new config item
1498 CZMQ_EXPORT zconfig_t *
1499 zconfig_new (const char *name, zconfig_t *parent);
1500
1501 // Load a config tree from a specified ZPL text file; returns a zconfig_t
1502 // reference for the root, if the file exists and is readable. Returns NULL
1503 // if the file does not exist.
1504 CZMQ_EXPORT zconfig_t *
1505 zconfig_load (const char *filename);
1506
1507 // Equivalent to zconfig_load, taking a format string instead of a fixed
1508 // filename.
1509 CZMQ_EXPORT zconfig_t *
1510 zconfig_loadf (const char *format, ...) CHECK_PRINTF (1);
1511
1512 // Destroy a config item and all its children
1513 CZMQ_EXPORT void
1514 zconfig_destroy (zconfig_t **self_p);
1515
1516 // Return name of config item
1517 CZMQ_EXPORT char *
1518 zconfig_name (zconfig_t *self);
1519
1520 // Return value of config item
1521 CZMQ_EXPORT char *
1522 zconfig_value (zconfig_t *self);
1523
1524 // Insert or update configuration key with value
1525 CZMQ_EXPORT void
1526 zconfig_put (zconfig_t *self, const char *path, const char *value);
1527
1528 // Equivalent to zconfig_put, accepting a format specifier and variable
1529 // argument list, instead of a single string value.
1530 CZMQ_EXPORT void
1531 zconfig_putf (zconfig_t *self, const char *path, const char *format, ...) CHECK_PRINTF (3);
1532
1533 // Get value for config item into a string value; leading slash is optional
1534 // and ignored.
1535 CZMQ_EXPORT char *
1536 zconfig_get (zconfig_t *self, const char *path, const char *default_value);
1537
1538 // Set config item name, name may be NULL
1539 CZMQ_EXPORT void
1540 zconfig_set_name (zconfig_t *self, const char *name);
1541
1542 // Set new value for config item. The new value may be a string, a printf
1543 // format, or NULL. Note that if string may possibly contain '%', or if it
1544 // comes from an insecure source, you must use '%s' as the format, followed
1545 // by the string.
1546 CZMQ_EXPORT void
1547 zconfig_set_value (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2);
1548
1549 // Find our first child, if any
1550 CZMQ_EXPORT zconfig_t *
1551 zconfig_child (zconfig_t *self);
1552
1553 // Find our first sibling, if any
1554 CZMQ_EXPORT zconfig_t *
1555 zconfig_next (zconfig_t *self);
1556
1557 // Find a config item along a path; leading slash is optional and ignored.
1558 CZMQ_EXPORT zconfig_t *
1559 zconfig_locate (zconfig_t *self, const char *path);
1560
1561 // Locate the last config item at a specified depth
1562 CZMQ_EXPORT zconfig_t *
1563 zconfig_at_depth (zconfig_t *self, int level);
1564
1565 // Execute a callback for each config item in the tree; returns zero if
1566 // successful, else -1.
1567 CZMQ_EXPORT int
1568 zconfig_execute (zconfig_t *self, zconfig_fct handler, void *arg);
1569
1570 // Add comment to config item before saving to disk. You can add as many
1571 // comment lines as you like. If you use a null format, all comments are
1572 // deleted.
1573 CZMQ_EXPORT void
1574 zconfig_set_comment (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2);
1575
1576 // Return comments of config item, as zlist.
1577 CZMQ_EXPORT zlist_t *
1578 zconfig_comments (zconfig_t *self);
1579
1580 // Save a config tree to a specified ZPL text file, where a filename
1581 // "-" means dump to standard output.
1582 CZMQ_EXPORT int
1583 zconfig_save (zconfig_t *self, const char *filename);
1584
1585 // Equivalent to zconfig_save, taking a format string instead of a fixed
1586 // filename.
1587 CZMQ_EXPORT int
1588 zconfig_savef (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2);
1589
1590 // Report filename used during zconfig_load, or NULL if none
1591 CZMQ_EXPORT const char *
1592 zconfig_filename (zconfig_t *self);
1593
1594 // Reload config tree from same file that it was previously loaded from.
1595 // Returns 0 if OK, -1 if there was an error (and then does not change
1596 // existing data).
1597 CZMQ_EXPORT int
1598 zconfig_reload (zconfig_t **self_p);
1599
1600 // Load a config tree from a memory chunk
1601 CZMQ_EXPORT zconfig_t *
1602 zconfig_chunk_load (zchunk_t *chunk);
1603
1604 // Save a config tree to a new memory chunk
1605 CZMQ_EXPORT zchunk_t *
1606 zconfig_chunk_save (zconfig_t *self);
1607
1608 // Load a config tree from a null-terminated string
1609 // Caller owns return value and must destroy it when done.
1610 CZMQ_EXPORT zconfig_t *
1611 zconfig_str_load (const char *string);
1612
1613 // Save a config tree to a new null terminated string
1614 // Caller owns return value and must destroy it when done.
1615 CZMQ_EXPORT char *
1616 zconfig_str_save (zconfig_t *self);
1617
1618 // Return true if a configuration tree was loaded from a file and that
1619 // file has changed in since the tree was loaded.
1620 CZMQ_EXPORT bool
1621 zconfig_has_changed (zconfig_t *self);
1622
1623 // Print the config file to open stream
1624 CZMQ_EXPORT void
1625 zconfig_fprint (zconfig_t *self, FILE *file);
1626
1627 // Print properties of object
1628 CZMQ_EXPORT void
1629 zconfig_print (zconfig_t *self);
1630
1631 // Self test of this class
1632 CZMQ_EXPORT void
1633 zconfig_test (bool verbose);
1634
1635```
1636Please add '@interface' section in './../src/zconfig.c'.
1637
1638This is the class self test code:
1639
1640```c
1641 // Create temporary directory for test files
1642 # define TESTDIR ".test_zconfig"
1643 zsys_dir_create (TESTDIR);
1644
1645 zconfig_t *root = zconfig_new ("root", NULL);
1646 assert (root);
1647 zconfig_t *section, *item;
1648
1649 section = zconfig_new ("headers", root);
1650 assert (section);
1651 item = zconfig_new ("email", section);
1652 assert (item);
1653 zconfig_set_value (item, "some@random.com");
1654 item = zconfig_new ("name", section);
1655 assert (item);
1656 zconfig_set_value (item, "Justin Kayce");
1657 zconfig_putf (root, "/curve/secret-key", "%s", "Top Secret");
1658 zconfig_set_comment (root, " CURVE certificate");
1659 zconfig_set_comment (root, " -----------------");
1660 assert (zconfig_comments (root));
1661 zconfig_save (root, TESTDIR "/test.cfg");
1662 zconfig_destroy (&root);
1663 root = zconfig_load (TESTDIR "/test.cfg");
1664 if (verbose)
1665 zconfig_save (root, "-");
1666 assert (streq (zconfig_filename (root), TESTDIR "/test.cfg"));
1667
1668 char *email = zconfig_get (root, "/headers/email", NULL);
1669 assert (email);
1670 assert (streq (email, "some@random.com"));
1671 char *passwd = zconfig_get (root, "/curve/secret-key", NULL);
1672 assert (passwd);
1673 assert (streq (passwd, "Top Secret"));
1674
1675 zconfig_savef (root, "%s/%s", TESTDIR, "test.cfg");
1676 assert (!zconfig_has_changed (root));
1677 int rc = zconfig_reload (&root);
1678 assert (rc == 0);
1679 assert (!zconfig_has_changed (root));
1680 zconfig_destroy (&root);
1681
1682 // Test chunk load/save
1683 root = zconfig_new ("root", NULL);
1684 assert (root);
1685 section = zconfig_new ("section", root);
1686 assert (section);
1687 item = zconfig_new ("value", section);
1688 assert (item);
1689 zconfig_set_value (item, "somevalue");
1690 zconfig_t *search = zconfig_locate (root, "section/value");
1691 assert (search == item);
1692 zchunk_t *chunk = zconfig_chunk_save (root);
1693 assert (strlen ((char *) zchunk_data (chunk)) == 32);
1694 char *string = zconfig_str_save (root);
1695 assert (string);
1696 assert (streq (string, (char *) zchunk_data (chunk)));
1697 free (string);
1698 assert (chunk);
1699 zconfig_destroy (&root);
1700
1701 root = zconfig_chunk_load (chunk);
1702 assert (root);
1703 char *value = zconfig_get (root, "/section/value", NULL);
1704 assert (value);
1705 assert (streq (value, "somevalue"));
1706
1707 // Test config can't be saved to a file in a path that doesn't
1708 // exist or isn't writable
1709 rc = zconfig_savef (root, "%s/path/that/doesnt/exist/%s", TESTDIR, "test.cfg");
1710 assert (rc == -1);
1711
1712 zconfig_destroy (&root);
1713 zchunk_destroy (&chunk);
1714
1715 // Test str_load
1716 zconfig_t *config = zconfig_str_load (
1717 "malamute\n"
1718 " endpoint = ipc://@/malamute\n"
1719 " producer = STREAM\n"
1720 " consumer\n"
1721 " STREAM2 = .*\n"
1722 " STREAM3 = HAM\n"
1723 "server\n"
1724 " verbose = true\n"
1725 );
1726 assert (config);
1727 assert (streq (zconfig_get (config, "malamute/endpoint", NULL), "ipc://@/malamute"));
1728 assert (streq (zconfig_get (config, "malamute/producer", NULL), "STREAM"));
1729 assert (zconfig_locate (config, "malamute/consumer"));
1730
1731 zconfig_t *c = zconfig_child (zconfig_locate (config, "malamute/consumer"));
1732 assert (c);
1733 assert (streq (zconfig_name (c), "STREAM2"));
1734 assert (streq (zconfig_value (c), ".*"));
1735
1736 c = zconfig_next (c);
1737 assert (c);
1738 assert (streq (zconfig_name (c), "STREAM3"));
1739 assert (streq (zconfig_value (c), "HAM"));
1740
1741 c = zconfig_next (c);
1742 assert (!c);
1743
1744 assert (streq (zconfig_get (config, "server/verbose", NULL), "true"));
1745
1746 zconfig_destroy (&config);
1747
1748 // Delete all test files
1749 zdir_t *dir = zdir_new (TESTDIR, NULL);
1750 assert (dir);
1751 zdir_remove (dir, true);
1752 zdir_destroy (&dir);
1753
1754 #if defined (__WINDOWS__)
1755 zsys_shutdown();
1756 #endif
1757```
1758
1759#### zdigest - provides hashing functions (SHA-1 at present)
1760
1761The zdigest class generates a hash from zchunks of data. The current
1762algorithm is SHA-1, chosen for speed. We are aiming to generate a
1763unique digest for a file, and there are no security issues in this
1764use case.
1765
1766The current code depends on OpenSSL, which might be replaced by hard
1767coded SHA-1 implementation to reduce build dependencies.
1768
1769This is the class interface:
1770
1771```h
1772 // This is a stable class, and may not change except for emergencies. It
1773 // is provided in stable builds.
1774 // Constructor - creates new digest object, which you use to build up a
1775 // digest by repeatedly calling zdigest_update() on chunks of data.
1776 CZMQ_EXPORT zdigest_t *
1777 zdigest_new (void);
1778
1779 // Destroy a digest object
1780 CZMQ_EXPORT void
1781 zdigest_destroy (zdigest_t **self_p);
1782
1783 // Add buffer into digest calculation
1784 CZMQ_EXPORT void
1785 zdigest_update (zdigest_t *self, const byte *buffer, size_t length);
1786
1787 // Return final digest hash data. If built without crypto support,
1788 // returns NULL.
1789 CZMQ_EXPORT const byte *
1790 zdigest_data (zdigest_t *self);
1791
1792 // Return final digest hash size
1793 CZMQ_EXPORT size_t
1794 zdigest_size (zdigest_t *self);
1795
1796 // Return digest as printable hex string; caller should not modify nor
1797 // free this string. After calling this, you may not use zdigest_update()
1798 // on the same digest. If built without crypto support, returns NULL.
1799 CZMQ_EXPORT char *
1800 zdigest_string (zdigest_t *self);
1801
1802 // Self test of this class.
1803 CZMQ_EXPORT void
1804 zdigest_test (bool verbose);
1805
1806```
1807Please add '@interface' section in './../src/zdigest.c'.
1808
1809This is the class self test code:
1810
1811```c
1812 byte *buffer = (byte *) zmalloc (1024);
1813 memset (buffer, 0xAA, 1024);
1814
1815 zdigest_t *digest = zdigest_new ();
1816 assert (digest);
1817 zdigest_update (digest, buffer, 1024);
1818 const byte *data = zdigest_data (digest);
1819 assert (data [0] == 0xDE);
1820 assert (data [1] == 0xB2);
1821 assert (data [2] == 0x38);
1822 assert (data [3] == 0x07);
1823 assert (streq (zdigest_string (digest),
1824 "DEB23807D4FE025E900FE9A9C7D8410C3DDE9671"));
1825 zdigest_destroy (&digest);
1826 free (buffer);
1827
1828 #if defined (__WINDOWS__)
1829 zsys_shutdown();
1830 #endif
1831```
1832
1833#### zdir - work with file-system directories
1834
1835The zdir class gives access to the file system index. It will load
1836a directory tree (a directory plus all child directories) into a
1837zdir structure and then let you navigate that structure. It exists
1838mainly to wrap non-portable OS functions to do this.
1839
1840Please add '@discuss' section in './../src/zdir.c'.
1841
1842This is the class interface:
1843
1844```h
1845 // This is a stable class, and may not change except for emergencies. It
1846 // is provided in stable builds.
1847 // Create a new directory item that loads in the full tree of the specified
1848 // path, optionally located under some parent path. If parent is "-", then
1849 // loads only the top-level directory, and does not use parent as a path.
1850 CZMQ_EXPORT zdir_t *
1851 zdir_new (const char *path, const char *parent);
1852
1853 // Destroy a directory tree and all children it contains.
1854 CZMQ_EXPORT void
1855 zdir_destroy (zdir_t **self_p);
1856
1857 // Return directory path
1858 CZMQ_EXPORT const char *
1859 zdir_path (zdir_t *self);
1860
1861 // Return last modification time for directory.
1862 CZMQ_EXPORT time_t
1863 zdir_modified (zdir_t *self);
1864
1865 // Return total hierarchy size, in bytes of data contained in all files
1866 // in the directory tree.
1867 CZMQ_EXPORT off_t
1868 zdir_cursize (zdir_t *self);
1869
1870 // Return directory count
1871 CZMQ_EXPORT size_t
1872 zdir_count (zdir_t *self);
1873
1874 // Returns a sorted list of zfile objects; Each entry in the list is a pointer
1875 // to a zfile_t item already allocated in the zdir tree. Do not destroy the
1876 // original zdir tree until you are done with this list.
1877 // Caller owns return value and must destroy it when done.
1878 CZMQ_EXPORT zlist_t *
1879 zdir_list (zdir_t *self);
1880
1881 // Remove directory, optionally including all files that it contains, at
1882 // all levels. If force is false, will only remove the directory if empty.
1883 // If force is true, will remove all files and all subdirectories.
1884 CZMQ_EXPORT void
1885 zdir_remove (zdir_t *self, bool force);
1886
1887 // Calculate differences between two versions of a directory tree.
1888 // Returns a list of zdir_patch_t patches. Either older or newer may
1889 // be null, indicating the directory is empty/absent. If alias is set,
1890 // generates virtual filename (minus path, plus alias).
1891 // Caller owns return value and must destroy it when done.
1892 CZMQ_EXPORT zlist_t *
1893 zdir_diff (zdir_t *older, zdir_t *newer, const char *alias);
1894
1895 // Return full contents of directory as a zdir_patch list.
1896 // Caller owns return value and must destroy it when done.
1897 CZMQ_EXPORT zlist_t *
1898 zdir_resync (zdir_t *self, const char *alias);
1899
1900 // Load directory cache; returns a hash table containing the SHA-1 digests
1901 // of every file in the tree. The cache is saved between runs in .cache.
1902 // Caller owns return value and must destroy it when done.
1903 CZMQ_EXPORT zhash_t *
1904 zdir_cache (zdir_t *self);
1905
1906 // Print contents of directory to open stream
1907 CZMQ_EXPORT void
1908 zdir_fprint (zdir_t *self, FILE *file, int indent);
1909
1910 // Print contents of directory to stdout
1911 CZMQ_EXPORT void
1912 zdir_print (zdir_t *self, int indent);
1913
1914 // Create a new zdir_watch actor instance:
1915 //
1916 // zactor_t *watch = zactor_new (zdir_watch, NULL);
1917 //
1918 // Destroy zdir_watch instance:
1919 //
1920 // zactor_destroy (&watch);
1921 //
1922 // Enable verbose logging of commands and activity:
1923 //
1924 // zstr_send (watch, "VERBOSE");
1925 //
1926 // Subscribe to changes to a directory path:
1927 //
1928 // zsock_send (watch, "ss", "SUBSCRIBE", "directory_path");
1929 //
1930 // Unsubscribe from changes to a directory path:
1931 //
1932 // zsock_send (watch, "ss", "UNSUBSCRIBE", "directory_path");
1933 //
1934 // Receive directory changes:
1935 // zsock_recv (watch, "sp", &path, &patches);
1936 //
1937 // // Delete the received data.
1938 // free (path);
1939 // zlist_destroy (&patches);
1940 CZMQ_EXPORT void
1941 zdir_watch (zsock_t *pipe, void *unused);
1942
1943 // Self test of this class.
1944 CZMQ_EXPORT void
1945 zdir_test (bool verbose);
1946
1947```
1948Please add '@interface' section in './../src/zdir.c'.
1949
1950This is the class self test code:
1951
1952```c
1953 // need to create a file in the test directory we're watching
1954 // in order to ensure the directory exists
1955 zfile_t *initfile = zfile_new ("./zdir-test-dir", "initial_file");
1956 assert (initfile);
1957 zfile_output (initfile);
1958 fprintf (zfile_handle (initfile), "initial file\n");
1959 zfile_close (initfile);
1960 zfile_destroy (&initfile);
1961
1962 zdir_t *older = zdir_new ("zdir-test-dir", NULL);
1963 assert (older);
1964 if (verbose) {
1965 printf ("\n");
1966 zdir_dump (older, 0);
1967 }
1968 zdir_t *newer = zdir_new (".", NULL);
1969 assert (newer);
1970 zlist_t *patches = zdir_diff (older, newer, "/");
1971 assert (patches);
1972 while (zlist_size (patches)) {
1973 zdir_patch_t *patch = (zdir_patch_t *) zlist_pop (patches);
1974 zdir_patch_destroy (&patch);
1975 }
1976 zlist_destroy (&patches);
1977 zdir_destroy (&older);
1978 zdir_destroy (&newer);
1979
1980 zdir_t *nosuch = zdir_new ("does-not-exist", NULL);
1981 assert (nosuch == NULL);
1982
1983 // zdir_watch test:
1984 zactor_t *watch = zactor_new (zdir_watch, NULL);
1985 assert (watch);
1986
1987 int synced;
1988 if (verbose) {
1989 zsock_send (watch, "s", "VERBOSE");
1990 synced = zsock_wait(watch);
1991 assert ( synced == 0);
1992 }
1993
1994 zclock_sleep (1001); // wait for initial file to become 'stable'
1995
1996 zsock_send (watch, "si", "TIMEOUT", 100);
1997 synced = zsock_wait(watch);
1998 assert (synced == 0);
1999
2000 zsock_send (watch, "ss", "SUBSCRIBE", "zdir-test-dir");
2001 synced = zsock_wait(watch);
2002 assert(synced == 0);
2003
2004 zsock_send (watch, "ss", "UNSUBSCRIBE", "zdir-test-dir");
2005 synced = zsock_wait(watch);
2006 assert(synced == 0);
2007
2008 zsock_send (watch, "ss", "SUBSCRIBE", "zdir-test-dir");
2009 synced = zsock_wait(watch);
2010 assert(synced == 0);
2011
2012 zfile_t *newfile = zfile_new ("zdir-test-dir", "test_abc");
2013 zfile_output (newfile);
2014 fprintf (zfile_handle (newfile), "test file\n");
2015 zfile_close (newfile);
2016
2017 zpoller_t *watch_poll = zpoller_new (watch, NULL);
2018
2019 // poll for a certain timeout before giving up and failing the test.
2020 void* polled = zpoller_wait(watch_poll, 1001);
2021 assert (polled == watch);
2022
2023 // wait for notification of the file being added
2024 char *path;
2025 int rc = zsock_recv (watch, "sp", &path, &patches);
2026 assert (rc == 0);
2027
2028 assert (streq (path, "zdir-test-dir"));
2029 free (path);
2030
2031 assert (zlist_size (patches) == 1);
2032
2033 zdir_patch_t *patch = (zdir_patch_t *) zlist_pop (patches);
2034 assert (streq (zdir_patch_path (patch), "zdir-test-dir"));
2035
2036 zfile_t *patch_file = zdir_patch_file (patch);
2037 assert (streq (zfile_filename (patch_file, ""), "zdir-test-dir/test_abc"));
2038
2039 zdir_patch_destroy (&patch);
2040 zlist_destroy (&patches);
2041
2042 // remove the file
2043 zfile_remove (newfile);
2044 zfile_destroy (&newfile);
2045
2046 // poll for a certain timeout before giving up and failing the test.
2047 polled = zpoller_wait(watch_poll, 1001);
2048 assert (polled == watch);
2049
2050 // wait for notification of the file being removed
2051 rc = zsock_recv (watch, "sp", &path, &patches);
2052 assert (rc == 0);
2053
2054 assert (streq (path, "zdir-test-dir"));
2055 free (path);
2056
2057 assert (zlist_size (patches) == 1);
2058
2059 patch = (zdir_patch_t *) zlist_pop (patches);
2060 assert (streq (zdir_patch_path (patch), "zdir-test-dir"));
2061
2062 patch_file = zdir_patch_file (patch);
2063 assert (streq (zfile_filename (patch_file, ""), "zdir-test-dir/test_abc"));
2064
2065 zdir_patch_destroy (&patch);
2066 zlist_destroy (&patches);
2067
2068 zpoller_destroy (&watch_poll);
2069 zactor_destroy (&watch);
2070
2071 // clean up by removing the test directory.
2072 zdir_t *testdir = zdir_new ("zdir-test-dir", NULL);
2073 zdir_remove (testdir, true);
2074 zdir_destroy (&testdir);
2075
2076 #if defined (__WINDOWS__)
2077 zsys_shutdown();
2078 #endif
2079```
2080
2081#### zdir_patch - work with directory patches
2082
2083The zdir_patch class works with one patch, which says "create this
2084file" or "delete this file" (referring to a zfile item each time).
2085
2086Please add '@discuss' section in './../src/zdir_patch.c'.
2087
2088This is the class interface:
2089
2090```h
2091 // This is a stable class, and may not change except for emergencies. It
2092 // is provided in stable builds.
2093 #define ZDIR_PATCH_CREATE 1 // Creates a new file
2094 #define ZDIR_PATCH_DELETE 2 // Delete a file
2095
2096 // Create new patch
2097 CZMQ_EXPORT zdir_patch_t *
2098 zdir_patch_new (const char *path, zfile_t *file, int op, const char *alias);
2099
2100 // Destroy a patch
2101 CZMQ_EXPORT void
2102 zdir_patch_destroy (zdir_patch_t **self_p);
2103
2104 // Create copy of a patch. If the patch is null, or memory was exhausted,
2105 // returns null.
2106 // Caller owns return value and must destroy it when done.
2107 CZMQ_EXPORT zdir_patch_t *
2108 zdir_patch_dup (zdir_patch_t *self);
2109
2110 // Return patch file directory path
2111 CZMQ_EXPORT const char *
2112 zdir_patch_path (zdir_patch_t *self);
2113
2114 // Return patch file item
2115 CZMQ_EXPORT zfile_t *
2116 zdir_patch_file (zdir_patch_t *self);
2117
2118 // Return operation
2119 CZMQ_EXPORT int
2120 zdir_patch_op (zdir_patch_t *self);
2121
2122 // Return patch virtual file path
2123 CZMQ_EXPORT const char *
2124 zdir_patch_vpath (zdir_patch_t *self);
2125
2126 // Calculate hash digest for file (create only)
2127 CZMQ_EXPORT void
2128 zdir_patch_digest_set (zdir_patch_t *self);
2129
2130 // Return hash digest for patch file
2131 CZMQ_EXPORT const char *
2132 zdir_patch_digest (zdir_patch_t *self);
2133
2134 // Self test of this class.
2135 CZMQ_EXPORT void
2136 zdir_patch_test (bool verbose);
2137
2138```
2139Please add '@interface' section in './../src/zdir_patch.c'.
2140
2141This is the class self test code:
2142
2143```c
2144 zfile_t *file = zfile_new (".", "bilbo");
2145 assert (file);
2146 zdir_patch_t *patch = zdir_patch_new (".", file, patch_create, "/");
2147 assert (patch);
2148 zfile_destroy (&file);
2149
2150 file = zdir_patch_file (patch);
2151 assert (file);
2152 assert (streq (zfile_filename (file, "."), "bilbo"));
2153 assert (streq (zdir_patch_vpath (patch), "/bilbo"));
2154 zdir_patch_destroy (&patch);
2155
2156 #if defined (__WINDOWS__)
2157 zsys_shutdown();
2158 #endif
2159```
2160
2161#### zfile - provides methods to work with files in a portable fashion.
2162
2163The zfile class provides methods to work with disk files. A file object
2164provides the modified date, current size, and type of the file. You can
2165create a file object for a filename that does not yet exist. To read or
2166write data from the file, use the input and output methods, and then
2167read and write chunks. The output method lets you both read and write
2168chunks, at any offset. Finally, this class provides portable symbolic
2169links. If a filename ends in ".ln", the first line of text in the file
2170is read, and used as the underlying file for read/write operations.
2171This lets you manipulate (e.g.) copy symbolic links without copying
2172the perhaps very large files they point to.
2173
2174This class is a new API, deprecating the old zfile class (which still
2175exists but is implemented in zsys now).
2176
2177This is the class interface:
2178
2179```h
2180 // This is a stable class, and may not change except for emergencies. It
2181 // is provided in stable builds.
2182 // If file exists, populates properties. CZMQ supports portable symbolic
2183 // links, which are files with the extension ".ln". A symbolic link is a
2184 // text file containing one line, the filename of a target file. Reading
2185 // data from the symbolic link actually reads from the target file. Path
2186 // may be NULL, in which case it is not used.
2187 CZMQ_EXPORT zfile_t *
2188 zfile_new (const char *path, const char *name);
2189
2190 // Destroy a file item
2191 CZMQ_EXPORT void
2192 zfile_destroy (zfile_t **self_p);
2193
2194 // Duplicate a file item, returns a newly constructed item. If the file
2195 // is null, or memory was exhausted, returns null.
2196 // Caller owns return value and must destroy it when done.
2197 CZMQ_EXPORT zfile_t *
2198 zfile_dup (zfile_t *self);
2199
2200 // Return file name, remove path if provided
2201 CZMQ_EXPORT const char *
2202 zfile_filename (zfile_t *self, const char *path);
2203
2204 // Refresh file properties from disk; this is not done automatically
2205 // on access methods, otherwise it is not possible to compare directory
2206 // snapshots.
2207 CZMQ_EXPORT void
2208 zfile_restat (zfile_t *self);
2209
2210 // Return when the file was last modified. If you want this to reflect the
2211 // current situation, call zfile_restat before checking this property.
2212 CZMQ_EXPORT time_t
2213 zfile_modified (zfile_t *self);
2214
2215 // Return the last-known size of the file. If you want this to reflect the
2216 // current situation, call zfile_restat before checking this property.
2217 CZMQ_EXPORT off_t
2218 zfile_cursize (zfile_t *self);
2219
2220 // Return true if the file is a directory. If you want this to reflect
2221 // any external changes, call zfile_restat before checking this property.
2222 CZMQ_EXPORT bool
2223 zfile_is_directory (zfile_t *self);
2224
2225 // Return true if the file is a regular file. If you want this to reflect
2226 // any external changes, call zfile_restat before checking this property.
2227 CZMQ_EXPORT bool
2228 zfile_is_regular (zfile_t *self);
2229
2230 // Return true if the file is readable by this process. If you want this to
2231 // reflect any external changes, call zfile_restat before checking this
2232 // property.
2233 CZMQ_EXPORT bool
2234 zfile_is_readable (zfile_t *self);
2235
2236 // Return true if the file is writeable by this process. If you want this
2237 // to reflect any external changes, call zfile_restat before checking this
2238 // property.
2239 CZMQ_EXPORT bool
2240 zfile_is_writeable (zfile_t *self);
2241
2242 // Check if file has stopped changing and can be safely processed.
2243 // Updates the file statistics from disk at every call.
2244 CZMQ_EXPORT bool
2245 zfile_is_stable (zfile_t *self);
2246
2247 // Return true if the file was changed on disk since the zfile_t object
2248 // was created, or the last zfile_restat() call made on it.
2249 CZMQ_EXPORT bool
2250 zfile_has_changed (zfile_t *self);
2251
2252 // Remove the file from disk
2253 CZMQ_EXPORT void
2254 zfile_remove (zfile_t *self);
2255
2256 // Open file for reading
2257 // Returns 0 if OK, -1 if not found or not accessible
2258 CZMQ_EXPORT int
2259 zfile_input (zfile_t *self);
2260
2261 // Open file for writing, creating directory if needed
2262 // File is created if necessary; chunks can be written to file at any
2263 // location. Returns 0 if OK, -1 if error.
2264 CZMQ_EXPORT int
2265 zfile_output (zfile_t *self);
2266
2267 // Read chunk from file at specified position. If this was the last chunk,
2268 // sets the eof property. Returns a null chunk in case of error.
2269 // Caller owns return value and must destroy it when done.
2270 CZMQ_EXPORT zchunk_t *
2271 zfile_read (zfile_t *self, size_t bytes, off_t offset);
2272
2273 // Returns true if zfile_read() just read the last chunk in the file.
2274 CZMQ_EXPORT bool
2275 zfile_eof (zfile_t *self);
2276
2277 // Write chunk to file at specified position
2278 // Return 0 if OK, else -1
2279 CZMQ_EXPORT int
2280 zfile_write (zfile_t *self, zchunk_t *chunk, off_t offset);
2281
2282 // Read next line of text from file. Returns a pointer to the text line,
2283 // or NULL if there was nothing more to read from the file.
2284 CZMQ_EXPORT const char *
2285 zfile_readln (zfile_t *self);
2286
2287 // Close file, if open
2288 CZMQ_EXPORT void
2289 zfile_close (zfile_t *self);
2290
2291 // Return file handle, if opened
2292 CZMQ_EXPORT FILE *
2293 zfile_handle (zfile_t *self);
2294
2295 // Calculate SHA1 digest for file, using zdigest class.
2296 CZMQ_EXPORT const char *
2297 zfile_digest (zfile_t *self);
2298
2299 // Self test of this class.
2300 CZMQ_EXPORT void
2301 zfile_test (bool verbose);
2302
2303 // These methods are deprecated, and now moved to zsys class.
2304 CZMQ_EXPORT bool
2305 zfile_exists (const char *filename);
2306 CZMQ_EXPORT ssize_t
2307 zfile_size (const char *filename);
2308 CZMQ_EXPORT mode_t
2309 zfile_mode (const char *filename);
2310 CZMQ_EXPORT int
2311 zfile_delete (const char *filename);
2312 CZMQ_EXPORT bool
2313 zfile_stable (const char *filename);
2314 CZMQ_EXPORT int
2315 zfile_mkdir (const char *pathname);
2316 CZMQ_EXPORT int
2317 zfile_rmdir (const char *pathname);
2318 CZMQ_EXPORT void
2319 zfile_mode_private (void);
2320 CZMQ_EXPORT void
2321 zfile_mode_default (void);
2322```
2323Please add '@interface' section in './../src/zfile.c'.
2324
2325This is the class self test code:
2326
2327```c
2328 zfile_t *file = zfile_new (NULL, "bilbo");
2329 assert (file);
2330 assert (streq (zfile_filename (file, "."), "bilbo"));
2331 assert (zfile_is_readable (file) == false);
2332 zfile_destroy (&file);
2333
2334 // Create a test file in some random subdirectory
2335 file = zfile_new ("./this/is/a/test", "bilbo");
2336 assert (file);
2337 int rc = zfile_output (file);
2338 assert (rc == 0);
2339 zchunk_t *chunk = zchunk_new (NULL, 100);
2340 assert (chunk);
2341 zchunk_fill (chunk, 0, 100);
2342
2343 // Write 100 bytes at position 1,000,000 in the file
2344 rc = zfile_write (file, chunk, 1000000);
2345 assert (rc == 0);
2346 zchunk_destroy (&chunk);
2347 zfile_close (file);
2348 assert (zfile_is_readable (file));
2349 assert (zfile_cursize (file) == 1000100);
2350 assert (!zfile_is_stable (file));
2351 assert (zfile_digest (file));
2352
2353 // Now truncate file from outside
2354 int handle = open ("./this/is/a/test/bilbo", O_WRONLY | O_TRUNC | O_BINARY, 0);
2355 assert (handle >= 0);
2356 rc = write (handle, "Hello, World\n", 13);
2357 assert (rc == 13);
2358 close (handle);
2359 assert (zfile_has_changed (file));
2360 zclock_sleep (1001);
2361 assert (zfile_has_changed (file));
2362
2363 assert (!zfile_is_stable (file));
2364 zfile_restat (file);
2365 assert (zfile_is_stable (file));
2366 assert (streq (zfile_digest (file), "4AB299C8AD6ED14F31923DD94F8B5F5CB89DFB54"));
2367
2368 // Check we can read from file
2369 rc = zfile_input (file);
2370 assert (rc == 0);
2371 chunk = zfile_read (file, 1000100, 0);
2372 assert (chunk);
2373 assert (zchunk_size (chunk) == 13);
2374 zchunk_destroy (&chunk);
2375 zfile_close (file);
2376
2377 // Check we can read lines from file
2378 rc = zfile_input (file);
2379 assert (rc == 0);
2380 const char *line = zfile_readln (file);
2381 assert (streq (line, "Hello, World"));
2382 line = zfile_readln (file);
2383 assert (line == NULL);
2384 zfile_close (file);
2385
2386 // Try some fun with symbolic links
2387 zfile_t *link = zfile_new ("./this/is/a/test", "bilbo.ln");
2388 assert (link);
2389 rc = zfile_output (link);
2390 assert (rc == 0);
2391 fprintf (zfile_handle (link), "./this/is/a/test/bilbo\n");
2392 zfile_destroy (&link);
2393
2394 link = zfile_new ("./this/is/a/test", "bilbo.ln");
2395 assert (link);
2396 rc = zfile_input (link);
2397 assert (rc == 0);
2398 chunk = zfile_read (link, 1000100, 0);
2399 assert (chunk);
2400 assert (zchunk_size (chunk) == 13);
2401 zchunk_destroy (&chunk);
2402 zfile_destroy (&link);
2403
2404 // Remove file and directory
2405 zdir_t *dir = zdir_new ("./this", NULL);
2406 assert (dir);
2407 assert (zdir_cursize (dir) == 26);
2408 zdir_remove (dir, true);
2409 assert (zdir_cursize (dir) == 0);
2410 zdir_destroy (&dir);
2411
2412 // Check we can no longer read from file
2413 assert (zfile_is_readable (file));
2414 zfile_restat (file);
2415 assert (!zfile_is_readable (file));
2416 rc = zfile_input (file);
2417 assert (rc == -1);
2418 zfile_destroy (&file);
2419
2420 file = zfile_new ("./", "eof_checkfile");
2421 assert (file);
2422 // 1. Write something first
2423 rc = zfile_output (file);
2424 assert (rc == 0);
2425 chunk = zchunk_new ("123456789", 9);
2426 assert (chunk);
2427
2428 rc = zfile_write (file, chunk, 0);
2429 assert (rc == 0);
2430 zchunk_destroy (&chunk);
2431 zfile_close (file);
2432 assert (zfile_cursize (file) == 9);
2433
2434 // 2. Read the written something
2435 rc = zfile_input (file);
2436 assert (rc != -1);
2437 // try to read more bytes than there is in the file
2438 chunk = zfile_read (file, 1000, 0);
2439 assert (zfile_eof(file));
2440 assert (zchunk_streq (chunk, "123456789"));
2441 zchunk_destroy (&chunk);
2442
2443 // reading is ok
2444 chunk = zfile_read (file, 5, 0);
2445 assert (!zfile_eof(file));
2446 assert (zchunk_streq (chunk, "12345"));
2447 zchunk_destroy (&chunk);
2448
2449 // read from non zero offset until the end
2450 chunk = zfile_read (file, 5, 5);
2451 assert (zfile_eof(file));
2452 assert (zchunk_streq (chunk, "6789"));
2453 zchunk_destroy (&chunk);
2454 zfile_remove (file);
2455 zfile_close (file);
2456 zfile_destroy (&file);
2457
2458 #if defined (__WINDOWS__)
2459 zsys_shutdown();
2460 #endif
2461
2462```
2463
2464#### zframe - working with single message frames
2465
2466The zframe class provides methods to send and receive single message
2467frames across ØMQ sockets. A 'frame' corresponds to one zmq_msg_t. When
2468you read a frame from a socket, the zframe_more() method indicates if the
2469frame is part of an unfinished multipart message. The zframe_send method
2470normally destroys the frame, but with the ZFRAME_REUSE flag, you can send
2471the same frame many times. Frames are binary, and this class has no
2472special support for text data.
2473
2474Please add '@discuss' section in './../src/zframe.c'.
2475
2476This is the class interface:
2477
2478```h
2479 // This is a stable class, and may not change except for emergencies. It
2480 // is provided in stable builds.
2481 // This class has draft methods, which may change over time. They are not
2482 // in stable releases, by default. Use --enable-drafts to enable.
2483 #define ZFRAME_MORE 1 //
2484 #define ZFRAME_REUSE 2 //
2485 #define ZFRAME_DONTWAIT 4 //
2486
2487 // Create a new frame. If size is not null, allocates the frame data
2488 // to the specified size. If additionally, data is not null, copies
2489 // size octets from the specified data into the frame body.
2490 CZMQ_EXPORT zframe_t *
2491 zframe_new (const void *data, size_t size);
2492
2493 // Create an empty (zero-sized) frame
2494 CZMQ_EXPORT zframe_t *
2495 zframe_new_empty (void);
2496
2497 // Create a frame with a specified string content.
2498 CZMQ_EXPORT zframe_t *
2499 zframe_from (const char *string);
2500
2501 // Receive frame from socket, returns zframe_t object or NULL if the recv
2502 // was interrupted. Does a blocking recv, if you want to not block then use
2503 // zpoller or zloop.
2504 CZMQ_EXPORT zframe_t *
2505 zframe_recv (void *source);
2506
2507 // Destroy a frame
2508 CZMQ_EXPORT void
2509 zframe_destroy (zframe_t **self_p);
2510
2511 // Send a frame to a socket, destroy frame after sending.
2512 // Return -1 on error, 0 on success.
2513 CZMQ_EXPORT int
2514 zframe_send (zframe_t **self_p, void *dest, int flags);
2515
2516 // Return number of bytes in frame data
2517 CZMQ_EXPORT size_t
2518 zframe_size (zframe_t *self);
2519
2520 // Return address of frame data
2521 CZMQ_EXPORT byte *
2522 zframe_data (zframe_t *self);
2523
2524 // Return meta data property for frame
2525 // The caller shall not modify or free the returned value, which shall be
2526 // owned by the message.
2527 CZMQ_EXPORT const char *
2528 zframe_meta (zframe_t *self, const char *property);
2529
2530 // Create a new frame that duplicates an existing frame. If frame is null,
2531 // or memory was exhausted, returns null.
2532 // Caller owns return value and must destroy it when done.
2533 CZMQ_EXPORT zframe_t *
2534 zframe_dup (zframe_t *self);
2535
2536 // Return frame data encoded as printable hex string, useful for ØMQ UUIDs.
2537 // Caller must free string when finished with it.
2538 // Caller owns return value and must destroy it when done.
2539 CZMQ_EXPORT char *
2540 zframe_strhex (zframe_t *self);
2541
2542 // Return frame data copied into freshly allocated string
2543 // Caller must free string when finished with it.
2544 // Caller owns return value and must destroy it when done.
2545 CZMQ_EXPORT char *
2546 zframe_strdup (zframe_t *self);
2547
2548 // Return TRUE if frame body is equal to string, excluding terminator
2549 CZMQ_EXPORT bool
2550 zframe_streq (zframe_t *self, const char *string);
2551
2552 // Return frame MORE indicator (1 or 0), set when reading frame from socket
2553 // or by the zframe_set_more() method
2554 CZMQ_EXPORT int
2555 zframe_more (zframe_t *self);
2556
2557 // Set frame MORE indicator (1 or 0). Note this is NOT used when sending
2558 // frame to socket, you have to specify flag explicitly.
2559 CZMQ_EXPORT void
2560 zframe_set_more (zframe_t *self, int more);
2561
2562 // Return TRUE if two frames have identical size and data
2563 // If either frame is NULL, equality is always false.
2564 CZMQ_EXPORT bool
2565 zframe_eq (zframe_t *self, zframe_t *other);
2566
2567 // Set new contents for frame
2568 CZMQ_EXPORT void
2569 zframe_reset (zframe_t *self, const void *data, size_t size);
2570
2571 // Send message to zsys log sink (may be stdout, or system facility as
2572 // configured by zsys_set_logstream). Prefix shows before frame, if not null.
2573 CZMQ_EXPORT void
2574 zframe_print (zframe_t *self, const char *prefix);
2575
2576 // Probe the supplied object, and report if it looks like a zframe_t.
2577 CZMQ_EXPORT bool
2578 zframe_is (void *self);
2579
2580 // Self test of this class.
2581 CZMQ_EXPORT void
2582 zframe_test (bool verbose);
2583
2584 #ifdef CZMQ_BUILD_DRAFT_API
2585 // *** Draft method, for development use, may change without warning ***
2586 // Return frame routing ID, if the frame came from a ZMQ_SERVER socket.
2587 // Else returns zero.
2588 CZMQ_EXPORT uint32_t
2589 zframe_routing_id (zframe_t *self);
2590
2591 // *** Draft method, for development use, may change without warning ***
2592 // Set routing ID on frame. This is used if/when the frame is sent to a
2593 // ZMQ_SERVER socket.
2594 CZMQ_EXPORT void
2595 zframe_set_routing_id (zframe_t *self, uint32_t routing_id);
2596
2597 // *** Draft method, for development use, may change without warning ***
2598 // Return frame group of radio-dish pattern.
2599 CZMQ_EXPORT const char *
2600 zframe_group (zframe_t *self);
2601
2602 // *** Draft method, for development use, may change without warning ***
2603 // Set group on frame. This is used if/when the frame is sent to a
2604 // ZMQ_RADIO socket.
2605 // Return -1 on error, 0 on success.
2606 CZMQ_EXPORT int
2607 zframe_set_group (zframe_t *self, const char *group);
2608
2609 #endif // CZMQ_BUILD_DRAFT_API
2610```
2611Please add '@interface' section in './../src/zframe.c'.
2612
2613This is the class self test code:
2614
2615```c
2616 // Create two PAIR sockets and connect over inproc
2617 zsock_t *output = zsock_new_pair ("@tcp://127.0.0.1:9001");
2618 assert (output);
2619 zsock_t *input = zsock_new_pair (">tcp://127.0.0.1:9001");
2620 assert (input);
2621
2622 // Send five different frames, test ZFRAME_MORE
2623 int frame_nbr;
2624 for (frame_nbr = 0; frame_nbr < 5; frame_nbr++) {
2625 frame = zframe_new ("Hello", 5);
2626 assert (frame);
2627 rc = zframe_send (&frame, output, ZFRAME_MORE);
2628 assert (rc == 0);
2629 }
2630 // Send same frame five times, test ZFRAME_REUSE
2631 frame = zframe_new ("Hello", 5);
2632 assert (frame);
2633 for (frame_nbr = 0; frame_nbr < 5; frame_nbr++) {
2634 rc = zframe_send (&frame, output, ZFRAME_MORE + ZFRAME_REUSE);
2635 assert (rc == 0);
2636 }
2637 assert (frame);
2638 zframe_t *copy = zframe_dup (frame);
2639 assert (zframe_eq (frame, copy));
2640 zframe_destroy (&frame);
2641 assert (!zframe_eq (frame, copy));
2642 assert (zframe_size (copy) == 5);
2643 zframe_destroy (©);
2644 assert (!zframe_eq (frame, copy));
2645
2646 // Test zframe_new_empty
2647 frame = zframe_new_empty ();
2648 assert (frame);
2649 assert (zframe_size (frame) == 0);
2650 zframe_destroy (&frame);
2651
2652 // Send END frame
2653 frame = zframe_new ("NOT", 3);
2654 assert (frame);
2655 zframe_reset (frame, "END", 3);
2656 char *string = zframe_strhex (frame);
2657 assert (streq (string, "454E44"));
2658 free (string);
2659 string = zframe_strdup (frame);
2660 assert (streq (string, "END"));
2661 free (string);
2662 rc = zframe_send (&frame, output, 0);
2663 assert (rc == 0);
2664
2665 // Read and count until we receive END
2666 frame_nbr = 0;
2667 for (frame_nbr = 0;; frame_nbr++) {
2668 zframe_t *frame = zframe_recv (input);
2669 if (zframe_streq (frame, "END")) {
2670 zframe_destroy (&frame);
2671 break;
2672 }
2673 assert (zframe_more (frame));
2674 zframe_set_more (frame, 0);
2675 assert (zframe_more (frame) == 0);
2676 zframe_destroy (&frame);
2677 }
2678 assert (frame_nbr == 10);
2679
2680 #if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (4, 1, 0))
2681 // Test zframe_meta
2682 frame = zframe_new ("Hello", 5);
2683 assert (frame);
2684 rc = zframe_send (&frame, output, 0);
2685 assert (rc == 0);
2686 frame = zframe_recv (input);
2687 const char *meta = zframe_meta (frame, "Socket-Type");
2688 assert (meta != NULL);
2689 assert (streq (meta, "PAIR"));
2690 assert (zframe_meta (frame, "nonexistent") == NULL);
2691 zframe_destroy (&frame);
2692 #endif
2693
2694 zsock_destroy (&input);
2695 zsock_destroy (&output);
2696
2697 #if defined (ZMQ_SERVER)
2698 // Create server and client sockets and connect over inproc
2699 zsock_t *server = zsock_new_server ("inproc://zframe-test-routing");
2700 assert (server);
2701 zsock_t *client = zsock_new_client ("inproc://zframe-test-routing");
2702 assert (client);
2703
2704 // Send request from client to server
2705 zframe_t *request = zframe_new ("Hello", 5);
2706 assert (request);
2707 rc = zframe_send (&request, client, 0);
2708 assert (rc == 0);
2709 assert (!request);
2710
2711 // Read request and send reply
2712 request = zframe_recv (server);
2713 assert (request);
2714 assert (zframe_streq (request, "Hello"));
2715 assert (zframe_routing_id (request));
2716
2717 zframe_t *reply = zframe_new ("World", 5);
2718 assert (reply);
2719 zframe_set_routing_id (reply, zframe_routing_id (request));
2720 rc = zframe_send (&reply, server, 0);
2721 assert (rc == 0);
2722 zframe_destroy (&request);
2723
2724 // Read reply
2725 reply = zframe_recv (client);
2726 assert (zframe_streq (reply, "World"));
2727 assert (zframe_routing_id (reply) == 0);
2728 zframe_destroy (&reply);
2729
2730 // Client and server disallow multipart
2731 frame = zframe_new ("Hello", 5);
2732 rc = zframe_send (&frame, client, ZFRAME_MORE);
2733 assert (rc == -1);
2734 rc = zframe_send (&frame, server, ZFRAME_MORE);
2735 assert (rc == -1);
2736 zframe_destroy (&frame);
2737
2738 zsock_destroy (&client);
2739 zsock_destroy (&server);
2740 #endif
2741
2742 #ifdef ZMQ_RADIO
2743 // Create radio and dish sockets and connect over inproc
2744 zsock_t *radio = zsock_new_radio ("inproc://zframe-test-radio");
2745 assert (radio);
2746 zsock_t *dish = zsock_new_dish ("inproc://zframe-test-radio");
2747 assert (dish);
2748
2749 // Join the group
2750 rc = zsock_join (dish, "World");
2751 assert (rc == 0);
2752
2753 // Publish message from radio
2754 zframe_t *message = zframe_new ("Hello", 5);
2755 assert (message);
2756 rc = zframe_set_group (message, "World");
2757 assert (rc == 0);
2758 rc = zframe_send (&message, radio, 0);
2759 assert (rc == 0);
2760 assert (!message);
2761
2762 // Receive the message from dish
2763 message = zframe_recv (dish);
2764 assert (message);
2765 assert (zframe_streq (message, "Hello"));
2766 assert (strcmp("World", zframe_group (message)) == 0);
2767 zframe_destroy (&message);
2768
2769 zsock_destroy (&dish);
2770 zsock_destroy (&radio);
2771 #endif
2772
2773 #if defined (__WINDOWS__)
2774 zsys_shutdown();
2775 #endif
2776
2777```
2778
2779#### zgossip - decentralized configuration management
2780
2781Implements a gossip protocol for decentralized configuration management.
2782Your applications nodes form a loosely connected network (which can have
2783cycles), and publish name/value tuples. Each node re-distributes the new
2784tuples it receives, so that the entire network eventually achieves a
2785consistent state. The current design does not expire tuples.
2786
2787Provides these commands (sent as multipart strings to the actor):
2788
2789* BIND endpoint -- binds the gossip service to specified endpoint
2790* PORT -- returns the last TCP port, if any, used for binding
2791* LOAD configfile -- load configuration from specified file
2792* SET configpath value -- set configuration path = value
2793* SAVE configfile -- save configuration to specified file
2794* CONNECT endpoint -- connect the gossip service to the specified peer
2795* PUBLISH key value -- publish a key/value pair to the gossip cluster
2796* STATUS -- return number of key/value pairs held by gossip service
2797
2798Returns these messages:
2799
2800* PORT number -- reply to PORT command
2801* STATUS number -- reply to STATUS command
2802* DELIVER key value -- new tuple delivered from network
2803
2804The gossip protocol distributes information around a loosely-connected
2805network of gossip services. The information consists of name/value pairs
2806published by applications at any point in the network. The goal of the
2807gossip protocol is to create eventual consistency between all the using
2808applications.
2809
2810The name/value pairs (tuples) can be used for configuration data, for
2811status updates, for presence, or for discovery. When used for discovery,
2812the gossip protocol works as an alternative to e.g. UDP beaconing.
2813
2814The gossip network consists of a set of loosely-coupled nodes that
2815exchange tuples. Nodes can be connected across arbitrary transports,
2816so the gossip network can have nodes that communicate over inproc,
2817over IPC, and/or over TCP, at the same time.
2818
2819Each node runs the same stack, which is a server-client hybrid using
2820a modified Harmony pattern (from Chapter 8 of the Guide):
2821http://zguide.zeromq.org/page:all#True-Peer-Connectivity-Harmony-Pattern
2822
2823Each node provides a ROUTER socket that accepts client connections on an
2824key defined by the application via a BIND command. The state machine
2825for these connections is in zgossip.xml, and the generated code is in
2826zgossip_engine.inc.
2827
2828Each node additionally creates outbound connections via DEALER sockets
2829to a set of servers ("remotes"), and under control of the calling app,
2830which sends CONNECT commands for each configured remote.
2831
2832The messages between client and server are defined in zgossip_msg.xml.
2833We built this stack using the zeromq/zproto toolkit.
2834
2835To join the gossip network, a node connects to one or more peers. Each
2836peer acts as a forwarder. This loosely-coupled network can scale to
2837thousands of nodes. However the gossip protocol is NOT designed to be
2838efficient, and should not be used for application data, as the same
2839tuples may be sent many times across the network.
2840
2841The basic logic of the gossip service is to accept PUBLISH messages
2842from its owning application, and to forward these to every remote, and
2843every client it talks to. When a node gets a duplicate tuple, it throws
2844it away. When a node gets a new tuple, it stores it, and forwards it as
2845just described.
2846
2847At present there is no way to expire tuples from the network.
2848
2849The assumptions in this design are:
2850
2851* The data set is slow-changing. Thus, the cost of the gossip protocol
2852 is irrelevant with respect to other traffic.
2853
2854This is the class interface:
2855
2856```h
2857 // To work with zgossip, use the CZMQ zactor API:
2858 //
2859 // Create new zgossip instance, passing logging prefix:
2860 //
2861 // zactor_t *zgossip = zactor_new (zgossip, "myname");
2862 //
2863 // Destroy zgossip instance
2864 //
2865 // zactor_destroy (&zgossip);
2866 //
2867 // Enable verbose logging of commands and activity:
2868 //
2869 // zstr_send (zgossip, "VERBOSE");
2870 //
2871 // Bind zgossip to specified endpoint. TCP endpoints may specify
2872 // the port number as "*" to aquire an ephemeral port:
2873 //
2874 // zstr_sendx (zgossip, "BIND", endpoint, NULL);
2875 //
2876 // Return assigned port number, specifically when BIND was done using an
2877 // an ephemeral port:
2878 //
2879 // zstr_sendx (zgossip, "PORT", NULL);
2880 // char *command, *port_str;
2881 // zstr_recvx (zgossip, &command, &port_str, NULL);
2882 // assert (streq (command, "PORT"));
2883 //
2884 // Specify configuration file to load, overwriting any previous loaded
2885 // configuration file or options:
2886 //
2887 // zstr_sendx (zgossip, "LOAD", filename, NULL);
2888 //
2889 // Set configuration path value:
2890 //
2891 // zstr_sendx (zgossip, "SET", path, value, NULL);
2892 //
2893 // Save configuration data to config file on disk:
2894 //
2895 // zstr_sendx (zgossip, "SAVE", filename, NULL);
2896 //
2897 // Send zmsg_t instance to zgossip:
2898 //
2899 // zactor_send (zgossip, &msg);
2900 //
2901 // Receive zmsg_t instance from zgossip:
2902 //
2903 // zmsg_t *msg = zactor_recv (zgossip);
2904 //
2905 // This is the zgossip constructor as a zactor_fn:
2906 //
2907 CZMQ_EXPORT void
2908 zgossip (zsock_t *pipe, void *args);
2909
2910 // Self test of this class
2911 CZMQ_EXPORT void
2912 zgossip_test (bool verbose);
2913```
2914Please add '@interface' section in './../src/zgossip.c'.
2915
2916This is the class self test code:
2917
2918```c
2919 // Test basic client-to-server operation of the protocol
2920 zactor_t *server = zactor_new (zgossip, "server");
2921 assert (server);
2922 if (verbose)
2923 zstr_send (server, "VERBOSE");
2924 zstr_sendx (server, "BIND", "inproc://zgossip", NULL);
2925
2926 zsock_t *client = zsock_new (ZMQ_DEALER);
2927 assert (client);
2928 zsock_set_rcvtimeo (client, 2000);
2929 int rc = zsock_connect (client, "inproc://zgossip");
2930 assert (rc == 0);
2931
2932 // Send HELLO, which gets no message
2933 zgossip_msg_t *message = zgossip_msg_new ();
2934 zgossip_msg_set_id (message, ZGOSSIP_MSG_HELLO);
2935 zgossip_msg_send (message, client);
2936
2937 // Send PING, expect PONG back
2938 zgossip_msg_set_id (message, ZGOSSIP_MSG_PING);
2939 zgossip_msg_send (message, client);
2940 zgossip_msg_recv (message, client);
2941 assert (zgossip_msg_id (message) == ZGOSSIP_MSG_PONG);
2942 zgossip_msg_destroy (&message);
2943
2944 zactor_destroy (&server);
2945 zsock_destroy (&client);
2946
2947 // Test peer-to-peer operations
2948 zactor_t *base = zactor_new (zgossip, "base");
2949 assert (base);
2950 if (verbose)
2951 zstr_send (base, "VERBOSE");
2952 // Set a 100msec timeout on clients so we can test expiry
2953 zstr_sendx (base, "SET", "server/timeout", "100", NULL);
2954 zstr_sendx (base, "BIND", "inproc://base", NULL);
2955
2956 zactor_t *alpha = zactor_new (zgossip, "alpha");
2957 assert (alpha);
2958 zstr_sendx (alpha, "CONNECT", "inproc://base", NULL);
2959 zstr_sendx (alpha, "PUBLISH", "inproc://alpha-1", "service1", NULL);
2960 zstr_sendx (alpha, "PUBLISH", "inproc://alpha-2", "service2", NULL);
2961
2962 zactor_t *beta = zactor_new (zgossip, "beta");
2963 assert (beta);
2964 zstr_sendx (beta, "CONNECT", "inproc://base", NULL);
2965 zstr_sendx (beta, "PUBLISH", "inproc://beta-1", "service1", NULL);
2966 zstr_sendx (beta, "PUBLISH", "inproc://beta-2", "service2", NULL);
2967
2968 // got nothing
2969 zclock_sleep (200);
2970
2971 zstr_send (alpha, "STATUS");
2972 char *command, *status, *key, *value;
2973
2974 zstr_recvx (alpha, &command, &key, &value, NULL);
2975 assert (streq (command, "DELIVER"));
2976 assert (streq (key, "inproc://alpha-1"));
2977 assert (streq (value, "service1"));
2978 zstr_free (&command);
2979 zstr_free (&key);
2980 zstr_free (&value);
2981
2982 zstr_recvx (alpha, &command, &key, &value, NULL);
2983 assert (streq (command, "DELIVER"));
2984 assert (streq (key, "inproc://alpha-2"));
2985 assert (streq (value, "service2"));
2986 zstr_free (&command);
2987 zstr_free (&key);
2988 zstr_free (&value);
2989
2990 zstr_recvx (alpha, &command, &key, &value, NULL);
2991 assert (streq (command, "DELIVER"));
2992 assert (streq (key, "inproc://beta-1"));
2993 assert (streq (value, "service1"));
2994 zstr_free (&command);
2995 zstr_free (&key);
2996 zstr_free (&value);
2997
2998 zstr_recvx (alpha, &command, &key, &value, NULL);
2999 assert (streq (command, "DELIVER"));
3000 assert (streq (key, "inproc://beta-2"));
3001 assert (streq (value, "service2"));
3002 zstr_free (&command);
3003 zstr_free (&key);
3004 zstr_free (&value);
3005
3006 zstr_recvx (alpha, &command, &status, NULL);
3007 assert (streq (command, "STATUS"));
3008 assert (atoi (status) == 4);
3009 zstr_free (&command);
3010 zstr_free (&status);
3011
3012 zactor_destroy (&base);
3013 zactor_destroy (&alpha);
3014 zactor_destroy (&beta);
3015
3016 #if defined (__WINDOWS__)
3017 zsys_shutdown();
3018 #endif
3019
3020```
3021
3022#### zhash - simple generic hash container
3023
3024zhash is an expandable hash table container. This is a simple container.
3025For heavy-duty applications we recommend using zhashx.
3026
3027Note that it's relatively slow (~50K insertions/deletes per second), so
3028don't do inserts/updates on the critical path for message I/O. It can
3029do ~2.5M lookups per second for 16-char keys. Timed on a 1.6GHz CPU.
3030
3031This is the class interface:
3032
3033```h
3034 // This is a stable class, and may not change except for emergencies. It
3035 // is provided in stable builds.
3036 // Callback function for zhash_freefn method
3037 typedef void (zhash_free_fn) (
3038 void *data);
3039
3040 // Create a new, empty hash container
3041 CZMQ_EXPORT zhash_t *
3042 zhash_new (void);
3043
3044 // Unpack binary frame into a new hash table. Packed data must follow format
3045 // defined by zhash_pack. Hash table is set to autofree. An empty frame
3046 // unpacks to an empty hash table.
3047 CZMQ_EXPORT zhash_t *
3048 zhash_unpack (zframe_t *frame);
3049
3050 // Destroy a hash container and all items in it
3051 CZMQ_EXPORT void
3052 zhash_destroy (zhash_t **self_p);
3053
3054 // Insert item into hash table with specified key and item.
3055 // If key is already present returns -1 and leaves existing item unchanged
3056 // Returns 0 on success.
3057 CZMQ_EXPORT int
3058 zhash_insert (zhash_t *self, const char *key, void *item);
3059
3060 // Update item into hash table with specified key and item.
3061 // If key is already present, destroys old item and inserts new one.
3062 // Use free_fn method to ensure deallocator is properly called on item.
3063 CZMQ_EXPORT void
3064 zhash_update (zhash_t *self, const char *key, void *item);
3065
3066 // Remove an item specified by key from the hash table. If there was no such
3067 // item, this function does nothing.
3068 CZMQ_EXPORT void
3069 zhash_delete (zhash_t *self, const char *key);
3070
3071 // Return the item at the specified key, or null
3072 CZMQ_EXPORT void *
3073 zhash_lookup (zhash_t *self, const char *key);
3074
3075 // Reindexes an item from an old key to a new key. If there was no such
3076 // item, does nothing. Returns 0 if successful, else -1.
3077 CZMQ_EXPORT int
3078 zhash_rename (zhash_t *self, const char *old_key, const char *new_key);
3079
3080 // Set a free function for the specified hash table item. When the item is
3081 // destroyed, the free function, if any, is called on that item.
3082 // Use this when hash items are dynamically allocated, to ensure that
3083 // you don't have memory leaks. You can pass 'free' or NULL as a free_fn.
3084 // Returns the item, or NULL if there is no such item.
3085 CZMQ_EXPORT void *
3086 zhash_freefn (zhash_t *self, const char *key, zhash_free_fn free_fn);
3087
3088 // Return the number of keys/items in the hash table
3089 CZMQ_EXPORT size_t
3090 zhash_size (zhash_t *self);
3091
3092 // Make copy of hash table; if supplied table is null, returns null.
3093 // Does not copy items themselves. Rebuilds new table so may be slow on
3094 // very large tables. NOTE: only works with item values that are strings
3095 // since there's no other way to know how to duplicate the item value.
3096 // Caller owns return value and must destroy it when done.
3097 CZMQ_EXPORT zhash_t *
3098 zhash_dup (zhash_t *self);
3099
3100 // Return keys for items in table
3101 // Caller owns return value and must destroy it when done.
3102 CZMQ_EXPORT zlist_t *
3103 zhash_keys (zhash_t *self);
3104
3105 // Simple iterator; returns first item in hash table, in no given order,
3106 // or NULL if the table is empty. This method is simpler to use than the
3107 // foreach() method, which is deprecated. To access the key for this item
3108 // use zhash_cursor(). NOTE: do NOT modify the table while iterating.
3109 CZMQ_EXPORT void *
3110 zhash_first (zhash_t *self);
3111
3112 // Simple iterator; returns next item in hash table, in no given order,
3113 // or NULL if the last item was already returned. Use this together with
3114 // zhash_first() to process all items in a hash table. If you need the
3115 // items in sorted order, use zhash_keys() and then zlist_sort(). To
3116 // access the key for this item use zhash_cursor(). NOTE: do NOT modify
3117 // the table while iterating.
3118 CZMQ_EXPORT void *
3119 zhash_next (zhash_t *self);
3120
3121 // After a successful first/next method, returns the key for the item that
3122 // was returned. This is a constant string that you may not modify or
3123 // deallocate, and which lasts as long as the item in the hash. After an
3124 // unsuccessful first/next, returns NULL.
3125 CZMQ_EXPORT const char *
3126 zhash_cursor (zhash_t *self);
3127
3128 // Add a comment to hash table before saving to disk. You can add as many
3129 // comment lines as you like. These comment lines are discarded when loading
3130 // the file. If you use a null format, all comments are deleted.
3131 CZMQ_EXPORT void
3132 zhash_comment (zhash_t *self, const char *format, ...) CHECK_PRINTF (2);
3133
3134 // Serialize hash table to a binary frame that can be sent in a message.
3135 // The packed format is compatible with the 'dictionary' type defined in
3136 // http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto:
3137 //
3138 // ; A list of name/value pairs
3139 // dictionary = dict-count *( dict-name dict-value )
3140 // dict-count = number-4
3141 // dict-value = longstr
3142 // dict-name = string
3143 //
3144 // ; Strings are always length + text contents
3145 // longstr = number-4 *VCHAR
3146 // string = number-1 *VCHAR
3147 //
3148 // ; Numbers are unsigned integers in network byte order
3149 // number-1 = 1OCTET
3150 // number-4 = 4OCTET
3151 //
3152 // Comments are not included in the packed data. Item values MUST be
3153 // strings.
3154 // Caller owns return value and must destroy it when done.
3155 CZMQ_EXPORT zframe_t *
3156 zhash_pack (zhash_t *self);
3157
3158 // Save hash table to a text file in name=value format. Hash values must be
3159 // printable strings; keys may not contain '=' character. Returns 0 if OK,
3160 // else -1 if a file error occurred.
3161 CZMQ_EXPORT int
3162 zhash_save (zhash_t *self, const char *filename);
3163
3164 // Load hash table from a text file in name=value format; hash table must
3165 // already exist. Hash values must printable strings; keys may not contain
3166 // '=' character. Returns 0 if OK, else -1 if a file was not readable.
3167 CZMQ_EXPORT int
3168 zhash_load (zhash_t *self, const char *filename);
3169
3170 // When a hash table was loaded from a file by zhash_load, this method will
3171 // reload the file if it has been modified since, and is "stable", i.e. not
3172 // still changing. Returns 0 if OK, -1 if there was an error reloading the
3173 // file.
3174 CZMQ_EXPORT int
3175 zhash_refresh (zhash_t *self);
3176
3177 // Set hash for automatic value destruction. Note that this assumes that
3178 // values are NULL-terminated strings. Do not use with different types.
3179 CZMQ_EXPORT void
3180 zhash_autofree (zhash_t *self);
3181
3182 // Self test of this class.
3183 CZMQ_EXPORT void
3184 zhash_test (bool verbose);
3185
3186```
3187Please add '@interface' section in './../src/zhash.c'.
3188
3189This is the class self test code:
3190
3191```c
3192 zhash_t *hash = zhash_new ();
3193 assert (hash);
3194 assert (zhash_size (hash) == 0);
3195 assert (zhash_first (hash) == NULL);
3196 assert (zhash_cursor (hash) == NULL);
3197
3198 // Insert some items
3199 int rc;
3200 rc = zhash_insert (hash, "DEADBEEF", "dead beef");
3201 char *item = (char *) zhash_first (hash);
3202 assert (streq (zhash_cursor (hash), "DEADBEEF"));
3203 assert (streq (item, "dead beef"));
3204 assert (rc == 0);
3205 rc = zhash_insert (hash, "ABADCAFE", "a bad cafe");
3206 assert (rc == 0);
3207 rc = zhash_insert (hash, "C0DEDBAD", "coded bad");
3208 assert (rc == 0);
3209 rc = zhash_insert (hash, "DEADF00D", "dead food");
3210 assert (rc == 0);
3211 assert (zhash_size (hash) == 4);
3212
3213 // Look for existing items
3214 item = (char *) zhash_lookup (hash, "DEADBEEF");
3215 assert (streq (item, "dead beef"));
3216 item = (char *) zhash_lookup (hash, "ABADCAFE");
3217 assert (streq (item, "a bad cafe"));
3218 item = (char *) zhash_lookup (hash, "C0DEDBAD");
3219 assert (streq (item, "coded bad"));
3220 item = (char *) zhash_lookup (hash, "DEADF00D");
3221 assert (streq (item, "dead food"));
3222
3223 // Look for non-existent items
3224 item = (char *) zhash_lookup (hash, "foo");
3225 assert (item == NULL);
3226
3227 // Try to insert duplicate items
3228 rc = zhash_insert (hash, "DEADBEEF", "foo");
3229 assert (rc == -1);
3230 item = (char *) zhash_lookup (hash, "DEADBEEF");
3231 assert (streq (item, "dead beef"));
3232
3233 // Some rename tests
3234
3235 // Valid rename, key is now LIVEBEEF
3236 rc = zhash_rename (hash, "DEADBEEF", "LIVEBEEF");
3237 assert (rc == 0);
3238 item = (char *) zhash_lookup (hash, "LIVEBEEF");
3239 assert (streq (item, "dead beef"));
3240
3241 // Trying to rename an unknown item to a non-existent key
3242 rc = zhash_rename (hash, "WHATBEEF", "NONESUCH");
3243 assert (rc == -1);
3244
3245 // Trying to rename an unknown item to an existing key
3246 rc = zhash_rename (hash, "WHATBEEF", "LIVEBEEF");
3247 assert (rc == -1);
3248 item = (char *) zhash_lookup (hash, "LIVEBEEF");
3249 assert (streq (item, "dead beef"));
3250
3251 // Trying to rename an existing item to another existing item
3252 rc = zhash_rename (hash, "LIVEBEEF", "ABADCAFE");
3253 assert (rc == -1);
3254 item = (char *) zhash_lookup (hash, "LIVEBEEF");
3255 assert (streq (item, "dead beef"));
3256 item = (char *) zhash_lookup (hash, "ABADCAFE");
3257 assert (streq (item, "a bad cafe"));
3258
3259 // Test keys method
3260 zlist_t *keys = zhash_keys (hash);
3261 assert (zlist_size (keys) == 4);
3262 zlist_destroy (&keys);
3263
3264 // Test dup method
3265 zhash_t *copy = zhash_dup (hash);
3266 assert (zhash_size (copy) == 4);
3267 item = (char *) zhash_lookup (copy, "LIVEBEEF");
3268 assert (item);
3269 assert (streq (item, "dead beef"));
3270 zhash_destroy (©);
3271
3272 // Test pack/unpack methods
3273 zframe_t *frame = zhash_pack (hash);
3274 copy = zhash_unpack (frame);
3275 zframe_destroy (&frame);
3276 assert (zhash_size (copy) == 4);
3277 item = (char *) zhash_lookup (copy, "LIVEBEEF");
3278 assert (item);
3279 assert (streq (item, "dead beef"));
3280 zhash_destroy (©);
3281
3282 // Test save and load
3283 zhash_comment (hash, "This is a test file");
3284 zhash_comment (hash, "Created by %s", "czmq_selftest");
3285 zhash_save (hash, ".cache");
3286 copy = zhash_new ();
3287 assert (copy);
3288 zhash_load (copy, ".cache");
3289 item = (char *) zhash_lookup (copy, "LIVEBEEF");
3290 assert (item);
3291 assert (streq (item, "dead beef"));
3292 zhash_destroy (©);
3293 zsys_file_delete (".cache");
3294
3295 // Delete a item
3296 zhash_delete (hash, "LIVEBEEF");
3297 item = (char *) zhash_lookup (hash, "LIVEBEEF");
3298 assert (item == NULL);
3299 assert (zhash_size (hash) == 3);
3300
3301 // Check that the queue is robust against random usage
3302 struct {
3303 char name [100];
3304 bool exists;
3305 } testset [200];
3306 memset (testset, 0, sizeof (testset));
3307 int testmax = 200, testnbr, iteration;
3308
3309 srandom ((unsigned) time (NULL));
3310 for (iteration = 0; iteration < 25000; iteration++) {
3311 testnbr = randof (testmax);
3312 assert (testnbr != testmax);
3313 assert (testnbr < testmax);
3314 if (testset [testnbr].exists) {
3315 item = (char *) zhash_lookup (hash, testset [testnbr].name);
3316 assert (item);
3317 zhash_delete (hash, testset [testnbr].name);
3318 testset [testnbr].exists = false;
3319 }
3320 else {
3321 sprintf (testset [testnbr].name, "%x-%x", rand (), rand ());
3322 if (zhash_insert (hash, testset [testnbr].name, "") == 0)
3323 testset [testnbr].exists = true;
3324 }
3325 }
3326 // Test 10K lookups
3327 for (iteration = 0; iteration < 10000; iteration++)
3328 item = (char *) zhash_lookup (hash, "DEADBEEFABADCAFE");
3329
3330 // Destructor should be safe to call twice
3331 zhash_destroy (&hash);
3332 zhash_destroy (&hash);
3333 assert (hash == NULL);
3334
3335 // Test autofree; automatically copies and frees string values
3336 hash = zhash_new ();
3337 assert (hash);
3338 zhash_autofree (hash);
3339 char value [255];
3340 strcpy (value, "This is a string");
3341 rc = zhash_insert (hash, "key1", value);
3342 assert (rc == 0);
3343 strcpy (value, "Inserting with the same key will fail");
3344 rc = zhash_insert (hash, "key1", value);
3345 assert (rc == -1);
3346 strcpy (value, "Ring a ding ding");
3347 rc = zhash_insert (hash, "key2", value);
3348 assert (rc == 0);
3349 assert (streq ((char *) zhash_lookup (hash, "key1"), "This is a string"));
3350 assert (streq ((char *) zhash_lookup (hash, "key2"), "Ring a ding ding"));
3351 zhash_destroy (&hash);
3352
3353 #if defined (__WINDOWS__)
3354 zsys_shutdown();
3355 #endif
3356```
3357
3358#### zhashx - extended generic hash container
3359
3360zhashx is an extended hash table container with more functionality than
3361zhash, its simpler cousin.
3362
3363The hash table always has a size that is prime and roughly doubles its
3364size when 75% full. In case of hash collisions items are chained in a
3365linked list. The hash table size is increased slightly (up to 5 times
3366before roughly doubling the size) when an overly long chain (between 1
3367and 63 items depending on table size) is detected.
3368
3369This is the class interface:
3370
3371```h
3372 // This is a stable class, and may not change except for emergencies. It
3373 // is provided in stable builds.
3374 // This class has draft methods, which may change over time. They are not
3375 // in stable releases, by default. Use --enable-drafts to enable.
3376 // Destroy an item
3377 typedef void (zhashx_destructor_fn) (
3378 void **item);
3379
3380 // Duplicate an item
3381 typedef void * (zhashx_duplicator_fn) (
3382 const void *item);
3383
3384 // Compare two items, for sorting
3385 typedef int (zhashx_comparator_fn) (
3386 const void *item1, const void *item2);
3387
3388 // Destroy an item.
3389 typedef void (zhashx_free_fn) (
3390 void *data);
3391
3392 // Hash function for keys.
3393 typedef size_t (zhashx_hash_fn) (
3394 const void *key);
3395
3396 // Serializes an item to a longstr.
3397 // The caller takes ownership of the newly created object.
3398 typedef char * (zhashx_serializer_fn) (
3399 const void *item);
3400
3401 // Deserializes a longstr into an item.
3402 // The caller takes ownership of the newly created object.
3403 typedef void * (zhashx_deserializer_fn) (
3404 const char *item_str);
3405
3406 // Create a new, empty hash container
3407 CZMQ_EXPORT zhashx_t *
3408 zhashx_new (void);
3409
3410 // Unpack binary frame into a new hash table. Packed data must follow format
3411 // defined by zhashx_pack. Hash table is set to autofree. An empty frame
3412 // unpacks to an empty hash table.
3413 CZMQ_EXPORT zhashx_t *
3414 zhashx_unpack (zframe_t *frame);
3415
3416 // Destroy a hash container and all items in it
3417 CZMQ_EXPORT void
3418 zhashx_destroy (zhashx_t **self_p);
3419
3420 // Insert item into hash table with specified key and item.
3421 // If key is already present returns -1 and leaves existing item unchanged
3422 // Returns 0 on success.
3423 CZMQ_EXPORT int
3424 zhashx_insert (zhashx_t *self, const void *key, void *item);
3425
3426 // Update or insert item into hash table with specified key and item. If the
3427 // key is already present, destroys old item and inserts new one. If you set
3428 // a container item destructor, this is called on the old value. If the key
3429 // was not already present, inserts a new item. Sets the hash cursor to the
3430 // new item.
3431 CZMQ_EXPORT void
3432 zhashx_update (zhashx_t *self, const void *key, void *item);
3433
3434 // Remove an item specified by key from the hash table. If there was no such
3435 // item, this function does nothing.
3436 CZMQ_EXPORT void
3437 zhashx_delete (zhashx_t *self, const void *key);
3438
3439 // Delete all items from the hash table. If the key destructor is
3440 // set, calls it on every key. If the item destructor is set, calls
3441 // it on every item.
3442 CZMQ_EXPORT void
3443 zhashx_purge (zhashx_t *self);
3444
3445 // Return the item at the specified key, or null
3446 CZMQ_EXPORT void *
3447 zhashx_lookup (zhashx_t *self, const void *key);
3448
3449 // Reindexes an item from an old key to a new key. If there was no such
3450 // item, does nothing. Returns 0 if successful, else -1.
3451 CZMQ_EXPORT int
3452 zhashx_rename (zhashx_t *self, const void *old_key, const void *new_key);
3453
3454 // Set a free function for the specified hash table item. When the item is
3455 // destroyed, the free function, if any, is called on that item.
3456 // Use this when hash items are dynamically allocated, to ensure that
3457 // you don't have memory leaks. You can pass 'free' or NULL as a free_fn.
3458 // Returns the item, or NULL if there is no such item.
3459 CZMQ_EXPORT void *
3460 zhashx_freefn (zhashx_t *self, const void *key, zhashx_free_fn free_fn);
3461
3462 // Return the number of keys/items in the hash table
3463 CZMQ_EXPORT size_t
3464 zhashx_size (zhashx_t *self);
3465
3466 // Return a zlistx_t containing the keys for the items in the
3467 // table. Uses the key_duplicator to duplicate all keys and sets the
3468 // key_destructor as destructor for the list.
3469 // Caller owns return value and must destroy it when done.
3470 CZMQ_EXPORT zlistx_t *
3471 zhashx_keys (zhashx_t *self);
3472
3473 // Return a zlistx_t containing the values for the items in the
3474 // table. Uses the duplicator to duplicate all items and sets the
3475 // destructor as destructor for the list.
3476 // Caller owns return value and must destroy it when done.
3477 CZMQ_EXPORT zlistx_t *
3478 zhashx_values (zhashx_t *self);
3479
3480 // Simple iterator; returns first item in hash table, in no given order,
3481 // or NULL if the table is empty. This method is simpler to use than the
3482 // foreach() method, which is deprecated. To access the key for this item
3483 // use zhashx_cursor(). NOTE: do NOT modify the table while iterating.
3484 CZMQ_EXPORT void *
3485 zhashx_first (zhashx_t *self);
3486
3487 // Simple iterator; returns next item in hash table, in no given order,
3488 // or NULL if the last item was already returned. Use this together with
3489 // zhashx_first() to process all items in a hash table. If you need the
3490 // items in sorted order, use zhashx_keys() and then zlistx_sort(). To
3491 // access the key for this item use zhashx_cursor(). NOTE: do NOT modify
3492 // the table while iterating.
3493 CZMQ_EXPORT void *
3494 zhashx_next (zhashx_t *self);
3495
3496 // After a successful first/next method, returns the key for the item that
3497 // was returned. This is a constant string that you may not modify or
3498 // deallocate, and which lasts as long as the item in the hash. After an
3499 // unsuccessful first/next, returns NULL.
3500 CZMQ_EXPORT const void *
3501 zhashx_cursor (zhashx_t *self);
3502
3503 // Add a comment to hash table before saving to disk. You can add as many
3504 // comment lines as you like. These comment lines are discarded when loading
3505 // the file. If you use a null format, all comments are deleted.
3506 CZMQ_EXPORT void
3507 zhashx_comment (zhashx_t *self, const char *format, ...) CHECK_PRINTF (2);
3508
3509 // Save hash table to a text file in name=value format. Hash values must be
3510 // printable strings; keys may not contain '=' character. Returns 0 if OK,
3511 // else -1 if a file error occurred.
3512 CZMQ_EXPORT int
3513 zhashx_save (zhashx_t *self, const char *filename);
3514
3515 // Load hash table from a text file in name=value format; hash table must
3516 // already exist. Hash values must printable strings; keys may not contain
3517 // '=' character. Returns 0 if OK, else -1 if a file was not readable.
3518 CZMQ_EXPORT int
3519 zhashx_load (zhashx_t *self, const char *filename);
3520
3521 // When a hash table was loaded from a file by zhashx_load, this method will
3522 // reload the file if it has been modified since, and is "stable", i.e. not
3523 // still changing. Returns 0 if OK, -1 if there was an error reloading the
3524 // file.
3525 CZMQ_EXPORT int
3526 zhashx_refresh (zhashx_t *self);
3527
3528 // Serialize hash table to a binary frame that can be sent in a message.
3529 // The packed format is compatible with the 'dictionary' type defined in
3530 // http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto:
3531 //
3532 // ; A list of name/value pairs
3533 // dictionary = dict-count *( dict-name dict-value )
3534 // dict-count = number-4
3535 // dict-value = longstr
3536 // dict-name = string
3537 //
3538 // ; Strings are always length + text contents
3539 // longstr = number-4 *VCHAR
3540 // string = number-1 *VCHAR
3541 //
3542 // ; Numbers are unsigned integers in network byte order
3543 // number-1 = 1OCTET
3544 // number-4 = 4OCTET
3545 //
3546 // Comments are not included in the packed data. Item values MUST be
3547 // strings.
3548 // Caller owns return value and must destroy it when done.
3549 CZMQ_EXPORT zframe_t *
3550 zhashx_pack (zhashx_t *self);
3551
3552 // Make a copy of the list; items are duplicated if you set a duplicator
3553 // for the list, otherwise not. Copying a null reference returns a null
3554 // reference. Note that this method's behavior changed slightly for CZMQ
3555 // v3.x, as it does not set nor respect autofree. It does however let you
3556 // duplicate any hash table safely. The old behavior is in zhashx_dup_v2.
3557 // Caller owns return value and must destroy it when done.
3558 CZMQ_EXPORT zhashx_t *
3559 zhashx_dup (zhashx_t *self);
3560
3561 // Set a user-defined deallocator for hash items; by default items are not
3562 // freed when the hash is destroyed.
3563 CZMQ_EXPORT void
3564 zhashx_set_destructor (zhashx_t *self, zhashx_destructor_fn destructor);
3565
3566 // Set a user-defined duplicator for hash items; by default items are not
3567 // copied when the hash is duplicated.
3568 CZMQ_EXPORT void
3569 zhashx_set_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator);
3570
3571 // Set a user-defined deallocator for keys; by default keys are freed
3572 // when the hash is destroyed using free().
3573 CZMQ_EXPORT void
3574 zhashx_set_key_destructor (zhashx_t *self, zhashx_destructor_fn destructor);
3575
3576 // Set a user-defined duplicator for keys; by default keys are duplicated
3577 // using strdup.
3578 CZMQ_EXPORT void
3579 zhashx_set_key_duplicator (zhashx_t *self, zhashx_duplicator_fn duplicator);
3580
3581 // Set a user-defined comparator for keys; by default keys are
3582 // compared using strcmp.
3583 CZMQ_EXPORT void
3584 zhashx_set_key_comparator (zhashx_t *self, zhashx_comparator_fn comparator);
3585
3586 // Set a user-defined comparator for keys; by default keys are
3587 // compared using strcmp.
3588 CZMQ_EXPORT void
3589 zhashx_set_key_hasher (zhashx_t *self, zhashx_hash_fn hasher);
3590
3591 // Make copy of hash table; if supplied table is null, returns null.
3592 // Does not copy items themselves. Rebuilds new table so may be slow on
3593 // very large tables. NOTE: only works with item values that are strings
3594 // since there's no other way to know how to duplicate the item value.
3595 CZMQ_EXPORT zhashx_t *
3596 zhashx_dup_v2 (zhashx_t *self);
3597
3598 // Self test of this class.
3599 CZMQ_EXPORT void
3600 zhashx_test (bool verbose);
3601
3602 #ifdef CZMQ_BUILD_DRAFT_API
3603 // *** Draft method, for development use, may change without warning ***
3604 // Same as unpack but uses a user-defined deserializer function to convert
3605 // a longstr back into item format.
3606 CZMQ_EXPORT zhashx_t *
3607 zhashx_unpack_own (zframe_t *frame, zhashx_deserializer_fn deserializer);
3608
3609 // *** Draft method, for development use, may change without warning ***
3610 // Same as pack but uses a user-defined serializer function to convert items
3611 // into longstr.
3612 // Caller owns return value and must destroy it when done.
3613 CZMQ_EXPORT zframe_t *
3614 zhashx_pack_own (zhashx_t *self, zhashx_serializer_fn serializer);
3615
3616 #endif // CZMQ_BUILD_DRAFT_API
3617```
3618Please add '@interface' section in './../src/zhashx.c'.
3619
3620This is the class self test code:
3621
3622```c
3623 zhashx_t *hash = zhashx_new ();
3624 assert (hash);
3625 assert (zhashx_size (hash) == 0);
3626 assert (zhashx_first (hash) == NULL);
3627 assert (zhashx_cursor (hash) == NULL);
3628
3629 // Insert some items
3630 int rc;
3631 rc = zhashx_insert (hash, "DEADBEEF", "dead beef");
3632 char *item = (char *) zhashx_first (hash);
3633 assert (streq ((char *) zhashx_cursor (hash), "DEADBEEF"));
3634 assert (streq (item, "dead beef"));
3635 assert (rc == 0);
3636 rc = zhashx_insert (hash, "ABADCAFE", "a bad cafe");
3637 assert (rc == 0);
3638 rc = zhashx_insert (hash, "C0DEDBAD", "coded bad");
3639 assert (rc == 0);
3640 rc = zhashx_insert (hash, "DEADF00D", "dead food");
3641 assert (rc == 0);
3642 assert (zhashx_size (hash) == 4);
3643
3644 // Look for existing items
3645 item = (char *) zhashx_lookup (hash, "DEADBEEF");
3646 assert (streq (item, "dead beef"));
3647 item = (char *) zhashx_lookup (hash, "ABADCAFE");
3648 assert (streq (item, "a bad cafe"));
3649 item = (char *) zhashx_lookup (hash, "C0DEDBAD");
3650 assert (streq (item, "coded bad"));
3651 item = (char *) zhashx_lookup (hash, "DEADF00D");
3652 assert (streq (item, "dead food"));
3653
3654 // Look for non-existent items
3655 item = (char *) zhashx_lookup (hash, "foo");
3656 assert (item == NULL);
3657
3658 // Try to insert duplicate items
3659 rc = zhashx_insert (hash, "DEADBEEF", "foo");
3660 assert (rc == -1);
3661 item = (char *) zhashx_lookup (hash, "DEADBEEF");
3662 assert (streq (item, "dead beef"));
3663
3664 // Some rename tests
3665
3666 // Valid rename, key is now LIVEBEEF
3667 rc = zhashx_rename (hash, "DEADBEEF", "LIVEBEEF");
3668 assert (rc == 0);
3669 item = (char *) zhashx_lookup (hash, "LIVEBEEF");
3670 assert (streq (item, "dead beef"));
3671
3672 // Trying to rename an unknown item to a non-existent key
3673 rc = zhashx_rename (hash, "WHATBEEF", "NONESUCH");
3674 assert (rc == -1);
3675
3676 // Trying to rename an unknown item to an existing key
3677 rc = zhashx_rename (hash, "WHATBEEF", "LIVEBEEF");
3678 assert (rc == -1);
3679 item = (char *) zhashx_lookup (hash, "LIVEBEEF");
3680 assert (streq (item, "dead beef"));
3681
3682 // Trying to rename an existing item to another existing item
3683 rc = zhashx_rename (hash, "LIVEBEEF", "ABADCAFE");
3684 assert (rc == -1);
3685 item = (char *) zhashx_lookup (hash, "LIVEBEEF");
3686 assert (streq (item, "dead beef"));
3687 item = (char *) zhashx_lookup (hash, "ABADCAFE");
3688 assert (streq (item, "a bad cafe"));
3689
3690 // Test keys method
3691 zlistx_t *keys = zhashx_keys (hash);
3692 assert (zlistx_size (keys) == 4);
3693 zlistx_destroy (&keys);
3694
3695 zlistx_t *values = zhashx_values(hash);
3696 assert (zlistx_size (values) == 4);
3697 zlistx_destroy (&values);
3698
3699 // Test dup method
3700 zhashx_t *copy = zhashx_dup (hash);
3701 assert (zhashx_size (copy) == 4);
3702 item = (char *) zhashx_lookup (copy, "LIVEBEEF");
3703 assert (item);
3704 assert (streq (item, "dead beef"));
3705 zhashx_destroy (©);
3706
3707 // Test pack/unpack methods
3708 zframe_t *frame = zhashx_pack (hash);
3709 copy = zhashx_unpack (frame);
3710 zframe_destroy (&frame);
3711 assert (zhashx_size (copy) == 4);
3712 item = (char *) zhashx_lookup (copy, "LIVEBEEF");
3713 assert (item);
3714 assert (streq (item, "dead beef"));
3715 zhashx_destroy (©);
3716
3717 #ifdef CZMQ_BUILD_DRAFT_API
3718 // Test own pack/unpack methods
3719 zhashx_t *own_hash = zhashx_new ();
3720 zhashx_set_destructor (own_hash, s_test_destroy_int);
3721 assert (own_hash);
3722 int *val1 = (int *) zmalloc (sizeof (int));
3723 int *val2 = (int *) zmalloc (sizeof (int));
3724 *val1 = 25;
3725 *val2 = 100;
3726 zhashx_insert (own_hash, "val1", val1);
3727 zhashx_insert (own_hash, "val2", val2);
3728 frame = zhashx_pack_own (own_hash, s_test_serialize_int);
3729 copy = zhashx_unpack_own (frame, s_test_deserialze_int);
3730 zhashx_set_destructor (copy, s_test_destroy_int);
3731 zframe_destroy (&frame);
3732 assert (zhashx_size (copy) == 2);
3733 assert (*((int *) zhashx_lookup (copy, "val1")) == 25);
3734 assert (*((int *) zhashx_lookup (copy, "val2")) == 100);
3735 zhashx_destroy (©);
3736 zhashx_destroy (&own_hash);
3737 #endif // CZMQ_BUILD_DRAFT_API
3738
3739 // Test save and load
3740 zhashx_comment (hash, "This is a test file");
3741 zhashx_comment (hash, "Created by %s", "czmq_selftest");
3742 zhashx_save (hash, ".cache");
3743 copy = zhashx_new ();
3744 assert (copy);
3745 zhashx_load (copy, ".cache");
3746 item = (char *) zhashx_lookup (copy, "LIVEBEEF");
3747 assert (item);
3748 assert (streq (item, "dead beef"));
3749 zhashx_destroy (©);
3750 zsys_file_delete (".cache");
3751
3752 // Delete a item
3753 zhashx_delete (hash, "LIVEBEEF");
3754 item = (char *) zhashx_lookup (hash, "LIVEBEEF");
3755 assert (item == NULL);
3756 assert (zhashx_size (hash) == 3);
3757
3758 // Check that the queue is robust against random usage
3759 struct {
3760 char name [100];
3761 bool exists;
3762 } testset [200];
3763 memset (testset, 0, sizeof (testset));
3764 int testmax = 200, testnbr, iteration;
3765
3766 srandom ((unsigned) time (NULL));
3767 for (iteration = 0; iteration < 25000; iteration++) {
3768 testnbr = randof (testmax);
3769 if (testset [testnbr].exists) {
3770 item = (char *) zhashx_lookup (hash, testset [testnbr].name);
3771 assert (item);
3772 zhashx_delete (hash, testset [testnbr].name);
3773 testset [testnbr].exists = false;
3774 }
3775 else {
3776 sprintf (testset [testnbr].name, "%x-%x", rand (), rand ());
3777 if (zhashx_insert (hash, testset [testnbr].name, "") == 0)
3778 testset [testnbr].exists = true;
3779 }
3780 }
3781 // Test 10K lookups
3782 for (iteration = 0; iteration < 10000; iteration++)
3783 item = (char *) zhashx_lookup (hash, "DEADBEEFABADCAFE");
3784
3785 // Destructor should be safe to call twice
3786 zhashx_destroy (&hash);
3787 zhashx_destroy (&hash);
3788 assert (hash == NULL);
3789
3790 // Test destructor; automatically copies and frees string values
3791 hash = zhashx_new ();
3792 assert (hash);
3793 zhashx_set_destructor (hash, (zhashx_destructor_fn *) zstr_free);
3794 zhashx_set_duplicator (hash, (zhashx_duplicator_fn *) strdup);
3795 char value [255];
3796 strcpy (value, "This is a string");
3797 rc = zhashx_insert (hash, "key1", value);
3798 assert (rc == 0);
3799 strcpy (value, "Ring a ding ding");
3800 rc = zhashx_insert (hash, "key2", value);
3801 assert (rc == 0);
3802 assert (streq ((char *) zhashx_lookup (hash, "key1"), "This is a string"));
3803 assert (streq ((char *) zhashx_lookup (hash, "key2"), "Ring a ding ding"));
3804 zhashx_destroy (&hash);
3805
3806 // Test purger and shrinker: no data should end up unreferenced in valgrind
3807 hash = zhashx_new ();
3808 assert (hash);
3809 zhashx_set_destructor (hash, (zhashx_destructor_fn *) zstr_free);
3810 zhashx_set_duplicator (hash, (zhashx_duplicator_fn *) strdup);
3811 char valuep [255];
3812 strcpy (valuep, "This is a string");
3813 rc = zhashx_insert (hash, "key1", valuep);
3814 assert (rc == 0);
3815 strcpy (valuep, "Ring a ding ding");
3816 rc = zhashx_insert (hash, "key2", valuep);
3817 assert (rc == 0);
3818 strcpy (valuep, "Cartahena delenda est");
3819 rc = zhashx_insert (hash, "key3", valuep);
3820 assert (rc == 0);
3821 strcpy (valuep, "So say we all!");
3822 rc = zhashx_insert (hash, "key4", valuep);
3823 assert (rc == 0);
3824 assert (streq ((char *) zhashx_lookup (hash, "key1"), "This is a string"));
3825 assert (streq ((char *) zhashx_lookup (hash, "key2"), "Ring a ding ding"));
3826 assert (streq ((char *) zhashx_lookup (hash, "key3"), "Cartahena delenda est"));
3827 assert (streq ((char *) zhashx_lookup (hash, "key4"), "So say we all!"));
3828 zhashx_purge (hash);
3829 zhashx_destroy (&hash);
3830
3831 #if defined (__WINDOWS__)
3832 zsys_shutdown();
3833 #endif
3834```
3835
3836#### ziflist - list of network interfaces available on system
3837
3838The ziflist class takes a snapshot of the network interfaces that the
3839system currently supports (this can change arbitrarily, especially on
3840mobile devices). The caller can then access the network interface
3841information using an iterator that works like zlistx. Only stores those
3842interfaces with broadcast capability, and ignores the loopback interface.
3843
3844Please add '@discuss' section in './../src/ziflist.c'.
3845
3846This is the class interface:
3847
3848```h
3849 // This is a stable class, and may not change except for emergencies. It
3850 // is provided in stable builds.
3851 // This class has draft methods, which may change over time. They are not
3852 // in stable releases, by default. Use --enable-drafts to enable.
3853 // Get a list of network interfaces currently defined on the system
3854 CZMQ_EXPORT ziflist_t *
3855 ziflist_new (void);
3856
3857 // Destroy a ziflist instance
3858 CZMQ_EXPORT void
3859 ziflist_destroy (ziflist_t **self_p);
3860
3861 // Reload network interfaces from system
3862 CZMQ_EXPORT void
3863 ziflist_reload (ziflist_t *self);
3864
3865 // Return the number of network interfaces on system
3866 CZMQ_EXPORT size_t
3867 ziflist_size (ziflist_t *self);
3868
3869 // Get first network interface, return NULL if there are none
3870 CZMQ_EXPORT const char *
3871 ziflist_first (ziflist_t *self);
3872
3873 // Get next network interface, return NULL if we hit the last one
3874 CZMQ_EXPORT const char *
3875 ziflist_next (ziflist_t *self);
3876
3877 // Return the current interface IP address as a printable string
3878 CZMQ_EXPORT const char *
3879 ziflist_address (ziflist_t *self);
3880
3881 // Return the current interface broadcast address as a printable string
3882 CZMQ_EXPORT const char *
3883 ziflist_broadcast (ziflist_t *self);
3884
3885 // Return the current interface network mask as a printable string
3886 CZMQ_EXPORT const char *
3887 ziflist_netmask (ziflist_t *self);
3888
3889 // Return the list of interfaces.
3890 CZMQ_EXPORT void
3891 ziflist_print (ziflist_t *self);
3892
3893 // Self test of this class.
3894 CZMQ_EXPORT void
3895 ziflist_test (bool verbose);
3896
3897 #ifdef CZMQ_BUILD_DRAFT_API
3898 // *** Draft method, for development use, may change without warning ***
3899 // Get a list of network interfaces currently defined on the system
3900 // Includes IPv6 interfaces
3901 // Caller owns return value and must destroy it when done.
3902 CZMQ_EXPORT ziflist_t *
3903 ziflist_new_ipv6 (void);
3904
3905 // *** Draft method, for development use, may change without warning ***
3906 // Reload network interfaces from system, including IPv6
3907 CZMQ_EXPORT void
3908 ziflist_reload_ipv6 (ziflist_t *self);
3909
3910 // *** Draft method, for development use, may change without warning ***
3911 // Return true if the current interface uses IPv6
3912 CZMQ_EXPORT bool
3913 ziflist_is_ipv6 (ziflist_t *self);
3914
3915 #endif // CZMQ_BUILD_DRAFT_API
3916```
3917Please add '@interface' section in './../src/ziflist.c'.
3918
3919This is the class self test code:
3920
3921```c
3922 ziflist_t *iflist = ziflist_new ();
3923 assert (iflist);
3924
3925 size_t items = ziflist_size (iflist);
3926
3927 if (verbose) {
3928 printf ("ziflist: interfaces=%zu\n", ziflist_size (iflist));
3929 const char *name = ziflist_first (iflist);
3930 while (name) {
3931 printf (" - name=%s address=%s netmask=%s broadcast=%s\n",
3932 name, ziflist_address (iflist), ziflist_netmask (iflist), ziflist_broadcast (iflist));
3933 name = ziflist_next (iflist);
3934 }
3935 }
3936 ziflist_reload (iflist);
3937 assert (items == ziflist_size (iflist));
3938 ziflist_destroy (&iflist);
3939
3940 #if defined (__WINDOWS__)
3941 zsys_shutdown();
3942 #endif
3943```
3944
3945#### zlist - simple generic list container
3946
3947Provides a generic container implementing a fast singly-linked list. You
3948can use this to construct multi-dimensional lists, and other structures
3949together with other generic containers like zhash. This is a simple
3950class. For demanding applications we recommend using zlistx.
3951
3952To iterate through a list, use zlist_first to get the first item, then
3953loop while not null, and do zlist_next at the end of each iteration.
3954
3955This is the class interface:
3956
3957```h
3958 // This is a stable class, and may not change except for emergencies. It
3959 // is provided in stable builds.
3960 // Comparison function e.g. for sorting and removing.
3961 typedef int (zlist_compare_fn) (
3962 void *item1, void *item2);
3963
3964 // Callback function for zlist_freefn method
3965 typedef void (zlist_free_fn) (
3966 void *data);
3967
3968 // Create a new list container
3969 CZMQ_EXPORT zlist_t *
3970 zlist_new (void);
3971
3972 // Destroy a list container
3973 CZMQ_EXPORT void
3974 zlist_destroy (zlist_t **self_p);
3975
3976 // Return the item at the head of list. If the list is empty, returns NULL.
3977 // Leaves cursor pointing at the head item, or NULL if the list is empty.
3978 CZMQ_EXPORT void *
3979 zlist_first (zlist_t *self);
3980
3981 // Return the next item. If the list is empty, returns NULL. To move to
3982 // the start of the list call zlist_first (). Advances the cursor.
3983 CZMQ_EXPORT void *
3984 zlist_next (zlist_t *self);
3985
3986 // Return the item at the tail of list. If the list is empty, returns NULL.
3987 // Leaves cursor pointing at the tail item, or NULL if the list is empty.
3988 CZMQ_EXPORT void *
3989 zlist_last (zlist_t *self);
3990
3991 // Return first item in the list, or null, leaves the cursor
3992 CZMQ_EXPORT void *
3993 zlist_head (zlist_t *self);
3994
3995 // Return last item in the list, or null, leaves the cursor
3996 CZMQ_EXPORT void *
3997 zlist_tail (zlist_t *self);
3998
3999 // Return the current item of list. If the list is empty, returns NULL.
4000 // Leaves cursor pointing at the current item, or NULL if the list is empty.
4001 CZMQ_EXPORT void *
4002 zlist_item (zlist_t *self);
4003
4004 // Append an item to the end of the list, return 0 if OK or -1 if this
4005 // failed for some reason (out of memory). Note that if a duplicator has
4006 // been set, this method will also duplicate the item.
4007 CZMQ_EXPORT int
4008 zlist_append (zlist_t *self, void *item);
4009
4010 // Push an item to the start of the list, return 0 if OK or -1 if this
4011 // failed for some reason (out of memory). Note that if a duplicator has
4012 // been set, this method will also duplicate the item.
4013 CZMQ_EXPORT int
4014 zlist_push (zlist_t *self, void *item);
4015
4016 // Pop the item off the start of the list, if any
4017 CZMQ_EXPORT void *
4018 zlist_pop (zlist_t *self);
4019
4020 // Checks if an item already is present. Uses compare method to determine if
4021 // items are equal. If the compare method is NULL the check will only compare
4022 // pointers. Returns true if item is present else false.
4023 CZMQ_EXPORT bool
4024 zlist_exists (zlist_t *self, void *item);
4025
4026 // Remove the specified item from the list if present
4027 CZMQ_EXPORT void
4028 zlist_remove (zlist_t *self, void *item);
4029
4030 // Make a copy of list. If the list has autofree set, the copied list will
4031 // duplicate all items, which must be strings. Otherwise, the list will hold
4032 // pointers back to the items in the original list. If list is null, returns
4033 // NULL.
4034 // Caller owns return value and must destroy it when done.
4035 CZMQ_EXPORT zlist_t *
4036 zlist_dup (zlist_t *self);
4037
4038 // Purge all items from list
4039 CZMQ_EXPORT void
4040 zlist_purge (zlist_t *self);
4041
4042 // Return number of items in the list
4043 CZMQ_EXPORT size_t
4044 zlist_size (zlist_t *self);
4045
4046 // Sort the list. If the compare function is null, sorts the list by
4047 // ascending key value using a straight ASCII comparison. If you specify
4048 // a compare function, this decides how items are sorted. The sort is not
4049 // stable, so may reorder items with the same keys. The algorithm used is
4050 // combsort, a compromise between performance and simplicity.
4051 CZMQ_EXPORT void
4052 zlist_sort (zlist_t *self, zlist_compare_fn compare);
4053
4054 // Set list for automatic item destruction; item values MUST be strings.
4055 // By default a list item refers to a value held elsewhere. When you set
4056 // this, each time you append or push a list item, zlist will take a copy
4057 // of the string value. Then, when you destroy the list, it will free all
4058 // item values automatically. If you use any other technique to allocate
4059 // list values, you must free them explicitly before destroying the list.
4060 // The usual technique is to pop list items and destroy them, until the
4061 // list is empty.
4062 CZMQ_EXPORT void
4063 zlist_autofree (zlist_t *self);
4064
4065 // Sets a compare function for this list. The function compares two items.
4066 // It returns an integer less than, equal to, or greater than zero if the
4067 // first item is found, respectively, to be less than, to match, or be
4068 // greater than the second item.
4069 // This function is used for sorting, removal and exists checking.
4070 CZMQ_EXPORT void
4071 zlist_comparefn (zlist_t *self, zlist_compare_fn fn);
4072
4073 // Set a free function for the specified list item. When the item is
4074 // destroyed, the free function, if any, is called on that item.
4075 // Use this when list items are dynamically allocated, to ensure that
4076 // you don't have memory leaks. You can pass 'free' or NULL as a free_fn.
4077 // Returns the item, or NULL if there is no such item.
4078 CZMQ_EXPORT void *
4079 zlist_freefn (zlist_t *self, void *item, zlist_free_fn fn, bool at_tail);
4080
4081 // Self test of this class.
4082 CZMQ_EXPORT void
4083 zlist_test (bool verbose);
4084
4085```
4086Please add '@interface' section in './../src/zlist.c'.
4087
4088This is the class self test code:
4089
4090```c
4091 zlist_t *list = zlist_new ();
4092 assert (list);
4093 assert (zlist_size (list) == 0);
4094
4095 // Three items we'll use as test data
4096 // List items are void *, not particularly strings
4097 char *cheese = "boursin";
4098 char *bread = "baguette";
4099 char *wine = "bordeaux";
4100
4101 zlist_append (list, cheese);
4102 assert (zlist_size (list) == 1);
4103 assert ( zlist_exists (list, cheese));
4104 assert (!zlist_exists (list, bread));
4105 assert (!zlist_exists (list, wine));
4106 zlist_append (list, bread);
4107 assert (zlist_size (list) == 2);
4108 assert ( zlist_exists (list, cheese));
4109 assert ( zlist_exists (list, bread));
4110 assert (!zlist_exists (list, wine));
4111 zlist_append (list, wine);
4112 assert (zlist_size (list) == 3);
4113 assert ( zlist_exists (list, cheese));
4114 assert ( zlist_exists (list, bread));
4115 assert ( zlist_exists (list, wine));
4116
4117 assert (zlist_head (list) == cheese);
4118 assert (zlist_next (list) == cheese);
4119
4120 assert (zlist_first (list) == cheese);
4121 assert (zlist_tail (list) == wine);
4122 assert (zlist_next (list) == bread);
4123
4124 assert (zlist_first (list) == cheese);
4125 assert (zlist_next (list) == bread);
4126 assert (zlist_next (list) == wine);
4127 assert (zlist_next (list) == NULL);
4128 // After we reach end of list, next wraps around
4129 assert (zlist_next (list) == cheese);
4130 assert (zlist_size (list) == 3);
4131
4132 zlist_remove (list, wine);
4133 assert (zlist_size (list) == 2);
4134
4135 assert (zlist_first (list) == cheese);
4136 zlist_remove (list, cheese);
4137 assert (zlist_size (list) == 1);
4138 assert (zlist_first (list) == bread);
4139
4140 zlist_remove (list, bread);
4141 assert (zlist_size (list) == 0);
4142
4143 zlist_append (list, cheese);
4144 zlist_append (list, bread);
4145 assert (zlist_last (list) == bread);
4146 zlist_remove (list, bread);
4147 assert (zlist_last (list) == cheese);
4148 zlist_remove (list, cheese);
4149 assert (zlist_last (list) == NULL);
4150
4151 zlist_push (list, cheese);
4152 assert (zlist_size (list) == 1);
4153 assert (zlist_first (list) == cheese);
4154
4155 zlist_push (list, bread);
4156 assert (zlist_size (list) == 2);
4157 assert (zlist_first (list) == bread);
4158 assert (zlist_item (list) == bread);
4159
4160 zlist_append (list, wine);
4161 assert (zlist_size (list) == 3);
4162 assert (zlist_first (list) == bread);
4163
4164 zlist_t *sub_list = zlist_dup (list);
4165 assert (sub_list);
4166 assert (zlist_size (sub_list) == 3);
4167
4168 zlist_sort (list, NULL);
4169 char *item;
4170 item = (char *) zlist_pop (list);
4171 assert (item == bread);
4172 item = (char *) zlist_pop (list);
4173 assert (item == wine);
4174 item = (char *) zlist_pop (list);
4175 assert (item == cheese);
4176 assert (zlist_size (list) == 0);
4177
4178 assert (zlist_size (sub_list) == 3);
4179 zlist_push (list, sub_list);
4180 zlist_t *sub_list_2 = zlist_dup (sub_list);
4181 zlist_append (list, sub_list_2);
4182 assert (zlist_freefn (list, sub_list, &s_zlist_free, false) == sub_list);
4183 assert (zlist_freefn (list, sub_list_2, &s_zlist_free, true) == sub_list_2);
4184 zlist_destroy (&list);
4185
4186 // Test autofree functionality
4187 list = zlist_new ();
4188 assert (list);
4189 zlist_autofree (list);
4190 // Set equals function otherwise equals will not work as autofree copies strings
4191 zlist_comparefn (list, (zlist_compare_fn *) strcmp);
4192 zlist_push (list, bread);
4193 zlist_append (list, cheese);
4194 assert (zlist_size (list) == 2);
4195 zlist_append (list, wine);
4196 assert (zlist_exists (list, wine));
4197 zlist_remove (list, wine);
4198 assert (!zlist_exists (list, wine));
4199 assert (streq ((const char *) zlist_first (list), bread));
4200 item = (char *) zlist_pop (list);
4201 assert (streq (item, bread));
4202 free (item);
4203 item = (char *) zlist_pop (list);
4204 assert (streq (item, cheese));
4205 free (item);
4206
4207 zlist_destroy (&list);
4208 assert (list == NULL);
4209
4210 #if defined (__WINDOWS__)
4211 zsys_shutdown();
4212 #endif
4213```
4214
4215#### zlistx - extended generic list container
4216
4217Provides a generic doubly-linked list container. This container provides
4218hooks for duplicator, comparator, and destructor functions. These tie
4219into CZMQ and standard C semantics, so e.g. for string items you can
4220use strdup, strcmp, and zstr_free. To store custom objects, define your
4221own duplicator and comparator, and use the standard object destructor.
4222
4223This is a reworking of the simpler zlist container. It is faster to
4224insert and delete items anywhere in the list, and to keep ordered lists.
4225
4226This is the class interface:
4227
4228```h
4229 // This is a stable class, and may not change except for emergencies. It
4230 // is provided in stable builds.
4231 // Destroy an item
4232 typedef void (zlistx_destructor_fn) (
4233 void **item);
4234
4235 // Duplicate an item
4236 typedef void * (zlistx_duplicator_fn) (
4237 const void *item);
4238
4239 // Compare two items, for sorting
4240 typedef int (zlistx_comparator_fn) (
4241 const void *item1, const void *item2);
4242
4243 // Create a new, empty list.
4244 CZMQ_EXPORT zlistx_t *
4245 zlistx_new (void);
4246
4247 // Destroy a list. If an item destructor was specified, all items in the
4248 // list are automatically destroyed as well.
4249 CZMQ_EXPORT void
4250 zlistx_destroy (zlistx_t **self_p);
4251
4252 // Add an item to the head of the list. Calls the item duplicator, if any,
4253 // on the item. Resets cursor to list head. Returns an item handle on
4254 // success, NULL if memory was exhausted.
4255 CZMQ_EXPORT void *
4256 zlistx_add_start (zlistx_t *self, void *item);
4257
4258 // Add an item to the tail of the list. Calls the item duplicator, if any,
4259 // on the item. Resets cursor to list head. Returns an item handle on
4260 // success, NULL if memory was exhausted.
4261 CZMQ_EXPORT void *
4262 zlistx_add_end (zlistx_t *self, void *item);
4263
4264 // Return the number of items in the list
4265 CZMQ_EXPORT size_t
4266 zlistx_size (zlistx_t *self);
4267
4268 // Return first item in the list, or null, leaves the cursor
4269 CZMQ_EXPORT void *
4270 zlistx_head (zlistx_t *self);
4271
4272 // Return last item in the list, or null, leaves the cursor
4273 CZMQ_EXPORT void *
4274 zlistx_tail (zlistx_t *self);
4275
4276 // Return the item at the head of list. If the list is empty, returns NULL.
4277 // Leaves cursor pointing at the head item, or NULL if the list is empty.
4278 CZMQ_EXPORT void *
4279 zlistx_first (zlistx_t *self);
4280
4281 // Return the next item. At the end of the list (or in an empty list),
4282 // returns NULL. Use repeated zlistx_next () calls to work through the list
4283 // from zlistx_first (). First time, acts as zlistx_first().
4284 CZMQ_EXPORT void *
4285 zlistx_next (zlistx_t *self);
4286
4287 // Return the previous item. At the start of the list (or in an empty list),
4288 // returns NULL. Use repeated zlistx_prev () calls to work through the list
4289 // backwards from zlistx_last (). First time, acts as zlistx_last().
4290 CZMQ_EXPORT void *
4291 zlistx_prev (zlistx_t *self);
4292
4293 // Return the item at the tail of list. If the list is empty, returns NULL.
4294 // Leaves cursor pointing at the tail item, or NULL if the list is empty.
4295 CZMQ_EXPORT void *
4296 zlistx_last (zlistx_t *self);
4297
4298 // Returns the value of the item at the cursor, or NULL if the cursor is
4299 // not pointing to an item.
4300 CZMQ_EXPORT void *
4301 zlistx_item (zlistx_t *self);
4302
4303 // Returns the handle of the item at the cursor, or NULL if the cursor is
4304 // not pointing to an item.
4305 CZMQ_EXPORT void *
4306 zlistx_cursor (zlistx_t *self);
4307
4308 // Returns the item associated with the given list handle, or NULL if passed
4309 // in handle is NULL. Asserts that the passed in handle points to a list element.
4310 CZMQ_EXPORT void *
4311 zlistx_handle_item (void *handle);
4312
4313 // Find an item in the list, searching from the start. Uses the item
4314 // comparator, if any, else compares item values directly. Returns the
4315 // item handle found, or NULL. Sets the cursor to the found item, if any.
4316 CZMQ_EXPORT void *
4317 zlistx_find (zlistx_t *self, void *item);
4318
4319 // Detach an item from the list, using its handle. The item is not modified,
4320 // and the caller is responsible for destroying it if necessary. If handle is
4321 // null, detaches the first item on the list. Returns item that was detached,
4322 // or null if none was. If cursor was at item, moves cursor to previous item,
4323 // so you can detach items while iterating forwards through a list.
4324 CZMQ_EXPORT void *
4325 zlistx_detach (zlistx_t *self, void *handle);
4326
4327 // Detach item at the cursor, if any, from the list. The item is not modified,
4328 // and the caller is responsible for destroying it as necessary. Returns item
4329 // that was detached, or null if none was. Moves cursor to previous item, so
4330 // you can detach items while iterating forwards through a list.
4331 CZMQ_EXPORT void *
4332 zlistx_detach_cur (zlistx_t *self);
4333
4334 // Delete an item, using its handle. Calls the item destructor is any is
4335 // set. If handle is null, deletes the first item on the list. Returns 0
4336 // if an item was deleted, -1 if not. If cursor was at item, moves cursor
4337 // to previous item, so you can delete items while iterating forwards
4338 // through a list.
4339 CZMQ_EXPORT int
4340 zlistx_delete (zlistx_t *self, void *handle);
4341
4342 // Move an item to the start of the list, via its handle.
4343 CZMQ_EXPORT void
4344 zlistx_move_start (zlistx_t *self, void *handle);
4345
4346 // Move an item to the end of the list, via its handle.
4347 CZMQ_EXPORT void
4348 zlistx_move_end (zlistx_t *self, void *handle);
4349
4350 // Remove all items from the list, and destroy them if the item destructor
4351 // is set.
4352 CZMQ_EXPORT void
4353 zlistx_purge (zlistx_t *self);
4354
4355 // Sort the list. If an item comparator was set, calls that to compare
4356 // items, otherwise compares on item value. The sort is not stable, so may
4357 // reorder equal items.
4358 CZMQ_EXPORT void
4359 zlistx_sort (zlistx_t *self);
4360
4361 // Create a new node and insert it into a sorted list. Calls the item
4362 // duplicator, if any, on the item. If low_value is true, starts searching
4363 // from the start of the list, otherwise searches from the end. Use the item
4364 // comparator, if any, to find where to place the new node. Returns a handle
4365 // to the new node, or NULL if memory was exhausted. Resets the cursor to the
4366 // list head.
4367 CZMQ_EXPORT void *
4368 zlistx_insert (zlistx_t *self, void *item, bool low_value);
4369
4370 // Move an item, specified by handle, into position in a sorted list. Uses
4371 // the item comparator, if any, to determine the new location. If low_value
4372 // is true, starts searching from the start of the list, otherwise searches
4373 // from the end.
4374 CZMQ_EXPORT void
4375 zlistx_reorder (zlistx_t *self, void *handle, bool low_value);
4376
4377 // Make a copy of the list; items are duplicated if you set a duplicator
4378 // for the list, otherwise not. Copying a null reference returns a null
4379 // reference.
4380 CZMQ_EXPORT zlistx_t *
4381 zlistx_dup (zlistx_t *self);
4382
4383 // Set a user-defined deallocator for list items; by default items are not
4384 // freed when the list is destroyed.
4385 CZMQ_EXPORT void
4386 zlistx_set_destructor (zlistx_t *self, zlistx_destructor_fn destructor);
4387
4388 // Set a user-defined duplicator for list items; by default items are not
4389 // copied when the list is duplicated.
4390 CZMQ_EXPORT void
4391 zlistx_set_duplicator (zlistx_t *self, zlistx_duplicator_fn duplicator);
4392
4393 // Set a user-defined comparator for zlistx_find and zlistx_sort; the method
4394 // must return -1, 0, or 1 depending on whether item1 is less than, equal to,
4395 // or greater than, item2.
4396 CZMQ_EXPORT void
4397 zlistx_set_comparator (zlistx_t *self, zlistx_comparator_fn comparator);
4398
4399 // Self test of this class.
4400 CZMQ_EXPORT void
4401 zlistx_test (bool verbose);
4402
4403```
4404Please add '@interface' section in './../src/zlistx.c'.
4405
4406This is the class self test code:
4407
4408```c
4409 zlistx_t *list = zlistx_new ();
4410 assert (list);
4411 assert (zlistx_size (list) == 0);
4412
4413 // Test operations on an empty list
4414 assert (zlistx_first (list) == NULL);
4415 assert (zlistx_last (list) == NULL);
4416 assert (zlistx_next (list) == NULL);
4417 assert (zlistx_prev (list) == NULL);
4418 assert (zlistx_find (list, "hello") == NULL);
4419 assert (zlistx_delete (list, NULL) == -1);
4420 assert (zlistx_detach (list, NULL) == NULL);
4421 assert (zlistx_delete (list, NULL) == -1);
4422 assert (zlistx_detach (list, NULL) == NULL);
4423 zlistx_purge (list);
4424 zlistx_sort (list);
4425
4426 // Use item handlers
4427 zlistx_set_destructor (list, (zlistx_destructor_fn *) zstr_free);
4428 zlistx_set_duplicator (list, (zlistx_duplicator_fn *) strdup);
4429 zlistx_set_comparator (list, (zlistx_comparator_fn *) strcmp);
4430
4431 // Try simple insert/sort/delete/next
4432 assert (zlistx_next (list) == NULL);
4433 zlistx_add_end (list, "world");
4434 assert (streq ((char *) zlistx_next (list), "world"));
4435 zlistx_add_end (list, "hello");
4436 assert (streq ((char *) zlistx_prev (list), "hello"));
4437 zlistx_sort (list);
4438 assert (zlistx_size (list) == 2);
4439 void *handle = zlistx_find (list, "hello");
4440 char *item1 = (char *) zlistx_item (list);
4441 char *item2 = (char *) zlistx_handle_item (handle);
4442 assert (item1 == item2);
4443 assert (streq (item1, "hello"));
4444 zlistx_delete (list, handle);
4445 assert (zlistx_size (list) == 1);
4446 char *string = (char *) zlistx_detach (list, NULL);
4447 assert (streq (string, "world"));
4448 free (string);
4449 assert (zlistx_size (list) == 0);
4450
4451 // Check next/back work
4452 // Now populate the list with items
4453 zlistx_add_start (list, "five");
4454 zlistx_add_end (list, "six");
4455 zlistx_add_start (list, "four");
4456 zlistx_add_end (list, "seven");
4457 zlistx_add_start (list, "three");
4458 zlistx_add_end (list, "eight");
4459 zlistx_add_start (list, "two");
4460 zlistx_add_end (list, "nine");
4461 zlistx_add_start (list, "one");
4462 zlistx_add_end (list, "ten");
4463
4464 // Test our navigation skills
4465 assert (zlistx_size (list) == 10);
4466 assert (streq ((char *) zlistx_last (list), "ten"));
4467 assert (streq ((char *) zlistx_prev (list), "nine"));
4468 assert (streq ((char *) zlistx_prev (list), "eight"));
4469 assert (streq ((char *) zlistx_prev (list), "seven"));
4470 assert (streq ((char *) zlistx_prev (list), "six"));
4471 assert (streq ((char *) zlistx_prev (list), "five"));
4472 assert (streq ((char *) zlistx_first (list), "one"));
4473 assert (streq ((char *) zlistx_next (list), "two"));
4474 assert (streq ((char *) zlistx_next (list), "three"));
4475 assert (streq ((char *) zlistx_next (list), "four"));
4476
4477 // Sort by alphabetical order
4478 zlistx_sort (list);
4479 assert (streq ((char *) zlistx_first (list), "eight"));
4480 assert (streq ((char *) zlistx_last (list), "two"));
4481
4482 // Moving items around
4483 handle = zlistx_find (list, "six");
4484 zlistx_move_start (list, handle);
4485 assert (streq ((char *) zlistx_first (list), "six"));
4486 zlistx_move_end (list, handle);
4487 assert (streq ((char *) zlistx_last (list), "six"));
4488 zlistx_sort (list);
4489 assert (streq ((char *) zlistx_last (list), "two"));
4490
4491 // Copying a list
4492 zlistx_t *copy = zlistx_dup (list);
4493 assert (copy);
4494 assert (zlistx_size (copy) == 10);
4495 assert (streq ((char *) zlistx_first (copy), "eight"));
4496 assert (streq ((char *) zlistx_last (copy), "two"));
4497 zlistx_destroy (©);
4498
4499 // Delete items while iterating
4500 string = (char *) zlistx_first (list);
4501 assert (streq (string, "eight"));
4502 string = (char *) zlistx_next (list);
4503 assert (streq (string, "five"));
4504 zlistx_delete (list, zlistx_cursor (list));
4505 string = (char *) zlistx_next (list);
4506 assert (streq (string, "four"));
4507
4508 zlistx_purge (list);
4509 zlistx_destroy (&list);
4510
4511 #if defined (__WINDOWS__)
4512 zsys_shutdown();
4513 #endif
4514```
4515
4516#### zloop - event-driven reactor
4517
4518The zloop class provides an event-driven reactor pattern. The reactor
4519handles zmq_pollitem_t items (pollers or writers, sockets or fds), and
4520once-off or repeated timers. Its resolution is 1 msec. It uses a tickless
4521timer to reduce CPU interrupts in inactive processes.
4522
4523Please add '@discuss' section in './../src/zloop.c'.
4524
4525This is the class interface:
4526
4527```h
4528 // This is a stable class, and may not change except for emergencies. It
4529 // is provided in stable builds.
4530 // Callback function for reactor socket activity
4531 typedef int (zloop_reader_fn) (
4532 zloop_t *loop, zsock_t *reader, void *arg);
4533
4534 // Callback function for reactor events (low-level)
4535 typedef int (zloop_fn) (
4536 zloop_t *loop, zmq_pollitem_t *item, void *arg);
4537
4538 // Callback for reactor timer events
4539 typedef int (zloop_timer_fn) (
4540 zloop_t *loop, int timer_id, void *arg);
4541
4542 // Create a new zloop reactor
4543 CZMQ_EXPORT zloop_t *
4544 zloop_new (void);
4545
4546 // Destroy a reactor
4547 CZMQ_EXPORT void
4548 zloop_destroy (zloop_t **self_p);
4549
4550 // Register socket reader with the reactor. When the reader has messages,
4551 // the reactor will call the handler, passing the arg. Returns 0 if OK, -1
4552 // if there was an error. If you register the same socket more than once,
4553 // each instance will invoke its corresponding handler.
4554 CZMQ_EXPORT int
4555 zloop_reader (zloop_t *self, zsock_t *sock, zloop_reader_fn handler, void *arg);
4556
4557 // Cancel a socket reader from the reactor. If multiple readers exist for
4558 // same socket, cancels ALL of them.
4559 CZMQ_EXPORT void
4560 zloop_reader_end (zloop_t *self, zsock_t *sock);
4561
4562 // Configure a registered reader to ignore errors. If you do not set this,
4563 // then readers that have errors are removed from the reactor silently.
4564 CZMQ_EXPORT void
4565 zloop_reader_set_tolerant (zloop_t *self, zsock_t *sock);
4566
4567 // Register low-level libzmq pollitem with the reactor. When the pollitem
4568 // is ready, will call the handler, passing the arg. Returns 0 if OK, -1
4569 // if there was an error. If you register the pollitem more than once, each
4570 // instance will invoke its corresponding handler. A pollitem with
4571 // socket=NULL and fd=0 means 'poll on FD zero'.
4572 CZMQ_EXPORT int
4573 zloop_poller (zloop_t *self, zmq_pollitem_t *item, zloop_fn handler, void *arg);
4574
4575 // Cancel a pollitem from the reactor, specified by socket or FD. If both
4576 // are specified, uses only socket. If multiple poll items exist for same
4577 // socket/FD, cancels ALL of them.
4578 CZMQ_EXPORT void
4579 zloop_poller_end (zloop_t *self, zmq_pollitem_t *item);
4580
4581 // Configure a registered poller to ignore errors. If you do not set this,
4582 // then poller that have errors are removed from the reactor silently.
4583 CZMQ_EXPORT void
4584 zloop_poller_set_tolerant (zloop_t *self, zmq_pollitem_t *item);
4585
4586 // Register a timer that expires after some delay and repeats some number of
4587 // times. At each expiry, will call the handler, passing the arg. To run a
4588 // timer forever, use 0 times. Returns a timer_id that is used to cancel the
4589 // timer in the future. Returns -1 if there was an error.
4590 CZMQ_EXPORT int
4591 zloop_timer (zloop_t *self, size_t delay, size_t times, zloop_timer_fn handler, void *arg);
4592
4593 // Cancel a specific timer identified by a specific timer_id (as returned by
4594 // zloop_timer).
4595 CZMQ_EXPORT int
4596 zloop_timer_end (zloop_t *self, int timer_id);
4597
4598 // Register a ticket timer. Ticket timers are very fast in the case where
4599 // you use a lot of timers (thousands), and frequently remove and add them.
4600 // The main use case is expiry timers for servers that handle many clients,
4601 // and which reset the expiry timer for each message received from a client.
4602 // Whereas normal timers perform poorly as the number of clients grows, the
4603 // cost of ticket timers is constant, no matter the number of clients. You
4604 // must set the ticket delay using zloop_set_ticket_delay before creating a
4605 // ticket. Returns a handle to the timer that you should use in
4606 // zloop_ticket_reset and zloop_ticket_delete.
4607 CZMQ_EXPORT void *
4608 zloop_ticket (zloop_t *self, zloop_timer_fn handler, void *arg);
4609
4610 // Reset a ticket timer, which moves it to the end of the ticket list and
4611 // resets its execution time. This is a very fast operation.
4612 CZMQ_EXPORT void
4613 zloop_ticket_reset (zloop_t *self, void *handle);
4614
4615 // Delete a ticket timer. We do not actually delete the ticket here, as
4616 // other code may still refer to the ticket. We mark as deleted, and remove
4617 // later and safely.
4618 CZMQ_EXPORT void
4619 zloop_ticket_delete (zloop_t *self, void *handle);
4620
4621 // Set the ticket delay, which applies to all tickets. If you lower the
4622 // delay and there are already tickets created, the results are undefined.
4623 CZMQ_EXPORT void
4624 zloop_set_ticket_delay (zloop_t *self, size_t ticket_delay);
4625
4626 // Set hard limit on number of timers allowed. Setting more than a small
4627 // number of timers (10-100) can have a dramatic impact on the performance
4628 // of the reactor. For high-volume cases, use ticket timers. If the hard
4629 // limit is reached, the reactor stops creating new timers and logs an
4630 // error.
4631 CZMQ_EXPORT void
4632 zloop_set_max_timers (zloop_t *self, size_t max_timers);
4633
4634 // Set verbose tracing of reactor on/off. The default verbose setting is
4635 // off (false).
4636 CZMQ_EXPORT void
4637 zloop_set_verbose (zloop_t *self, bool verbose);
4638
4639 // By default the reactor stops if the process receives a SIGINT or SIGTERM
4640 // signal. This makes it impossible to shut-down message based architectures
4641 // like zactors. This method lets you switch off break handling. The default
4642 // nonstop setting is off (false).
4643 CZMQ_EXPORT void
4644 zloop_set_nonstop (zloop_t *self, bool nonstop);
4645
4646 // Start the reactor. Takes control of the thread and returns when the ØMQ
4647 // context is terminated or the process is interrupted, or any event handler
4648 // returns -1. Event handlers may register new sockets and timers, and
4649 // cancel sockets. Returns 0 if interrupted, -1 if canceled by a handler.
4650 CZMQ_EXPORT int
4651 zloop_start (zloop_t *self);
4652
4653 // Self test of this class.
4654 CZMQ_EXPORT void
4655 zloop_test (bool verbose);
4656
4657```
4658Please add '@interface' section in './../src/zloop.c'.
4659
4660This is the class self test code:
4661
4662```c
4663 // Create two PAIR sockets and connect over inproc
4664 zsock_t *output = zsock_new (ZMQ_PAIR);
4665 assert (output);
4666 zsock_bind (output, "inproc://zloop.test");
4667
4668 zsock_t *input = zsock_new (ZMQ_PAIR);
4669 assert (input);
4670 zsock_connect (input, "inproc://zloop.test");
4671
4672 zloop_t *loop = zloop_new ();
4673 assert (loop);
4674 zloop_set_verbose (loop, verbose);
4675
4676 // Create a timer that will be cancelled
4677 int timer_id = zloop_timer (loop, 1000, 1, s_timer_event, NULL);
4678 zloop_timer (loop, 5, 1, s_cancel_timer_event, &timer_id);
4679
4680 // After 20 msecs, send a ping message to output3
4681 zloop_timer (loop, 20, 1, s_timer_event, output);
4682
4683 // Set up some tickets that will never expire
4684 zloop_set_ticket_delay (loop, 10000);
4685 void *ticket1 = zloop_ticket (loop, s_timer_event, NULL);
4686 void *ticket2 = zloop_ticket (loop, s_timer_event, NULL);
4687 void *ticket3 = zloop_ticket (loop, s_timer_event, NULL);
4688
4689 // When we get the ping message, end the reactor
4690 rc = zloop_reader (loop, input, s_socket_event, NULL);
4691 assert (rc == 0);
4692 zloop_reader_set_tolerant (loop, input);
4693 zloop_start (loop);
4694
4695 zloop_ticket_delete (loop, ticket1);
4696 zloop_ticket_delete (loop, ticket2);
4697 zloop_ticket_delete (loop, ticket3);
4698
4699 // Check whether loop properly ignores zsys_interrupted flag
4700 // when asked to
4701 zloop_destroy (&loop);
4702 loop = zloop_new ();
4703
4704 bool timer_event_called = false;
4705 zloop_timer (loop, 1, 1, s_timer_event3, &timer_event_called);
4706
4707 zsys_interrupted = 1;
4708 zloop_start (loop);
4709 // zloop returns immediately without giving any handler a chance to run
4710 assert (!timer_event_called);
4711
4712 zloop_set_nonstop (loop, true);
4713 zloop_start (loop);
4714 // zloop runs the handler which will terminate the loop
4715 assert (timer_event_called);
4716 zsys_interrupted = 0;
4717
4718 // Check if reader removed in timer is not called
4719 zloop_destroy (&loop);
4720 loop = zloop_new ();
4721
4722 bool socket_event_called = false;
4723 zloop_reader (loop, output, s_socket_event1, &socket_event_called);
4724 zloop_timer (loop, 0, 1, s_timer_event5, output);
4725
4726 zstr_send (input, "PING");
4727
4728 zloop_start (loop);
4729 assert (!socket_event_called);
4730
4731 // cleanup
4732 zloop_destroy (&loop);
4733 assert (loop == NULL);
4734
4735 zsock_destroy (&input);
4736 zsock_destroy (&output);
4737
4738 #if defined (__WINDOWS__)
4739 zsys_shutdown();
4740 #endif
4741```
4742
4743#### zmonitor - socket event monitor
4744
4745The zmonitor actor provides an API for obtaining socket events such as
4746connected, listen, disconnected, etc. Socket events are only available
4747for sockets connecting or bound to ipc:// and tcp:// endpoints.
4748
4749This class wraps the ZMQ socket monitor API, see zmq_socket_monitor for
4750details. Works on all versions of libzmq from 3.2 onwards. This class
4751replaces zproxy_v2, and is meant for applications that use the CZMQ v3
4752API (meaning, zsock).
4753
4754This is the class interface:
4755
4756```h
4757 // Create new zmonitor actor instance to monitor a zsock_t socket:
4758 //
4759 // zactor_t *monitor = zactor_new (zmonitor, mysocket);
4760 //
4761 // Destroy zmonitor instance.
4762 //
4763 // zactor_destroy (&monitor);
4764 //
4765 // Enable verbose logging of commands and activity.
4766 //
4767 // zstr_send (monitor, "VERBOSE");
4768 //
4769 // Listen to monitor event type (zero or types, ending in NULL):
4770 // zstr_sendx (monitor, "LISTEN", type, ..., NULL);
4771 //
4772 // Events:
4773 // CONNECTED
4774 // CONNECT_DELAYED
4775 // CONNECT_RETRIED
4776 // LISTENING
4777 // BIND_FAILED
4778 // ACCEPTED
4779 // ACCEPT_FAILED
4780 // CLOSED
4781 // CLOSE_FAILED
4782 // DISCONNECTED
4783 // MONITOR_STOPPED
4784 // ALL
4785 //
4786 // Start monitor; after this, any further LISTEN commands are ignored.
4787 //
4788 // zstr_send (monitor, "START");
4789 // zsock_wait (monitor);
4790 //
4791 // Receive next monitor event:
4792 //
4793 // zmsg_t *msg = zmsg_recv (monitor);
4794 //
4795 // This is the zmonitor constructor as a zactor_fn; the argument can be
4796 // a zactor_t, zsock_t, or libzmq void * socket:
4797 CZMQ_EXPORT void
4798 zmonitor (zsock_t *pipe, void *sock);
4799
4800 // Selftest
4801 CZMQ_EXPORT void
4802 zmonitor_test (bool verbose);
4803```
4804Please add '@interface' section in './../src/zmonitor.c'.
4805
4806This is the class self test code:
4807
4808```c
4809 zsock_t *client = zsock_new (ZMQ_DEALER);
4810 assert (client);
4811 zactor_t *clientmon = zactor_new (zmonitor, client);
4812 assert (clientmon);
4813 if (verbose)
4814 zstr_sendx (clientmon, "VERBOSE", NULL);
4815 zstr_sendx (clientmon, "LISTEN", "LISTENING", "ACCEPTED", NULL);
4816 #if defined (ZMQ_EVENT_HANDSHAKE_SUCCEED)
4817 zstr_sendx (clientmon, "LISTEN", "HANDSHAKE_SUCCEED", NULL);
4818 #endif
4819 zstr_sendx (clientmon, "START", NULL);
4820 zsock_wait (clientmon);
4821
4822 zsock_t *server = zsock_new (ZMQ_DEALER);
4823 assert (server);
4824 zactor_t *servermon = zactor_new (zmonitor, server);
4825 assert (servermon);
4826 if (verbose)
4827 zstr_sendx (servermon, "VERBOSE", NULL);
4828 zstr_sendx (servermon, "LISTEN", "CONNECTED", "DISCONNECTED", NULL);
4829 zstr_sendx (servermon, "START", NULL);
4830 zsock_wait (servermon);
4831
4832 // Allow a brief time for the message to get there...
4833 zmq_poll (NULL, 0, 200);
4834
4835 // Check client is now listening
4836 int port_nbr = zsock_bind (client, "tcp://127.0.0.1:*");
4837 assert (port_nbr != -1);
4838 s_assert_event (clientmon, "LISTENING");
4839
4840 // Check server connected to client
4841 zsock_connect (server, "tcp://127.0.0.1:%d", port_nbr);
4842 s_assert_event (servermon, "CONNECTED");
4843
4844 // Check client accepted connection
4845 s_assert_event (clientmon, "ACCEPTED");
4846 #if defined (ZMQ_EVENT_HANDSHAKE_SUCCEED)
4847 s_assert_event (clientmon, "HANDSHAKE_SUCCEED");
4848 #endif
4849
4850 zactor_destroy (&clientmon);
4851 zactor_destroy (&servermon);
4852 zsock_destroy (&client);
4853 zsock_destroy (&server);
4854 #endif
4855
4856 #if defined (__WINDOWS__)
4857 zsys_shutdown();
4858 #endif
4859```
4860
4861#### zmsg - working with multipart messages
4862
4863The zmsg class provides methods to send and receive multipart messages
4864across ØMQ sockets. This class provides a list-like container interface,
4865with methods to work with the overall container. zmsg_t messages are
4866composed of zero or more zframe_t frames.
4867
4868Please add '@discuss' section in './../src/zmsg.c'.
4869
4870This is the class interface:
4871
4872```h
4873 // This is a stable class, and may not change except for emergencies. It
4874 // is provided in stable builds.
4875 // This class has draft methods, which may change over time. They are not
4876 // in stable releases, by default. Use --enable-drafts to enable.
4877 // Create a new empty message object
4878 CZMQ_EXPORT zmsg_t *
4879 zmsg_new (void);
4880
4881 // Receive message from socket, returns zmsg_t object or NULL if the recv
4882 // was interrupted. Does a blocking recv. If you want to not block then use
4883 // the zloop class or zmsg_recv_nowait or zmq_poll to check for socket input
4884 // before receiving.
4885 CZMQ_EXPORT zmsg_t *
4886 zmsg_recv (void *source);
4887
4888 // Load/append an open file into new message, return the message.
4889 // Returns NULL if the message could not be loaded.
4890 CZMQ_EXPORT zmsg_t *
4891 zmsg_load (FILE *file);
4892
4893 // Decodes a serialized message frame created by zmsg_encode () and returns
4894 // a new zmsg_t object. Returns NULL if the frame was badly formatted or
4895 // there was insufficient memory to work.
4896 CZMQ_EXPORT zmsg_t *
4897 zmsg_decode (zframe_t *frame);
4898
4899 // Generate a signal message encoding the given status. A signal is a short
4900 // message carrying a 1-byte success/failure code (by convention, 0 means
4901 // OK). Signals are encoded to be distinguishable from "normal" messages.
4902 CZMQ_EXPORT zmsg_t *
4903 zmsg_new_signal (byte status);
4904
4905 // Destroy a message object and all frames it contains
4906 CZMQ_EXPORT void
4907 zmsg_destroy (zmsg_t **self_p);
4908
4909 // Send message to destination socket, and destroy the message after sending
4910 // it successfully. If the message has no frames, sends nothing but destroys
4911 // the message anyhow. Nullifies the caller's reference to the message (as
4912 // it is a destructor).
4913 CZMQ_EXPORT int
4914 zmsg_send (zmsg_t **self_p, void *dest);
4915
4916 // Send message to destination socket as part of a multipart sequence, and
4917 // destroy the message after sending it successfully. Note that after a
4918 // zmsg_sendm, you must call zmsg_send or another method that sends a final
4919 // message part. If the message has no frames, sends nothing but destroys
4920 // the message anyhow. Nullifies the caller's reference to the message (as
4921 // it is a destructor).
4922 CZMQ_EXPORT int
4923 zmsg_sendm (zmsg_t **self_p, void *dest);
4924
4925 // Return size of message, i.e. number of frames (0 or more).
4926 CZMQ_EXPORT size_t
4927 zmsg_size (zmsg_t *self);
4928
4929 // Return total size of all frames in message.
4930 CZMQ_EXPORT size_t
4931 zmsg_content_size (zmsg_t *self);
4932
4933 // Push frame to the front of the message, i.e. before all other frames.
4934 // Message takes ownership of frame, will destroy it when message is sent.
4935 // Returns 0 on success, -1 on error. Deprecates zmsg_push, which did not
4936 // nullify the caller's frame reference.
4937 CZMQ_EXPORT int
4938 zmsg_prepend (zmsg_t *self, zframe_t **frame_p);
4939
4940 // Add frame to the end of the message, i.e. after all other frames.
4941 // Message takes ownership of frame, will destroy it when message is sent.
4942 // Returns 0 on success. Deprecates zmsg_add, which did not nullify the
4943 // caller's frame reference.
4944 CZMQ_EXPORT int
4945 zmsg_append (zmsg_t *self, zframe_t **frame_p);
4946
4947 // Remove first frame from message, if any. Returns frame, or NULL.
4948 // Caller owns return value and must destroy it when done.
4949 CZMQ_EXPORT zframe_t *
4950 zmsg_pop (zmsg_t *self);
4951
4952 // Push block of memory to front of message, as a new frame.
4953 // Returns 0 on success, -1 on error.
4954 CZMQ_EXPORT int
4955 zmsg_pushmem (zmsg_t *self, const void *data, size_t size);
4956
4957 // Add block of memory to the end of the message, as a new frame.
4958 // Returns 0 on success, -1 on error.
4959 CZMQ_EXPORT int
4960 zmsg_addmem (zmsg_t *self, const void *data, size_t size);
4961
4962 // Push string as new frame to front of message.
4963 // Returns 0 on success, -1 on error.
4964 CZMQ_EXPORT int
4965 zmsg_pushstr (zmsg_t *self, const char *string);
4966
4967 // Push string as new frame to end of message.
4968 // Returns 0 on success, -1 on error.
4969 CZMQ_EXPORT int
4970 zmsg_addstr (zmsg_t *self, const char *string);
4971
4972 // Push formatted string as new frame to front of message.
4973 // Returns 0 on success, -1 on error.
4974 CZMQ_EXPORT int
4975 zmsg_pushstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2);
4976
4977 // Push formatted string as new frame to end of message.
4978 // Returns 0 on success, -1 on error.
4979 CZMQ_EXPORT int
4980 zmsg_addstrf (zmsg_t *self, const char *format, ...) CHECK_PRINTF (2);
4981
4982 // Pop frame off front of message, return as fresh string. If there were
4983 // no more frames in the message, returns NULL.
4984 // Caller owns return value and must destroy it when done.
4985 CZMQ_EXPORT char *
4986 zmsg_popstr (zmsg_t *self);
4987
4988 // Push encoded message as a new frame. Message takes ownership of
4989 // submessage, so the original is destroyed in this call. Returns 0 on
4990 // success, -1 on error.
4991 CZMQ_EXPORT int
4992 zmsg_addmsg (zmsg_t *self, zmsg_t **msg_p);
4993
4994 // Remove first submessage from message, if any. Returns zmsg_t, or NULL if
4995 // decoding was not successful.
4996 // Caller owns return value and must destroy it when done.
4997 CZMQ_EXPORT zmsg_t *
4998 zmsg_popmsg (zmsg_t *self);
4999
5000 // Remove specified frame from list, if present. Does not destroy frame.
5001 CZMQ_EXPORT void
5002 zmsg_remove (zmsg_t *self, zframe_t *frame);
5003
5004 // Set cursor to first frame in message. Returns frame, or NULL, if the
5005 // message is empty. Use this to navigate the frames as a list.
5006 CZMQ_EXPORT zframe_t *
5007 zmsg_first (zmsg_t *self);
5008
5009 // Return the next frame. If there are no more frames, returns NULL. To move
5010 // to the first frame call zmsg_first(). Advances the cursor.
5011 CZMQ_EXPORT zframe_t *
5012 zmsg_next (zmsg_t *self);
5013
5014 // Return the last frame. If there are no frames, returns NULL.
5015 CZMQ_EXPORT zframe_t *
5016 zmsg_last (zmsg_t *self);
5017
5018 // Save message to an open file, return 0 if OK, else -1. The message is
5019 // saved as a series of frames, each with length and data. Note that the
5020 // file is NOT guaranteed to be portable between operating systems, not
5021 // versions of CZMQ. The file format is at present undocumented and liable
5022 // to arbitrary change.
5023 CZMQ_EXPORT int
5024 zmsg_save (zmsg_t *self, FILE *file);
5025
5026 // Serialize multipart message to a single message frame. Use this method
5027 // to send structured messages across transports that do not support
5028 // multipart data. Allocates and returns a new frame containing the
5029 // serialized message. To decode a serialized message frame, use
5030 // zmsg_decode ().
5031 // Caller owns return value and must destroy it when done.
5032 CZMQ_EXPORT zframe_t *
5033 zmsg_encode (zmsg_t *self);
5034
5035 // Create copy of message, as new message object. Returns a fresh zmsg_t
5036 // object. If message is null, or memory was exhausted, returns null.
5037 // Caller owns return value and must destroy it when done.
5038 CZMQ_EXPORT zmsg_t *
5039 zmsg_dup (zmsg_t *self);
5040
5041 // Send message to zsys log sink (may be stdout, or system facility as
5042 // configured by zsys_set_logstream).
5043 CZMQ_EXPORT void
5044 zmsg_print (zmsg_t *self);
5045
5046 // Return true if the two messages have the same number of frames and each
5047 // frame in the first message is identical to the corresponding frame in the
5048 // other message. As with zframe_eq, return false if either message is NULL.
5049 CZMQ_EXPORT bool
5050 zmsg_eq (zmsg_t *self, zmsg_t *other);
5051
5052 // Return signal value, 0 or greater, if message is a signal, -1 if not.
5053 CZMQ_EXPORT int
5054 zmsg_signal (zmsg_t *self);
5055
5056 // Probe the supplied object, and report if it looks like a zmsg_t.
5057 CZMQ_EXPORT bool
5058 zmsg_is (void *self);
5059
5060 // Self test of this class.
5061 CZMQ_EXPORT void
5062 zmsg_test (bool verbose);
5063
5064 #ifdef CZMQ_BUILD_DRAFT_API
5065 // *** Draft method, for development use, may change without warning ***
5066 // Return message routing ID, if the message came from a ZMQ_SERVER socket.
5067 // Else returns zero.
5068 CZMQ_EXPORT uint32_t
5069 zmsg_routing_id (zmsg_t *self);
5070
5071 // *** Draft method, for development use, may change without warning ***
5072 // Set routing ID on message. This is used if/when the message is sent to a
5073 // ZMQ_SERVER socket.
5074 CZMQ_EXPORT void
5075 zmsg_set_routing_id (zmsg_t *self, uint32_t routing_id);
5076
5077 #endif // CZMQ_BUILD_DRAFT_API
5078```
5079Please add '@interface' section in './../src/zmsg.c'.
5080
5081This is the class self test code:
5082
5083```c
5084 // Create two PAIR sockets and connect over inproc
5085 zsock_t *output = zsock_new_pair ("@inproc://zmsg.test");
5086 assert (output);
5087 zsock_t *input = zsock_new_pair (">inproc://zmsg.test");
5088 assert (input);
5089
5090 // Test send and receive of single-frame message
5091 zmsg_t *msg = zmsg_new ();
5092 assert (msg);
5093 zframe_t *frame = zframe_new ("Hello", 5);
5094 assert (frame);
5095 zmsg_prepend (msg, &frame);
5096 assert (zmsg_size (msg) == 1);
5097 assert (zmsg_content_size (msg) == 5);
5098 rc = zmsg_send (&msg, output);
5099 assert (msg == NULL);
5100 assert (rc == 0);
5101
5102 msg = zmsg_recv (input);
5103 assert (msg);
5104 assert (zmsg_size (msg) == 1);
5105 assert (zmsg_content_size (msg) == 5);
5106 zmsg_destroy (&msg);
5107
5108 // Test send and receive of multi-frame message
5109 msg = zmsg_new ();
5110 assert (msg);
5111 rc = zmsg_addmem (msg, "Frame0", 6);
5112 assert (rc == 0);
5113 rc = zmsg_addmem (msg, "Frame1", 6);
5114 assert (rc == 0);
5115 rc = zmsg_addmem (msg, "Frame2", 6);
5116 assert (rc == 0);
5117 rc = zmsg_addmem (msg, "Frame3", 6);
5118 assert (rc == 0);
5119 rc = zmsg_addmem (msg, "Frame4", 6);
5120 assert (rc == 0);
5121 rc = zmsg_addmem (msg, "Frame5", 6);
5122 assert (rc == 0);
5123 rc = zmsg_addmem (msg, "Frame6", 6);
5124 assert (rc == 0);
5125 rc = zmsg_addmem (msg, "Frame7", 6);
5126 assert (rc == 0);
5127 rc = zmsg_addmem (msg, "Frame8", 6);
5128 assert (rc == 0);
5129 rc = zmsg_addmem (msg, "Frame9", 6);
5130 assert (rc == 0);
5131 zmsg_t *copy = zmsg_dup (msg);
5132 assert (copy);
5133 rc = zmsg_send (©, output);
5134 assert (rc == 0);
5135 rc = zmsg_send (&msg, output);
5136 assert (rc == 0);
5137
5138 copy = zmsg_recv (input);
5139 assert (copy);
5140 assert (zmsg_size (copy) == 10);
5141 assert (zmsg_content_size (copy) == 60);
5142 zmsg_destroy (©);
5143
5144 msg = zmsg_recv (input);
5145 assert (msg);
5146 assert (zmsg_size (msg) == 10);
5147 assert (zmsg_content_size (msg) == 60);
5148
5149 // Save to a file, read back
5150 FILE *file = fopen ("zmsg.test", "w");
5151 assert (file);
5152 rc = zmsg_save (msg, file);
5153 assert (rc == 0);
5154 fclose (file);
5155
5156 file = fopen ("zmsg.test", "r");
5157 rc = zmsg_save (msg, file);
5158 assert (rc == -1);
5159 fclose (file);
5160 zmsg_destroy (&msg);
5161
5162 file = fopen ("zmsg.test", "r");
5163 msg = zmsg_load (file);
5164 assert (msg);
5165 fclose (file);
5166 remove ("zmsg.test");
5167 assert (zmsg_size (msg) == 10);
5168 assert (zmsg_content_size (msg) == 60);
5169
5170 // Remove all frames except first and last
5171 int frame_nbr;
5172 for (frame_nbr = 0; frame_nbr < 8; frame_nbr++) {
5173 zmsg_first (msg);
5174 frame = zmsg_next (msg);
5175 zmsg_remove (msg, frame);
5176 zframe_destroy (&frame);
5177 }
5178 // Test message frame manipulation
5179 assert (zmsg_size (msg) == 2);
5180 frame = zmsg_last (msg);
5181 assert (zframe_streq (frame, "Frame9"));
5182 assert (zmsg_content_size (msg) == 12);
5183 frame = zframe_new ("Address", 7);
5184 assert (frame);
5185 zmsg_prepend (msg, &frame);
5186 assert (zmsg_size (msg) == 3);
5187 rc = zmsg_addstr (msg, "Body");
5188 assert (rc == 0);
5189 assert (zmsg_size (msg) == 4);
5190 frame = zmsg_pop (msg);
5191 zframe_destroy (&frame);
5192 assert (zmsg_size (msg) == 3);
5193 char *body = zmsg_popstr (msg);
5194 assert (streq (body, "Frame0"));
5195 free (body);
5196 zmsg_destroy (&msg);
5197
5198 // Test encoding/decoding
5199 msg = zmsg_new ();
5200 assert (msg);
5201 byte *blank = (byte *) zmalloc (100000);
5202 assert (blank);
5203 rc = zmsg_addmem (msg, blank, 0);
5204 assert (rc == 0);
5205 rc = zmsg_addmem (msg, blank, 1);
5206 assert (rc == 0);
5207 rc = zmsg_addmem (msg, blank, 253);
5208 assert (rc == 0);
5209 rc = zmsg_addmem (msg, blank, 254);
5210 assert (rc == 0);
5211 rc = zmsg_addmem (msg, blank, 255);
5212 assert (rc == 0);
5213 rc = zmsg_addmem (msg, blank, 256);
5214 assert (rc == 0);
5215 rc = zmsg_addmem (msg, blank, 65535);
5216 assert (rc == 0);
5217 rc = zmsg_addmem (msg, blank, 65536);
5218 assert (rc == 0);
5219 rc = zmsg_addmem (msg, blank, 65537);
5220 assert (rc == 0);
5221 free (blank);
5222 assert (zmsg_size (msg) == 9);
5223 frame = zmsg_encode (msg);
5224 zmsg_destroy (&msg);
5225 msg = zmsg_decode (frame);
5226 assert (msg);
5227 zmsg_destroy (&msg);
5228 zframe_destroy (&frame);
5229
5230 // Test submessages
5231 msg = zmsg_new ();
5232 assert (msg);
5233 zmsg_t *submsg = zmsg_new ();
5234 zmsg_pushstr (msg, "matr");
5235 zmsg_pushstr (submsg, "joska");
5236 rc = zmsg_addmsg (msg, &submsg);
5237 assert (rc == 0);
5238 assert (submsg == NULL);
5239 submsg = zmsg_popmsg (msg);
5240 assert (submsg == NULL); // string "matr" is not encoded zmsg_t, so was discarded
5241 submsg = zmsg_popmsg (msg);
5242 assert (submsg);
5243 body = zmsg_popstr (submsg);
5244 assert (streq (body, "joska"));
5245 free (body);
5246 zmsg_destroy (&submsg);
5247 frame = zmsg_pop (msg);
5248 assert (frame == NULL);
5249 zmsg_destroy (&msg);
5250
5251 // Test comparison of two messages
5252 msg = zmsg_new ();
5253 zmsg_addstr (msg, "One");
5254 zmsg_addstr (msg, "Two");
5255 zmsg_addstr (msg, "Three");
5256 zmsg_t *msg_other = zmsg_new ();
5257 zmsg_addstr (msg_other, "One");
5258 zmsg_addstr (msg_other, "Two");
5259 zmsg_addstr (msg_other, "One-Hundred");
5260 zmsg_t *msg_dup = zmsg_dup (msg);
5261 zmsg_t *empty_msg = zmsg_new ();
5262 zmsg_t *empty_msg_2 = zmsg_new ();
5263 assert (zmsg_eq (msg, msg_dup));
5264 assert (!zmsg_eq (msg, msg_other));
5265 assert (zmsg_eq (empty_msg, empty_msg_2));
5266 assert (!zmsg_eq (msg, NULL));
5267 assert (!zmsg_eq (NULL, empty_msg));
5268 assert (!zmsg_eq (NULL, NULL));
5269 zmsg_destroy (&msg);
5270 zmsg_destroy (&msg_other);
5271 zmsg_destroy (&msg_dup);
5272 zmsg_destroy (&empty_msg);
5273 zmsg_destroy (&empty_msg_2);
5274
5275 // Test signal messages
5276 msg = zmsg_new_signal (0);
5277 assert (zmsg_signal (msg) == 0);
5278 zmsg_destroy (&msg);
5279 msg = zmsg_new_signal (-1);
5280 assert (zmsg_signal (msg) == 255);
5281 zmsg_destroy (&msg);
5282
5283 // Now try methods on an empty message
5284 msg = zmsg_new ();
5285 assert (msg);
5286 assert (zmsg_size (msg) == 0);
5287 assert (zmsg_unwrap (msg) == NULL);
5288 assert (zmsg_first (msg) == NULL);
5289 assert (zmsg_last (msg) == NULL);
5290 assert (zmsg_next (msg) == NULL);
5291 assert (zmsg_pop (msg) == NULL);
5292 // Sending an empty message is valid and destroys the message
5293 assert (zmsg_send (&msg, output) == 0);
5294 assert (!msg);
5295
5296 zsock_destroy (&input);
5297 zsock_destroy (&output);
5298
5299 #if defined (ZMQ_SERVER)
5300 // Create server and client sockets and connect over inproc
5301 zsock_t *server = zsock_new_server ("inproc://zmsg-test-routing");
5302 assert (server);
5303 zsock_t *client = zsock_new_client ("inproc://zmsg-test-routing");
5304 assert (client);
5305
5306 // Send request from client to server
5307 zmsg_t *request = zmsg_new ();
5308 assert (request);
5309 zmsg_addstr (request, "Hello");
5310 rc = zmsg_send (&request, client);
5311 assert (rc == 0);
5312 assert (!request);
5313
5314 // Read request and send reply
5315 request = zmsg_recv (server);
5316 assert (request);
5317 char *string = zmsg_popstr (request);
5318 assert (streq (string, "Hello"));
5319 assert (zmsg_routing_id (request));
5320 zstr_free (&string);
5321
5322 zmsg_t *reply = zmsg_new ();
5323 assert (reply);
5324 zmsg_addstr (reply, "World");
5325 zmsg_set_routing_id (reply, zmsg_routing_id (request));
5326 rc = zmsg_send (&reply, server);
5327 assert (rc == 0);
5328 zmsg_destroy (&request);
5329
5330 // Read reply
5331 reply = zmsg_recv (client);
5332 string = zmsg_popstr (reply);
5333 assert (streq (string, "World"));
5334 assert (zmsg_routing_id (reply) == 0);
5335 zmsg_destroy (&reply);
5336 zstr_free (&string);
5337
5338 // Client and server disallow multipart
5339 msg = zmsg_new ();
5340 zmsg_addstr (msg, "One");
5341 zmsg_addstr (msg, "Two");
5342 rc = zmsg_send (&msg, client);
5343 assert (rc == -1);
5344 assert (zmsg_size (msg) == 2);
5345 rc = zmsg_send (&msg, server);
5346 assert (rc == -1);
5347 assert (zmsg_size (msg) == 2);
5348 zmsg_destroy (&msg);
5349
5350 zsock_destroy (&client);
5351 zsock_destroy (&server);
5352 #endif
5353
5354 // Test message length calculation after removal
5355 msg = zmsg_new ();
5356 zmsg_addstr (msg, "One");
5357 zmsg_addstr (msg, "Two");
5358 size_t size_before = zmsg_content_size (msg);
5359 frame = zframe_new ("Three", strlen ("Three"));
5360 assert (frame);
5361 zmsg_remove (msg, frame);
5362 size_t size_after = zmsg_content_size (msg);
5363 assert (size_before == size_after);
5364 zframe_destroy (&frame);
5365 zmsg_destroy (&msg);
5366
5367 #if defined (__WINDOWS__)
5368 zsys_shutdown();
5369 #endif
5370
5371```
5372
5373#### zpoller - trivial socket poller class
5374
5375The zpoller class provides a minimalist interface to ZeroMQ's zmq_poll
5376API, for the very common case of reading from a number of sockets.
5377It does not provide polling for output, nor polling on file handles.
5378If you need either of these, use the zmq_poll API directly.
5379
5380The class implements the poller using the zmq_poller API if that exists,
5381else does the work itself.
5382
5383This is the class interface:
5384
5385```h
5386 // This is a stable class, and may not change except for emergencies. It
5387 // is provided in stable builds.
5388 // Create new poller, specifying zero or more readers. The list of
5389 // readers ends in a NULL. Each reader can be a zsock_t instance, a
5390 // zactor_t instance, a libzmq socket (void *), or a file handle.
5391 CZMQ_EXPORT zpoller_t *
5392 zpoller_new (void *reader, ...);
5393
5394 // Destroy a poller
5395 CZMQ_EXPORT void
5396 zpoller_destroy (zpoller_t **self_p);
5397
5398 // Add a reader to be polled. Returns 0 if OK, -1 on failure. The reader may
5399 // be a libzmq void * socket, a zsock_t instance, or a zactor_t instance.
5400 CZMQ_EXPORT int
5401 zpoller_add (zpoller_t *self, void *reader);
5402
5403 // Remove a reader from the poller; returns 0 if OK, -1 on failure. The reader
5404 // must have been passed during construction, or in an zpoller_add () call.
5405 CZMQ_EXPORT int
5406 zpoller_remove (zpoller_t *self, void *reader);
5407
5408 // By default the poller stops if the process receives a SIGINT or SIGTERM
5409 // signal. This makes it impossible to shut-down message based architectures
5410 // like zactors. This method lets you switch off break handling. The default
5411 // nonstop setting is off (false).
5412 CZMQ_EXPORT void
5413 zpoller_set_nonstop (zpoller_t *self, bool nonstop);
5414
5415 // Poll the registered readers for I/O, return first reader that has input.
5416 // The reader will be a libzmq void * socket, or a zsock_t or zactor_t
5417 // instance as specified in zpoller_new/zpoller_add. The timeout should be
5418 // zero or greater, or -1 to wait indefinitely. Socket priority is defined
5419 // by their order in the poll list. If you need a balanced poll, use the low
5420 // level zmq_poll method directly. If the poll call was interrupted (SIGINT),
5421 // or the ZMQ context was destroyed, or the timeout expired, returns NULL.
5422 // You can test the actual exit condition by calling zpoller_expired () and
5423 // zpoller_terminated (). The timeout is in msec.
5424 CZMQ_EXPORT void *
5425 zpoller_wait (zpoller_t *self, int timeout);
5426
5427 // Return true if the last zpoller_wait () call ended because the timeout
5428 // expired, without any error.
5429 CZMQ_EXPORT bool
5430 zpoller_expired (zpoller_t *self);
5431
5432 // Return true if the last zpoller_wait () call ended because the process
5433 // was interrupted, or the parent context was destroyed.
5434 CZMQ_EXPORT bool
5435 zpoller_terminated (zpoller_t *self);
5436
5437 // Self test of this class.
5438 CZMQ_EXPORT void
5439 zpoller_test (bool verbose);
5440
5441```
5442Please add '@interface' section in './../src/zpoller.c'.
5443
5444This is the class self test code:
5445
5446```c
5447 // Create a few sockets
5448 zsock_t *vent = zsock_new (ZMQ_PUSH);
5449 assert (vent);
5450 int port_nbr = zsock_bind (vent, "tcp://127.0.0.1:*");
5451 assert (port_nbr != -1);
5452 zsock_t *sink = zsock_new (ZMQ_PULL);
5453 assert (sink);
5454 int rc = zsock_connect (sink, "tcp://127.0.0.1:%d", port_nbr);
5455 assert (rc != -1);
5456 zsock_t *bowl = zsock_new (ZMQ_PULL);
5457 assert (bowl);
5458 zsock_t *dish = zsock_new (ZMQ_PULL);
5459 assert (dish);
5460
5461 // Set up poller
5462 zpoller_t *poller = zpoller_new (bowl, dish, NULL);
5463 assert (poller);
5464
5465 // Add a reader to the existing poller
5466 rc = zpoller_add (poller, sink);
5467 assert (rc == 0);
5468
5469 zstr_send (vent, "Hello, World");
5470
5471 // We expect a message only on the sink
5472 zsock_t *which = (zsock_t *) zpoller_wait (poller, -1);
5473 assert (which == sink);
5474 assert (zpoller_expired (poller) == false);
5475 assert (zpoller_terminated (poller) == false);
5476 char *message = zstr_recv (which);
5477 assert (streq (message, "Hello, World"));
5478 zstr_free (&message);
5479
5480 // Stop polling reader
5481 rc = zpoller_remove (poller, sink);
5482 assert (rc == 0);
5483
5484 // Removing a non-existent reader shall fail
5485 rc = zpoller_remove (poller, sink);
5486 assert (rc == -1);
5487 assert (errno == EINVAL);
5488
5489 // Check we can poll an FD
5490 rc = zsock_connect (bowl, "tcp://127.0.0.1:%d", port_nbr);
5491 assert (rc != -1);
5492 SOCKET fd = zsock_fd (bowl);
5493 rc = zpoller_add (poller, (void *) &fd);
5494 assert (rc != -1);
5495 zstr_send (vent, "Hello again, world");
5496 assert (zpoller_wait (poller, 500) == &fd);
5497
5498 // Check zpoller_set_nonstop ()
5499 zsys_interrupted = 1;
5500 zpoller_wait (poller, 0);
5501 assert (zpoller_terminated (poller));
5502 zpoller_set_nonstop (poller, true);
5503 zpoller_wait (poller, 0);
5504 assert (!zpoller_terminated (poller));
5505 zsys_interrupted = 0;
5506
5507 zpoller_destroy (&poller);
5508 zsock_destroy (&vent);
5509 zsock_destroy (&sink);
5510 zsock_destroy (&bowl);
5511 zsock_destroy (&dish);
5512
5513 #ifdef ZMQ_SERVER
5514 // Check thread safe sockets
5515 zpoller_destroy (&poller);
5516 zsock_t *client = zsock_new (ZMQ_CLIENT);
5517 assert (client);
5518 zsock_t *server = zsock_new (ZMQ_SERVER);
5519 assert (server);
5520 poller = zpoller_new (client, server, NULL);
5521 assert (poller);
5522 port_nbr = zsock_bind (server, "tcp://127.0.0.1:*");
5523 assert (port_nbr != -1);
5524 rc = zsock_connect (client, "tcp://127.0.0.1:%d", port_nbr);
5525 assert (rc != -1);
5526
5527 zstr_send (client, "Hello, World");
5528
5529 // We expect a message only on the server
5530 which = (zsock_t *) zpoller_wait (poller, -1);
5531 assert (which == server);
5532 assert (zpoller_expired (poller) == false);
5533 assert (zpoller_terminated (poller) == false);
5534 message = zstr_recv (which);
5535 assert (streq (message, "Hello, World"));
5536 zstr_free (&message);
5537
5538 zpoller_destroy (&poller);
5539 zsock_destroy (&client);
5540 zsock_destroy (&server);
5541 #endif
5542
5543 #if defined (__WINDOWS__)
5544 zsys_shutdown();
5545 #endif
5546```
5547
5548#### zproc - process configuration and status
5549
5550zproc - process configuration and status, plus unix pipes on steroids
5551
5552WARNING: zproc class have several limitations atm
5553 * is tested on zmq4 on Linux and OSX.
5554 * does not work on Windows, where you get empty stubs for most of the methods
5555 * does not work on libzmq3 and libzmq2. We have experienced stalls and timeouts
5556 when running tests against such old version
5557
5558Note: zproc is not yet stable, so there are no guarantees regarding API stability.
5559Some methods can have weird semantics or strange API.
5560
5561Class zproc run an external process and to use ZeroMQ sockets to communicate
5562with it. In other words standard input and outputs MAY be connected with appropriate
5563zeromq socket and data flow is managed by zproc itself. This makes zproc
5564the best in class way how to run and manage sub processes.
5565
5566Data are sent and received as zframes (zframe_t), so zproc does not try to interpret
5567content of the messages in any way. See test example on how to use it.
5568
5569 +----------------------------------------+
5570 | /bin/cat cat /etc/passwd |
5571 | stdin | stdout | stderr |
5572 |------||--------||---------------||-----|
5573 | fd1 fd2 fd3 |
5574 | ^ v v |
5575 |zmq://stdin |zmq://stdout |zmq://stderr |
5576 | [zproc supervisor] |
5577 +----------------------------------------+
5578
5579 ----------> zeromq magic here <-----------
5580
5581 +----------------------------------------+
5582 |zmq://stdin |zmq://stdout |zmq://stderr |
5583 | |
5584 | consumer |
5585 | |
5586 | |
5587 +----------------------------------------+
5588
5589
5590Please add '@discuss' section in './../src/zproc.c'.
5591
5592This is the class interface:
5593
5594```h
5595 // This is a draft class, and may change without notice. It is disabled in
5596 // stable builds by default. If you use this in applications, please ask
5597 // for it to be pushed to stable state. Use --enable-drafts to enable.
5598 #ifdef CZMQ_BUILD_DRAFT_API
5599 // *** Draft method, for development use, may change without warning ***
5600 // Create a new zproc.
5601 // NOTE: On Windows and with libzmq3 and libzmq2 this function
5602 // returns NULL. Code needs to be ported there.
5603 CZMQ_EXPORT zproc_t *
5604 zproc_new (void);
5605
5606 // *** Draft method, for development use, may change without warning ***
5607 // Destroy zproc, wait until process ends.
5608 CZMQ_EXPORT void
5609 zproc_destroy (zproc_t **self_p);
5610
5611 // *** Draft method, for development use, may change without warning ***
5612 // Setup the command line arguments, the first item must be an (absolute) filename
5613 // to run.
5614 CZMQ_EXPORT void
5615 zproc_set_args (zproc_t *self, zlistx_t *args);
5616
5617 // *** Draft method, for development use, may change without warning ***
5618 // Setup the environment variables for the process.
5619 CZMQ_EXPORT void
5620 zproc_set_env (zproc_t *self, zhashx_t *args);
5621
5622 // *** Draft method, for development use, may change without warning ***
5623 // Connects process stdin with a readable ('>', connect) zeromq socket. If
5624 // socket argument is NULL, zproc creates own managed pair of inproc
5625 // sockets. The writable one is then accessbile via zproc_stdin method.
5626 CZMQ_EXPORT void
5627 zproc_set_stdin (zproc_t *self, void *socket);
5628
5629 // *** Draft method, for development use, may change without warning ***
5630 // Connects process stdout with a writable ('@', bind) zeromq socket. If
5631 // socket argument is NULL, zproc creates own managed pair of inproc
5632 // sockets. The readable one is then accessbile via zproc_stdout method.
5633 CZMQ_EXPORT void
5634 zproc_set_stdout (zproc_t *self, void *socket);
5635
5636 // *** Draft method, for development use, may change without warning ***
5637 // Connects process stderr with a writable ('@', bind) zeromq socket. If
5638 // socket argument is NULL, zproc creates own managed pair of inproc
5639 // sockets. The readable one is then accessbile via zproc_stderr method.
5640 CZMQ_EXPORT void
5641 zproc_set_stderr (zproc_t *self, void *socket);
5642
5643 // *** Draft method, for development use, may change without warning ***
5644 // Return subprocess stdin writable socket. NULL for
5645 // not initialized or external sockets.
5646 CZMQ_EXPORT void *
5647 zproc_stdin (zproc_t *self);
5648
5649 // *** Draft method, for development use, may change without warning ***
5650 // Return subprocess stdout readable socket. NULL for
5651 // not initialized or external sockets.
5652 CZMQ_EXPORT void *
5653 zproc_stdout (zproc_t *self);
5654
5655 // *** Draft method, for development use, may change without warning ***
5656 // Return subprocess stderr readable socket. NULL for
5657 // not initialized or external sockets.
5658 CZMQ_EXPORT void *
5659 zproc_stderr (zproc_t *self);
5660
5661 // *** Draft method, for development use, may change without warning ***
5662 // Starts the process.
5663 CZMQ_EXPORT int
5664 zproc_run (zproc_t *self);
5665
5666 // *** Draft method, for development use, may change without warning ***
5667 // process exit code
5668 CZMQ_EXPORT int
5669 zproc_returncode (zproc_t *self);
5670
5671 // *** Draft method, for development use, may change without warning ***
5672 // PID of the process
5673 CZMQ_EXPORT int
5674 zproc_pid (zproc_t *self);
5675
5676 // *** Draft method, for development use, may change without warning ***
5677 // return true if process is running, false if not yet started or finished
5678 CZMQ_EXPORT bool
5679 zproc_running (zproc_t *self);
5680
5681 // *** Draft method, for development use, may change without warning ***
5682 // wait or poll process status, return return code
5683 CZMQ_EXPORT int
5684 zproc_wait (zproc_t *self, bool hang);
5685
5686 // *** Draft method, for development use, may change without warning ***
5687 // return internal actor, usefull for the polling if process died
5688 CZMQ_EXPORT void *
5689 zproc_actor (zproc_t *self);
5690
5691 // *** Draft method, for development use, may change without warning ***
5692 // send a signal to the subprocess
5693 CZMQ_EXPORT void
5694 zproc_kill (zproc_t *self, int signal);
5695
5696 // *** Draft method, for development use, may change without warning ***
5697 // set verbose mode
5698 CZMQ_EXPORT void
5699 zproc_set_verbose (zproc_t *self, bool verbose);
5700
5701 // *** Draft method, for development use, may change without warning ***
5702 // Returns CZMQ version as a single 6-digit integer encoding the major
5703 // version (x 10000), the minor version (x 100) and the patch.
5704 CZMQ_EXPORT int
5705 zproc_czmq_version (void);
5706
5707 // *** Draft method, for development use, may change without warning ***
5708 // Returns true if the process received a SIGINT or SIGTERM signal.
5709 // It is good practice to use this method to exit any infinite loop
5710 // processing messages.
5711 CZMQ_EXPORT bool
5712 zproc_interrupted (void);
5713
5714 // *** Draft method, for development use, may change without warning ***
5715 // Returns true if the underlying libzmq supports CURVE security.
5716 CZMQ_EXPORT bool
5717 zproc_has_curve (void);
5718
5719 // *** Draft method, for development use, may change without warning ***
5720 // Return current host name, for use in public tcp:// endpoints.
5721 // If the host name is not resolvable, returns NULL.
5722 // Caller owns return value and must destroy it when done.
5723 CZMQ_EXPORT char *
5724 zproc_hostname (void);
5725
5726 // *** Draft method, for development use, may change without warning ***
5727 // Move the current process into the background. The precise effect
5728 // depends on the operating system. On POSIX boxes, moves to a specified
5729 // working directory (if specified), closes all file handles, reopens
5730 // stdin, stdout, and stderr to the null device, and sets the process to
5731 // ignore SIGHUP. On Windows, does nothing. Returns 0 if OK, -1 if there
5732 // was an error.
5733 CZMQ_EXPORT void
5734 zproc_daemonize (const char *workdir);
5735
5736 // *** Draft method, for development use, may change without warning ***
5737 // Drop the process ID into the lockfile, with exclusive lock, and
5738 // switch the process to the specified group and/or user. Any of the
5739 // arguments may be null, indicating a no-op. Returns 0 on success,
5740 // -1 on failure. Note if you combine this with zsys_daemonize, run
5741 // after, not before that method, or the lockfile will hold the wrong
5742 // process ID.
5743 CZMQ_EXPORT void
5744 zproc_run_as (const char *lockfile, const char *group, const char *user);
5745
5746 // *** Draft method, for development use, may change without warning ***
5747 // Configure the number of I/O threads that ZeroMQ will use. A good
5748 // rule of thumb is one thread per gigabit of traffic in or out. The
5749 // default is 1, sufficient for most applications. If the environment
5750 // variable ZSYS_IO_THREADS is defined, that provides the default.
5751 // Note that this method is valid only before any socket is created.
5752 CZMQ_EXPORT void
5753 zproc_set_io_threads (size_t io_threads);
5754
5755 // *** Draft method, for development use, may change without warning ***
5756 // Configure the number of sockets that ZeroMQ will allow. The default
5757 // is 1024. The actual limit depends on the system, and you can query it
5758 // by using zsys_socket_limit (). A value of zero means "maximum".
5759 // Note that this method is valid only before any socket is created.
5760 CZMQ_EXPORT void
5761 zproc_set_max_sockets (size_t max_sockets);
5762
5763 // *** Draft method, for development use, may change without warning ***
5764 // Set network interface name to use for broadcasts, particularly zbeacon.
5765 // This lets the interface be configured for test environments where required.
5766 // For example, on Mac OS X, zbeacon cannot bind to 255.255.255.255 which is
5767 // the default when there is no specified interface. If the environment
5768 // variable ZSYS_INTERFACE is set, use that as the default interface name.
5769 // Setting the interface to "*" means "use all available interfaces".
5770 CZMQ_EXPORT void
5771 zproc_set_biface (const char *value);
5772
5773 // *** Draft method, for development use, may change without warning ***
5774 // Return network interface to use for broadcasts, or "" if none was set.
5775 CZMQ_EXPORT const char *
5776 zproc_biface (void);
5777
5778 // *** Draft method, for development use, may change without warning ***
5779 // Set log identity, which is a string that prefixes all log messages sent
5780 // by this process. The log identity defaults to the environment variable
5781 // ZSYS_LOGIDENT, if that is set.
5782 CZMQ_EXPORT void
5783 zproc_set_log_ident (const char *value);
5784
5785 // *** Draft method, for development use, may change without warning ***
5786 // Sends log output to a PUB socket bound to the specified endpoint. To
5787 // collect such log output, create a SUB socket, subscribe to the traffic
5788 // you care about, and connect to the endpoint. Log traffic is sent as a
5789 // single string frame, in the same format as when sent to stdout. The
5790 // log system supports a single sender; multiple calls to this method will
5791 // bind the same sender to multiple endpoints. To disable the sender, call
5792 // this method with a null argument.
5793 CZMQ_EXPORT void
5794 zproc_set_log_sender (const char *endpoint);
5795
5796 // *** Draft method, for development use, may change without warning ***
5797 // Enable or disable logging to the system facility (syslog on POSIX boxes,
5798 // event log on Windows). By default this is disabled.
5799 CZMQ_EXPORT void
5800 zproc_set_log_system (bool logsystem);
5801
5802 // *** Draft method, for development use, may change without warning ***
5803 // Log error condition - highest priority
5804 CZMQ_EXPORT void
5805 zproc_log_error (const char *format, ...) CHECK_PRINTF (1);
5806
5807 // *** Draft method, for development use, may change without warning ***
5808 // Log warning condition - high priority
5809 CZMQ_EXPORT void
5810 zproc_log_warning (const char *format, ...) CHECK_PRINTF (1);
5811
5812 // *** Draft method, for development use, may change without warning ***
5813 // Log normal, but significant, condition - normal priority
5814 CZMQ_EXPORT void
5815 zproc_log_notice (const char *format, ...) CHECK_PRINTF (1);
5816
5817 // *** Draft method, for development use, may change without warning ***
5818 // Log informational message - low priority
5819 CZMQ_EXPORT void
5820 zproc_log_info (const char *format, ...) CHECK_PRINTF (1);
5821
5822 // *** Draft method, for development use, may change without warning ***
5823 // Log debug-level message - lowest priority
5824 CZMQ_EXPORT void
5825 zproc_log_debug (const char *format, ...) CHECK_PRINTF (1);
5826
5827 // *** Draft method, for development use, may change without warning ***
5828 // Self test of this class.
5829 CZMQ_EXPORT void
5830 zproc_test (bool verbose);
5831
5832 #endif // CZMQ_BUILD_DRAFT_API
5833```
5834Please add '@interface' section in './../src/zproc.c'.
5835
5836This is the class self test code:
5837
5838```c
5839 #if defined (__WINDOWS__)
5840 printf ("SKIPPED (on Windows)\n");
5841 return;
5842 #endif
5843 #if ZMQ_VERSION_MAJOR < 4
5844 printf ("SKIPPED (on zmq pre-4)\n");
5845 return;
5846 #endif
5847 int major, minor, patch;
5848 zsys_version (&major, &minor, &patch);
5849 if (major < 4) {
5850 printf ("SKIPPED (on zmq pre-4)\n");
5851 return;
5852 }
5853
5854 // @selftest
5855 // 0. initialization
5856 // find the right binary
5857 char *file = "src/zsp";
5858 if (zsys_file_exists ("_build/../src/zsp"))
5859 file = "_build/../src/zsp";
5860 else
5861 if (zsys_file_exists ("zsp"))
5862 file = "./zsp";
5863
5864 if (!zsys_file_exists (file)) {
5865 zsys_warning ("cannot detect zsp binary, %s does not exists", file);
5866 printf ("SKIPPED (zsp not found");
5867 return;
5868 }
5869
5870 // Create new subproc instance
5871 zproc_t *self = zproc_new ();
5872 zproc_set_verbose (self, verbose);
5873 assert (self);
5874 // join stdout of the process to zeromq socket
5875 // all data will be readable from zproc_stdout socket
5876 zproc_set_stdout (self, NULL);
5877
5878 zlistx_t *args = zlistx_new ();
5879 zlistx_add_end (args, file);
5880 zlistx_add_end (args, "--stdout");
5881 zproc_set_args (self, args);
5882
5883 zhashx_t *env = zhashx_new ();
5884 zhashx_insert (env, "ZSP_MESSAGE", "czmq is great\n");
5885 zproc_set_env (self, env);
5886
5887 // execute the binary. It runs in own actor, which monitor the process and
5888 // pass data accross pipes and zeromq sockets
5889 zproc_run (self);
5890 zpoller_t *poller = zpoller_new (zproc_stdout (self), NULL);
5891
5892 // kill the binary, it never ends, but the test must
5893 zclock_sleep (800);
5894 zproc_kill (self, SIGTERM);
5895 zproc_wait (self, true);
5896
5897 // read the content from zproc_stdout - use zpoller and a loop
5898 bool stdout_read = false;
5899 while (!zsys_interrupted) {
5900 void *which = zpoller_wait (poller, 800);
5901
5902 if (!which)
5903 break;
5904
5905 if (which == zproc_stdout (self)) {
5906 stdout_read = true;
5907 zframe_t *frame;
5908 zsock_brecv (zproc_stdout (self), "f", &frame);
5909 assert (!strncmp(
5910 "czmq is great\n",
5911 (char*) zframe_data (frame),
5912 14));
5913
5914 if (verbose)
5915 zframe_print (frame, "zproc_test");
5916
5917 zframe_destroy (&frame);
5918 continue;
5919 }
5920
5921 // should not get there
5922 assert (false);
5923 }
5924
5925 assert (stdout_read);
5926 zpoller_destroy (&poller);
5927 zproc_destroy (&self);
5928```
5929
5930#### zproxy - run a steerable proxy in the background
5931
5932A zproxy actor switches messages between a frontend and a backend socket.
5933It acts much like the zmq_proxy_steerable method, though it makes benefit
5934of CZMQ's facilities, to be somewhat simpler to set-up.
5935
5936This class replaces zproxy_v2, and is meant for applications that use the
5937CZMQ v3 API (meaning, zsock).
5938
5939This is the class interface:
5940
5941```h
5942 // Create new zproxy actor instance. The proxy switches messages between
5943 // a frontend socket and a backend socket; use the FRONTEND and BACKEND
5944 // commands to configure these:
5945 //
5946 // zactor_t *proxy = zactor_new (zproxy, NULL);
5947 //
5948 // Destroy zproxy instance. This destroys the two sockets and stops any
5949 // message flow between them:
5950 //
5951 // zactor_destroy (&proxy);
5952 //
5953 // Note that all zproxy commands are synchronous, so your application always
5954 // waits for a signal from the actor after each command.
5955 //
5956 // Enable verbose logging of commands and activity:
5957 //
5958 // zstr_send (proxy, "VERBOSE");
5959 // zsock_wait (proxy);
5960 //
5961 // Specify frontend socket type -- see zsock_type_str () -- and attach to
5962 // endpoints, see zsock_attach (). Note that a proxy socket is always
5963 // serverish:
5964 //
5965 // zstr_sendx (proxy, "FRONTEND", "XSUB", endpoints, NULL);
5966 // zsock_wait (proxy);
5967 //
5968 // Specify backend socket type -- see zsock_type_str () -- and attach to
5969 // endpoints, see zsock_attach (). Note that a proxy socket is always
5970 // serverish:
5971 //
5972 // zstr_sendx (proxy, "BACKEND", "XPUB", endpoints, NULL);
5973 // zsock_wait (proxy);
5974 //
5975 // Capture all proxied messages; these are delivered to the application
5976 // via an inproc PULL socket that you have already bound to the specified
5977 // endpoint:
5978 //
5979 // zstr_sendx (proxy, "CAPTURE", endpoint, NULL);
5980 // zsock_wait (proxy);
5981 //
5982 // Pause the proxy. A paused proxy will cease processing messages, causing
5983 // them to be queued up and potentially hit the high-water mark on the
5984 // frontend or backend socket, causing messages to be dropped, or writing
5985 // applications to block:
5986 //
5987 // zstr_sendx (proxy, "PAUSE", NULL);
5988 // zsock_wait (proxy);
5989 //
5990 // Resume the proxy. Note that the proxy starts automatically as soon as it
5991 // has a properly attached frontend and backend socket:
5992 //
5993 // zstr_sendx (proxy, "RESUME", NULL);
5994 // zsock_wait (proxy);
5995 //
5996 // Configure an authentication domain for the "FRONTEND" or "BACKEND" proxy
5997 // socket -- see zsock_set_zap_domain (). Call before binding socket:
5998 //
5999 // zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL);
6000 // zsock_wait (proxy);
6001 //
6002 // Configure PLAIN authentication for the "FRONTEND" or "BACKEND" proxy
6003 // socket -- see zsock_set_plain_server (). Call before binding socket:
6004 //
6005 // zstr_sendx (proxy, "PLAIN", "BACKEND", NULL);
6006 // zsock_wait (proxy);
6007 //
6008 // Configure CURVE authentication for the "FRONTEND" or "BACKEND" proxy
6009 // socket -- see zsock_set_curve_server () -- specifying both the public and
6010 // secret keys of a certificate as Z85 armored strings -- see
6011 // zcert_public_txt () and zcert_secret_txt (). Call before binding socket:
6012 //
6013 // zstr_sendx (proxy, "CURVE", "FRONTEND", public_txt, secret_txt, NULL);
6014 // zsock_wait (proxy);
6015 //
6016 // This is the zproxy constructor as a zactor_fn; the argument is a
6017 // character string specifying frontend and backend socket types as two
6018 // uppercase strings separated by a hyphen:
6019 CZMQ_EXPORT void
6020 zproxy (zsock_t *pipe, void *unused);
6021
6022 // Selftest
6023 CZMQ_EXPORT void
6024 zproxy_test (bool verbose);
6025```
6026Please add '@interface' section in './../src/zproxy.c'.
6027
6028This is the class self test code:
6029
6030```c
6031 // Create and configure our proxy
6032 zactor_t *proxy = zactor_new (zproxy, NULL);
6033 assert (proxy);
6034 if (verbose) {
6035 zstr_sendx (proxy, "VERBOSE", NULL);
6036 zsock_wait (proxy);
6037 }
6038 zstr_sendx (proxy, "FRONTEND", "PULL", "inproc://frontend", NULL);
6039 zsock_wait (proxy);
6040 zstr_sendx (proxy, "BACKEND", "PUSH", "inproc://backend", NULL);
6041 zsock_wait (proxy);
6042
6043 // Connect application sockets to proxy
6044 zsock_t *faucet = zsock_new_push (">inproc://frontend");
6045 assert (faucet);
6046 zsock_t *sink = zsock_new_pull (">inproc://backend");
6047 assert (sink);
6048
6049 // Send some messages and check they arrived
6050 char *hello, *world;
6051 zstr_sendx (faucet, "Hello", "World", NULL);
6052 zstr_recvx (sink, &hello, &world, NULL);
6053 assert (streq (hello, "Hello"));
6054 assert (streq (world, "World"));
6055 zstr_free (&hello);
6056 zstr_free (&world);
6057
6058 // Test pause/resume functionality
6059 zstr_sendx (proxy, "PAUSE", NULL);
6060 zsock_wait (proxy);
6061 zstr_sendx (faucet, "Hello", "World", NULL);
6062 zsock_set_rcvtimeo (sink, 100);
6063 zstr_recvx (sink, &hello, &world, NULL);
6064 assert (!hello && !world);
6065
6066 zstr_sendx (proxy, "RESUME", NULL);
6067 zsock_wait (proxy);
6068 zstr_recvx (sink, &hello, &world, NULL);
6069 assert (streq (hello, "Hello"));
6070 assert (streq (world, "World"));
6071 zstr_free (&hello);
6072 zstr_free (&world);
6073
6074 // Test capture functionality
6075 zsock_t *capture = zsock_new_pull ("inproc://capture");
6076 assert (capture);
6077
6078 // Switch on capturing, check that it works
6079 zstr_sendx (proxy, "CAPTURE", "inproc://capture", NULL);
6080 zsock_wait (proxy);
6081 zstr_sendx (faucet, "Hello", "World", NULL);
6082 zstr_recvx (sink, &hello, &world, NULL);
6083 assert (streq (hello, "Hello"));
6084 assert (streq (world, "World"));
6085 zstr_free (&hello);
6086 zstr_free (&world);
6087
6088 zstr_recvx (capture, &hello, &world, NULL);
6089 assert (streq (hello, "Hello"));
6090 assert (streq (world, "World"));
6091 zstr_free (&hello);
6092 zstr_free (&world);
6093
6094 zsock_destroy (&faucet);
6095 zsock_destroy (&sink);
6096 zsock_destroy (&capture);
6097 zactor_destroy (&proxy);
6098
6099 // Test socket creation dependency
6100 proxy = zactor_new (zproxy, NULL);
6101 assert (proxy);
6102
6103 #ifdef WIN32
6104 sink = zsock_new_sub(">inproc://backend", "whatever");
6105 #else
6106 sink = zsock_new_sub (">ipc://backend", "whatever");
6107 #endif // WIN32
6108 assert (sink);
6109
6110 #ifdef WIN32
6111 zstr_sendx (proxy, "BACKEND", "XPUB", "inproc://backend", NULL);
6112 #else
6113 zstr_sendx(proxy, "BACKEND", "XPUB", "ipc://backend", NULL);
6114 #endif
6115 zsock_wait (proxy);
6116
6117 zsock_destroy(&sink);
6118 zactor_destroy(&proxy);
6119
6120 #if (ZMQ_VERSION_MAJOR == 4)
6121 // Test authentication functionality
6122 # define TESTDIR ".test_zproxy"
6123
6124 // Create temporary directory for test files
6125 zsys_dir_create (TESTDIR);
6126
6127 char *frontend = NULL;
6128 char *backend = NULL;
6129
6130 // Check there's no authentication
6131 s_create_test_sockets (&proxy, &faucet, &sink, verbose);
6132 s_bind_test_sockets (proxy, &frontend, &backend);
6133 bool success = s_can_connect (&proxy, &faucet, &sink, frontend, backend,
6134 verbose, true);
6135 assert (success);
6136
6137 // Install the authenticator
6138 zactor_t *auth = zactor_new (zauth, NULL);
6139 assert (auth);
6140 if (verbose) {
6141 zstr_sendx (auth, "VERBOSE", NULL);
6142 zsock_wait (auth);
6143 }
6144
6145 // Check there's no authentication on a default NULL server
6146 s_bind_test_sockets (proxy, &frontend, &backend);
6147 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose,
6148 true);
6149 assert (success);
6150
6151 // When we set a domain on the server, we switch on authentication
6152 // for NULL sockets, but with no policies, the client connection
6153 // will be allowed.
6154 zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL);
6155 zsock_wait (proxy);
6156 s_bind_test_sockets (proxy, &frontend, &backend);
6157 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose,
6158 true);
6159 assert (success);
6160
6161 // Blacklist 127.0.0.1, connection should fail
6162 zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL);
6163 zsock_wait (proxy);
6164 s_bind_test_sockets (proxy, &frontend, &backend);
6165 zstr_sendx (auth, "DENY", "127.0.0.1", NULL);
6166 zsock_wait (auth);
6167 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose,
6168 false);
6169 assert (!success);
6170
6171 // Whitelist our address, which overrides the blacklist
6172 zstr_sendx (proxy, "DOMAIN", "FRONTEND", "global", NULL);
6173 zsock_wait (proxy);
6174 zstr_sendx (proxy, "DOMAIN", "BACKEND", "global", NULL);
6175 zsock_wait (proxy);
6176 s_bind_test_sockets (proxy, &frontend, &backend);
6177 zstr_sendx (auth, "ALLOW", "127.0.0.1", NULL);
6178 zsock_wait (auth);
6179 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose,
6180 true);
6181 assert (success);
6182
6183 // Try PLAIN authentication
6184
6185 // Test negative case (no server-side passwords defined)
6186 zstr_sendx (proxy, "PLAIN", "FRONTEND", NULL);
6187 zsock_wait (proxy);
6188 s_bind_test_sockets (proxy, &frontend, &backend);
6189 zsock_set_plain_username (faucet, "admin");
6190 zsock_set_plain_password (faucet, "Password");
6191 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose,
6192 false);
6193 assert (!success);
6194
6195 // Test positive case (server-side passwords defined)
6196 FILE *password = fopen (TESTDIR "/password-file", "w");
6197 assert (password);
6198 fprintf (password, "admin=Password\n");
6199 fclose (password);
6200 zstr_sendx (proxy, "PLAIN", "FRONTEND", NULL);
6201 zsock_wait (proxy);
6202 zstr_sendx (proxy, "PLAIN", "BACKEND", NULL);
6203 zsock_wait (proxy);
6204 s_bind_test_sockets (proxy, &frontend, &backend);
6205 zsock_set_plain_username (faucet, "admin");
6206 zsock_set_plain_password (faucet, "Password");
6207 zsock_set_plain_username (sink, "admin");
6208 zsock_set_plain_password (sink, "Password");
6209 zstr_sendx (auth, "PLAIN", TESTDIR "/password-file", NULL);
6210 zsock_wait (auth);
6211 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose,
6212 true);
6213 assert (success);
6214
6215 // Test negative case (bad client password)
6216 zstr_sendx (proxy, "PLAIN", "FRONTEND", NULL);
6217 zsock_wait (proxy);
6218 s_bind_test_sockets (proxy, &frontend, &backend);
6219 zsock_set_plain_username (faucet, "admin");
6220 zsock_set_plain_password (faucet, "Bogus");
6221 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose,
6222 false);
6223 assert (!success);
6224
6225 if (zsys_has_curve ()) {
6226 // We'll create two new certificates and save the client public
6227 // certificate on disk
6228 zcert_t *server_cert = zcert_new ();
6229 assert (server_cert);
6230 zcert_t *client_cert = zcert_new ();
6231 assert (client_cert);
6232 const char *public_key = zcert_public_txt (server_cert);
6233 const char *secret_key = zcert_secret_txt (server_cert);
6234
6235 // Try CURVE authentication
6236
6237 // Test without setting-up any authentication
6238 zstr_sendx (proxy, "CURVE", "FRONTEND", public_key, secret_key, NULL);
6239 zsock_wait (proxy);
6240 s_bind_test_sockets (proxy, &frontend, &backend);
6241 zcert_apply (client_cert, faucet);
6242 zsock_set_curve_serverkey (faucet, public_key);
6243 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend,
6244 verbose, false);
6245 assert (!success);
6246
6247 // Test CURVE_ALLOW_ANY
6248 zstr_sendx (proxy, "CURVE", "FRONTEND", public_key, secret_key, NULL);
6249 zsock_wait (proxy);
6250 s_bind_test_sockets (proxy, &frontend, &backend);
6251 zcert_apply (client_cert, faucet);
6252 zsock_set_curve_serverkey (faucet, public_key);
6253 zstr_sendx (auth, "CURVE", CURVE_ALLOW_ANY, NULL);
6254 zsock_wait (auth);
6255 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend,
6256 verbose, true);
6257 assert (success);
6258
6259 // Test with client certificate file in authentication folder
6260 zstr_sendx (proxy, "CURVE", "FRONTEND", public_key, secret_key, NULL);
6261 zsock_wait (proxy);
6262 zstr_sendx (proxy, "CURVE", "BACKEND", public_key, secret_key, NULL);
6263 zsock_wait (proxy);
6264 s_bind_test_sockets (proxy, &frontend, &backend);
6265 zcert_apply (client_cert, faucet);
6266 zsock_set_curve_serverkey (faucet, public_key);
6267 zcert_apply (client_cert, sink);
6268 zsock_set_curve_serverkey (sink, public_key);
6269 zcert_save_public (client_cert, TESTDIR "/mycert.txt");
6270 zstr_sendx (auth, "CURVE", TESTDIR, NULL);
6271 zsock_wait (auth);
6272 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend,
6273 verbose, true);
6274 assert (success);
6275
6276 zcert_destroy (&server_cert);
6277 zcert_destroy (&client_cert);
6278 }
6279
6280 // Remove the authenticator and check a normal connection works
6281 zactor_destroy (&auth);
6282 s_bind_test_sockets (proxy, &frontend, &backend);
6283 success = s_can_connect (&proxy, &faucet, &sink, frontend, backend, verbose,
6284 true);
6285 assert (success);
6286
6287 // Cleanup
6288 zsock_destroy (&faucet);
6289 zsock_destroy (&sink);
6290 zactor_destroy (&proxy);
6291 zstr_free (&frontend);
6292 zstr_free (&backend);
6293
6294 // Delete temporary directory and test files
6295 zsys_file_delete (TESTDIR "/password-file");
6296 zsys_file_delete (TESTDIR "/mycert.txt");
6297 zsys_dir_delete (TESTDIR);
6298 #endif
6299
6300 #if defined (__WINDOWS__)
6301 zsys_shutdown();
6302 #endif
6303```
6304
6305#### zrex - work with regular expressions
6306
6307Wraps a very simple regular expression library (SLRE) as a CZMQ class.
6308Supports this syntax:
6309
6310 ^ Match beginning of a buffer
6311 $ Match end of a buffer
6312 () Grouping and substring capturing
6313 [...] Match any character from set
6314 [^...] Match any character but ones from set
6315 . Match any character
6316 \s Match whitespace
6317 \S Match non-whitespace
6318 \d Match decimal digit
6319 \D Match non decimal digit
6320 \a Match alphabetic character
6321 \A Match non-alphabetic character
6322 \w Match alphanumeric character
6323 \W Match non-alphanumeric character
6324 \r Match carriage return
6325 \n Match newline
6326 + Match one or more times (greedy)
6327 +? Match one or more times (non-greedy)
6328 * Match zero or more times (greedy)
6329 *? Match zero or more times (non-greedy)
6330 ? Match zero or once
6331 \xDD Match byte with hex value 0xDD
6332 \meta Match one of the meta character: ^$().[*+?\
6333
6334Please add '@discuss' section in './../src/zrex.c'.
6335
6336This is the class interface:
6337
6338```h
6339 // Constructor. Optionally, sets an expression against which we can match
6340 // text and capture hits. If there is an error in the expression, reports
6341 // zrex_valid() as false and provides the error in zrex_strerror(). If you
6342 // set a pattern, you can call zrex_matches() to test it against text.
6343 CZMQ_EXPORT zrex_t *
6344 zrex_new (const char *expression);
6345
6346 // Destructor
6347 CZMQ_EXPORT void
6348 zrex_destroy (zrex_t **self_p);
6349
6350 // Return true if the expression was valid and compiled without errors.
6351 CZMQ_EXPORT bool
6352 zrex_valid (zrex_t *self);
6353
6354 // Return the error message generated during compilation of the expression.
6355 CZMQ_EXPORT const char *
6356 zrex_strerror (zrex_t *self);
6357
6358 // Returns true if the text matches the previously compiled expression.
6359 // Use this method to compare one expression against many strings.
6360 CZMQ_EXPORT bool
6361 zrex_matches (zrex_t *self, const char *text);
6362
6363 // Returns true if the text matches the supplied expression. Use this
6364 // method to compare one string against several expressions.
6365 CZMQ_EXPORT bool
6366 zrex_eq (zrex_t *self, const char *text, const char *expression);
6367
6368 // Returns number of hits from last zrex_matches or zrex_eq. If the text
6369 // matched, returns 1 plus the number of capture groups. If the text did
6370 // not match, returns zero. To retrieve individual capture groups, call
6371 // zrex_hit ().
6372 CZMQ_EXPORT int
6373 zrex_hits (zrex_t *self);
6374
6375 // Returns the Nth capture group from the last expression match, where
6376 // N is 0 to the value returned by zrex_hits(). Capture group 0 is the
6377 // whole matching string. Sequence 1 is the first capture group, if any,
6378 // and so on.
6379 CZMQ_EXPORT const char *
6380 zrex_hit (zrex_t *self, uint index);
6381
6382 // Fetches hits into string variables provided by caller; this makes for
6383 // nicer code than accessing hits by index. Caller should not modify nor
6384 // free the returned values. Returns number of strings returned. This
6385 // method starts at hit 1, i.e. first capture group, as hit 0 is always
6386 // the original matched string.
6387 CZMQ_EXPORT int
6388 zrex_fetch (zrex_t *self, const char **string_p, ...);
6389
6390 // Self test of this class
6391 CZMQ_EXPORT void
6392 zrex_test (bool verbose);
6393```
6394Please add '@interface' section in './../src/zrex.c'.
6395
6396This is the class self test code:
6397
6398```c
6399 // This shows the pattern of matching many lines to a single pattern
6400 zrex_t *rex = zrex_new ("\\d+-\\d+-\\d+");
6401 assert (rex);
6402 assert (zrex_valid (rex));
6403 bool matches = zrex_matches (rex, "123-456-789");
6404 assert (matches);
6405 assert (zrex_hits (rex) == 1);
6406 assert (streq (zrex_hit (rex, 0), "123-456-789"));
6407 assert (zrex_hit (rex, 1) == NULL);
6408 zrex_destroy (&rex);
6409
6410 // Here we pick out hits using capture groups
6411 rex = zrex_new ("(\\d+)-(\\d+)-(\\d+)");
6412 assert (rex);
6413 assert (zrex_valid (rex));
6414 matches = zrex_matches (rex, "123-456-ABC");
6415 assert (!matches);
6416 matches = zrex_matches (rex, "123-456-789");
6417 assert (matches);
6418 assert (zrex_hits (rex) == 4);
6419 assert (streq (zrex_hit (rex, 0), "123-456-789"));
6420 assert (streq (zrex_hit (rex, 1), "123"));
6421 assert (streq (zrex_hit (rex, 2), "456"));
6422 assert (streq (zrex_hit (rex, 3), "789"));
6423 zrex_destroy (&rex);
6424
6425 // This shows the pattern of matching one line against many
6426 // patterns and then handling the case when it hits
6427 rex = zrex_new (NULL); // No initial pattern
6428 assert (rex);
6429 char *input = "Mechanism: CURVE";
6430 matches = zrex_eq (rex, input, "Version: (.+)");
6431 assert (!matches);
6432 assert (zrex_hits (rex) == 0);
6433 matches = zrex_eq (rex, input, "Mechanism: (.+)");
6434 assert (matches);
6435 assert (zrex_hits (rex) == 2);
6436 const char *mechanism;
6437 zrex_fetch (rex, &mechanism, NULL);
6438 assert (streq (zrex_hit (rex, 1), "CURVE"));
6439 assert (streq (mechanism, "CURVE"));
6440 zrex_destroy (&rex);
6441
6442 #if defined (__WINDOWS__)
6443 zsys_shutdown();
6444 #endif
6445
6446```
6447
6448#### zsock - high-level socket API that hides libzmq contexts and sockets
6449
6450The zsock class wraps the libzmq socket handle (a void *) with a proper
6451structure that follows the CLASS rules for construction and destruction.
6452Some zsock methods take a void * "polymorphic" reference, which can be
6453either a zsock_t or a zactor_t reference, or a libzmq void *.
6454
6455Please add '@discuss' section in './../src/zsock.c'.
6456
6457This is the class interface:
6458
6459```h
6460 // This is a stable class, and may not change except for emergencies. It
6461 // is provided in stable builds.
6462 // This class has draft methods, which may change over time. They are not
6463 // in stable releases, by default. Use --enable-drafts to enable.
6464 // Create a new socket. Returns the new socket, or NULL if the new socket
6465 // could not be created. Note that the symbol zsock_new (and other
6466 // constructors/destructors for zsock) are redirected to the *_checked
6467 // variant, enabling intelligent socket leak detection. This can have
6468 // performance implications if you use a LOT of sockets. To turn off this
6469 // redirection behaviour, define ZSOCK_NOCHECK.
6470 CZMQ_EXPORT zsock_t *
6471 zsock_new (int type);
6472
6473 // Create a PUB socket. Default action is bind.
6474 CZMQ_EXPORT zsock_t *
6475 zsock_new_pub (const char *endpoint);
6476
6477 // Create a SUB socket, and optionally subscribe to some prefix string. Default
6478 // action is connect.
6479 CZMQ_EXPORT zsock_t *
6480 zsock_new_sub (const char *endpoint, const char *subscribe);
6481
6482 // Create a REQ socket. Default action is connect.
6483 CZMQ_EXPORT zsock_t *
6484 zsock_new_req (const char *endpoint);
6485
6486 // Create a REP socket. Default action is bind.
6487 CZMQ_EXPORT zsock_t *
6488 zsock_new_rep (const char *endpoint);
6489
6490 // Create a DEALER socket. Default action is connect.
6491 CZMQ_EXPORT zsock_t *
6492 zsock_new_dealer (const char *endpoint);
6493
6494 // Create a ROUTER socket. Default action is bind.
6495 CZMQ_EXPORT zsock_t *
6496 zsock_new_router (const char *endpoint);
6497
6498 // Create a PUSH socket. Default action is connect.
6499 CZMQ_EXPORT zsock_t *
6500 zsock_new_push (const char *endpoint);
6501
6502 // Create a PULL socket. Default action is bind.
6503 CZMQ_EXPORT zsock_t *
6504 zsock_new_pull (const char *endpoint);
6505
6506 // Create an XPUB socket. Default action is bind.
6507 CZMQ_EXPORT zsock_t *
6508 zsock_new_xpub (const char *endpoint);
6509
6510 // Create an XSUB socket. Default action is connect.
6511 CZMQ_EXPORT zsock_t *
6512 zsock_new_xsub (const char *endpoint);
6513
6514 // Create a PAIR socket. Default action is connect.
6515 CZMQ_EXPORT zsock_t *
6516 zsock_new_pair (const char *endpoint);
6517
6518 // Create a STREAM socket. Default action is connect.
6519 CZMQ_EXPORT zsock_t *
6520 zsock_new_stream (const char *endpoint);
6521
6522 // Destroy the socket. You must use this for any socket created via the
6523 // zsock_new method.
6524 CZMQ_EXPORT void
6525 zsock_destroy (zsock_t **self_p);
6526
6527 // Bind a socket to a formatted endpoint. For tcp:// endpoints, supports
6528 // ephemeral ports, if you specify the port number as "*". By default
6529 // zsock uses the IANA designated range from C000 (49152) to FFFF (65535).
6530 // To override this range, follow the "*" with "[first-last]". Either or
6531 // both first and last may be empty. To bind to a random port within the
6532 // range, use "!" in place of "*".
6533 //
6534 // Examples:
6535 // tcp://127.0.0.1:* bind to first free port from C000 up
6536 // tcp://127.0.0.1:! bind to random port from C000 to FFFF
6537 // tcp://127.0.0.1:*[60000-] bind to first free port from 60000 up
6538 // tcp://127.0.0.1:![-60000] bind to random port from C000 to 60000
6539 // tcp://127.0.0.1:![55000-55999]
6540 // bind to random port from 55000 to 55999
6541 //
6542 // On success, returns the actual port number used, for tcp:// endpoints,
6543 // and 0 for other transports. On failure, returns -1. Note that when using
6544 // ephemeral ports, a port may be reused by different services without
6545 // clients being aware. Protocols that run on ephemeral ports should take
6546 // this into account.
6547 CZMQ_EXPORT int
6548 zsock_bind (zsock_t *self, const char *format, ...) CHECK_PRINTF (2);
6549
6550 // Returns last bound endpoint, if any.
6551 CZMQ_EXPORT const char *
6552 zsock_endpoint (zsock_t *self);
6553
6554 // Unbind a socket from a formatted endpoint.
6555 // Returns 0 if OK, -1 if the endpoint was invalid or the function
6556 // isn't supported.
6557 CZMQ_EXPORT int
6558 zsock_unbind (zsock_t *self, const char *format, ...) CHECK_PRINTF (2);
6559
6560 // Connect a socket to a formatted endpoint
6561 // Returns 0 if OK, -1 if the endpoint was invalid.
6562 CZMQ_EXPORT int
6563 zsock_connect (zsock_t *self, const char *format, ...) CHECK_PRINTF (2);
6564
6565 // Disconnect a socket from a formatted endpoint
6566 // Returns 0 if OK, -1 if the endpoint was invalid or the function
6567 // isn't supported.
6568 CZMQ_EXPORT int
6569 zsock_disconnect (zsock_t *self, const char *format, ...) CHECK_PRINTF (2);
6570
6571 // Attach a socket to zero or more endpoints. If endpoints is not null,
6572 // parses as list of ZeroMQ endpoints, separated by commas, and prefixed by
6573 // '@' (to bind the socket) or '>' (to connect the socket). Returns 0 if all
6574 // endpoints were valid, or -1 if there was a syntax error. If the endpoint
6575 // does not start with '@' or '>', the serverish argument defines whether
6576 // it is used to bind (serverish = true) or connect (serverish = false).
6577 CZMQ_EXPORT int
6578 zsock_attach (zsock_t *self, const char *endpoints, bool serverish);
6579
6580 // Returns socket type as printable constant string.
6581 CZMQ_EXPORT const char *
6582 zsock_type_str (zsock_t *self);
6583
6584 // Send a 'picture' message to the socket (or actor). The picture is a
6585 // string that defines the type of each frame. This makes it easy to send
6586 // a complex multiframe message in one call. The picture can contain any
6587 // of these characters, each corresponding to one or two arguments:
6588 //
6589 // i = int (signed)
6590 // 1 = uint8_t
6591 // 2 = uint16_t
6592 // 4 = uint32_t
6593 // 8 = uint64_t
6594 // s = char *
6595 // b = byte *, size_t (2 arguments)
6596 // c = zchunk_t *
6597 // f = zframe_t *
6598 // h = zhashx_t *
6599 // U = zuuid_t *
6600 // p = void * (sends the pointer value, only meaningful over inproc)
6601 // m = zmsg_t * (sends all frames in the zmsg)
6602 // z = sends zero-sized frame (0 arguments)
6603 // u = uint (deprecated)
6604 //
6605 // Note that s, b, c, and f are encoded the same way and the choice is
6606 // offered as a convenience to the sender, which may or may not already
6607 // have data in a zchunk or zframe. Does not change or take ownership of
6608 // any arguments. Returns 0 if successful, -1 if sending failed for any
6609 // reason.
6610 CZMQ_EXPORT int
6611 zsock_send (void *self, const char *picture, ...);
6612
6613 // Send a 'picture' message to the socket (or actor). This is a va_list
6614 // version of zsock_send (), so please consult its documentation for the
6615 // details.
6616 CZMQ_EXPORT int
6617 zsock_vsend (void *self, const char *picture, va_list argptr);
6618
6619 // Receive a 'picture' message to the socket (or actor). See zsock_send for
6620 // the format and meaning of the picture. Returns the picture elements into
6621 // a series of pointers as provided by the caller:
6622 //
6623 // i = int * (stores signed integer)
6624 // 4 = uint32_t * (stores 32-bit unsigned integer)
6625 // 8 = uint64_t * (stores 64-bit unsigned integer)
6626 // s = char ** (allocates new string)
6627 // b = byte **, size_t * (2 arguments) (allocates memory)
6628 // c = zchunk_t ** (creates zchunk)
6629 // f = zframe_t ** (creates zframe)
6630 // U = zuuid_t * (creates a zuuid with the data)
6631 // h = zhashx_t ** (creates zhashx)
6632 // p = void ** (stores pointer)
6633 // m = zmsg_t ** (creates a zmsg with the remaing frames)
6634 // z = null, asserts empty frame (0 arguments)
6635 // u = uint * (stores unsigned integer, deprecated)
6636 //
6637 // Note that zsock_recv creates the returned objects, and the caller must
6638 // destroy them when finished with them. The supplied pointers do not need
6639 // to be initialized. Returns 0 if successful, or -1 if it failed to recv
6640 // a message, in which case the pointers are not modified. When message
6641 // frames are truncated (a short message), sets return values to zero/null.
6642 // If an argument pointer is NULL, does not store any value (skips it).
6643 // An 'n' picture matches an empty frame; if the message does not match,
6644 // the method will return -1.
6645 CZMQ_EXPORT int
6646 zsock_recv (void *self, const char *picture, ...);
6647
6648 // Receive a 'picture' message from the socket (or actor). This is a
6649 // va_list version of zsock_recv (), so please consult its documentation
6650 // for the details.
6651 CZMQ_EXPORT int
6652 zsock_vrecv (void *self, const char *picture, va_list argptr);
6653
6654 // Send a binary encoded 'picture' message to the socket (or actor). This
6655 // method is similar to zsock_send, except the arguments are encoded in a
6656 // binary format that is compatible with zproto, and is designed to reduce
6657 // memory allocations. The pattern argument is a string that defines the
6658 // type of each argument. Supports these argument types:
6659 //
6660 // pattern C type zproto type:
6661 // 1 uint8_t type = "number" size = "1"
6662 // 2 uint16_t type = "number" size = "2"
6663 // 4 uint32_t type = "number" size = "3"
6664 // 8 uint64_t type = "number" size = "4"
6665 // s char *, 0-255 chars type = "string"
6666 // S char *, 0-2^32-1 chars type = "longstr"
6667 // c zchunk_t * type = "chunk"
6668 // f zframe_t * type = "frame"
6669 // u zuuid_t * type = "uuid"
6670 // m zmsg_t * type = "msg"
6671 // p void *, sends pointer value, only over inproc
6672 //
6673 // Does not change or take ownership of any arguments. Returns 0 if
6674 // successful, -1 if sending failed for any reason.
6675 CZMQ_EXPORT int
6676 zsock_bsend (void *self, const char *picture, ...);
6677
6678 // Receive a binary encoded 'picture' message from the socket (or actor).
6679 // This method is similar to zsock_recv, except the arguments are encoded
6680 // in a binary format that is compatible with zproto, and is designed to
6681 // reduce memory allocations. The pattern argument is a string that defines
6682 // the type of each argument. See zsock_bsend for the supported argument
6683 // types. All arguments must be pointers; this call sets them to point to
6684 // values held on a per-socket basis.
6685 // For types 1, 2, 4 and 8 the caller must allocate the memory itself before
6686 // calling zsock_brecv.
6687 // For types S, the caller must free the value once finished with it, as
6688 // zsock_brecv will allocate the buffer.
6689 // For type s, the caller must not free the value as it is stored in a
6690 // local cache for performance purposes.
6691 // For types c, f, u and m the caller must call the appropriate destructor
6692 // depending on the object as zsock_brecv will create new objects.
6693 // For type p the caller must coordinate with the sender, as it is just a
6694 // pointer value being passed.
6695 CZMQ_EXPORT int
6696 zsock_brecv (void *self, const char *picture, ...);
6697
6698 // Set socket to use unbounded pipes (HWM=0); use this in cases when you are
6699 // totally certain the message volume can fit in memory. This method works
6700 // across all versions of ZeroMQ. Takes a polymorphic socket reference.
6701 CZMQ_EXPORT void
6702 zsock_set_unbounded (void *self);
6703
6704 // Send a signal over a socket. A signal is a short message carrying a
6705 // success/failure code (by convention, 0 means OK). Signals are encoded
6706 // to be distinguishable from "normal" messages. Accepts a zsock_t or a
6707 // zactor_t argument, and returns 0 if successful, -1 if the signal could
6708 // not be sent. Takes a polymorphic socket reference.
6709 CZMQ_EXPORT int
6710 zsock_signal (void *self, byte status);
6711
6712 // Wait on a signal. Use this to coordinate between threads, over pipe
6713 // pairs. Blocks until the signal is received. Returns -1 on error, 0 or
6714 // greater on success. Accepts a zsock_t or a zactor_t as argument.
6715 // Takes a polymorphic socket reference.
6716 CZMQ_EXPORT int
6717 zsock_wait (void *self);
6718
6719 // If there is a partial message still waiting on the socket, remove and
6720 // discard it. This is useful when reading partial messages, to get specific
6721 // message types.
6722 CZMQ_EXPORT void
6723 zsock_flush (void *self);
6724
6725 // Probe the supplied object, and report if it looks like a zsock_t.
6726 // Takes a polymorphic socket reference.
6727 CZMQ_EXPORT bool
6728 zsock_is (void *self);
6729
6730 // Probe the supplied reference. If it looks like a zsock_t instance, return
6731 // the underlying libzmq socket handle; else if it looks like a file
6732 // descriptor, return NULL; else if it looks like a libzmq socket handle,
6733 // return the supplied value. Takes a polymorphic socket reference.
6734 CZMQ_EXPORT void *
6735 zsock_resolve (void *self);
6736
6737 // Get socket option `heartbeat_ivl`.
6738 // Available from libzmq 4.2.0.
6739 // Caller owns return value and must destroy it when done.
6740 CZMQ_EXPORT int
6741 zsock_heartbeat_ivl (void *self);
6742
6743 // Set socket option `heartbeat_ivl`.
6744 // Available from libzmq 4.2.0.
6745 CZMQ_EXPORT void
6746 zsock_set_heartbeat_ivl (void *self, int heartbeat_ivl);
6747
6748 // Get socket option `heartbeat_ttl`.
6749 // Available from libzmq 4.2.0.
6750 // Caller owns return value and must destroy it when done.
6751 CZMQ_EXPORT int
6752 zsock_heartbeat_ttl (void *self);
6753
6754 // Set socket option `heartbeat_ttl`.
6755 // Available from libzmq 4.2.0.
6756 CZMQ_EXPORT void
6757 zsock_set_heartbeat_ttl (void *self, int heartbeat_ttl);
6758
6759 // Get socket option `heartbeat_timeout`.
6760 // Available from libzmq 4.2.0.
6761 // Caller owns return value and must destroy it when done.
6762 CZMQ_EXPORT int
6763 zsock_heartbeat_timeout (void *self);
6764
6765 // Set socket option `heartbeat_timeout`.
6766 // Available from libzmq 4.2.0.
6767 CZMQ_EXPORT void
6768 zsock_set_heartbeat_timeout (void *self, int heartbeat_timeout);
6769
6770 // Get socket option `use_fd`.
6771 // Available from libzmq 4.2.0.
6772 // Caller owns return value and must destroy it when done.
6773 CZMQ_EXPORT int
6774 zsock_use_fd (void *self);
6775
6776 // Set socket option `use_fd`.
6777 // Available from libzmq 4.2.0.
6778 CZMQ_EXPORT void
6779 zsock_set_use_fd (void *self, int use_fd);
6780
6781 // Set socket option `xpub_manual`.
6782 // Available from libzmq 4.2.0.
6783 CZMQ_EXPORT void
6784 zsock_set_xpub_manual (void *self, int xpub_manual);
6785
6786 // Set socket option `xpub_welcome_msg`.
6787 // Available from libzmq 4.2.0.
6788 CZMQ_EXPORT void
6789 zsock_set_xpub_welcome_msg (void *self, const char *xpub_welcome_msg);
6790
6791 // Set socket option `stream_notify`.
6792 // Available from libzmq 4.2.0.
6793 CZMQ_EXPORT void
6794 zsock_set_stream_notify (void *self, int stream_notify);
6795
6796 // Get socket option `invert_matching`.
6797 // Available from libzmq 4.2.0.
6798 // Caller owns return value and must destroy it when done.
6799 CZMQ_EXPORT int
6800 zsock_invert_matching (void *self);
6801
6802 // Set socket option `invert_matching`.
6803 // Available from libzmq 4.2.0.
6804 CZMQ_EXPORT void
6805 zsock_set_invert_matching (void *self, int invert_matching);
6806
6807 // Set socket option `xpub_verboser`.
6808 // Available from libzmq 4.2.0.
6809 CZMQ_EXPORT void
6810 zsock_set_xpub_verboser (void *self, int xpub_verboser);
6811
6812 // Get socket option `connect_timeout`.
6813 // Available from libzmq 4.2.0.
6814 // Caller owns return value and must destroy it when done.
6815 CZMQ_EXPORT int
6816 zsock_connect_timeout (void *self);
6817
6818 // Set socket option `connect_timeout`.
6819 // Available from libzmq 4.2.0.
6820 CZMQ_EXPORT void
6821 zsock_set_connect_timeout (void *self, int connect_timeout);
6822
6823 // Get socket option `tcp_maxrt`.
6824 // Available from libzmq 4.2.0.
6825 // Caller owns return value and must destroy it when done.
6826 CZMQ_EXPORT int
6827 zsock_tcp_maxrt (void *self);
6828
6829 // Set socket option `tcp_maxrt`.
6830 // Available from libzmq 4.2.0.
6831 CZMQ_EXPORT void
6832 zsock_set_tcp_maxrt (void *self, int tcp_maxrt);
6833
6834 // Get socket option `thread_safe`.
6835 // Available from libzmq 4.2.0.
6836 // Caller owns return value and must destroy it when done.
6837 CZMQ_EXPORT int
6838 zsock_thread_safe (void *self);
6839
6840 // Get socket option `multicast_maxtpdu`.
6841 // Available from libzmq 4.2.0.
6842 // Caller owns return value and must destroy it when done.
6843 CZMQ_EXPORT int
6844 zsock_multicast_maxtpdu (void *self);
6845
6846 // Set socket option `multicast_maxtpdu`.
6847 // Available from libzmq 4.2.0.
6848 CZMQ_EXPORT void
6849 zsock_set_multicast_maxtpdu (void *self, int multicast_maxtpdu);
6850
6851 // Get socket option `vmci_buffer_size`.
6852 // Available from libzmq 4.2.0.
6853 // Caller owns return value and must destroy it when done.
6854 CZMQ_EXPORT int
6855 zsock_vmci_buffer_size (void *self);
6856
6857 // Set socket option `vmci_buffer_size`.
6858 // Available from libzmq 4.2.0.
6859 CZMQ_EXPORT void
6860 zsock_set_vmci_buffer_size (void *self, int vmci_buffer_size);
6861
6862 // Get socket option `vmci_buffer_min_size`.
6863 // Available from libzmq 4.2.0.
6864 // Caller owns return value and must destroy it when done.
6865 CZMQ_EXPORT int
6866 zsock_vmci_buffer_min_size (void *self);
6867
6868 // Set socket option `vmci_buffer_min_size`.
6869 // Available from libzmq 4.2.0.
6870 CZMQ_EXPORT void
6871 zsock_set_vmci_buffer_min_size (void *self, int vmci_buffer_min_size);
6872
6873 // Get socket option `vmci_buffer_max_size`.
6874 // Available from libzmq 4.2.0.
6875 // Caller owns return value and must destroy it when done.
6876 CZMQ_EXPORT int
6877 zsock_vmci_buffer_max_size (void *self);
6878
6879 // Set socket option `vmci_buffer_max_size`.
6880 // Available from libzmq 4.2.0.
6881 CZMQ_EXPORT void
6882 zsock_set_vmci_buffer_max_size (void *self, int vmci_buffer_max_size);
6883
6884 // Get socket option `vmci_connect_timeout`.
6885 // Available from libzmq 4.2.0.
6886 // Caller owns return value and must destroy it when done.
6887 CZMQ_EXPORT int
6888 zsock_vmci_connect_timeout (void *self);
6889
6890 // Set socket option `vmci_connect_timeout`.
6891 // Available from libzmq 4.2.0.
6892 CZMQ_EXPORT void
6893 zsock_set_vmci_connect_timeout (void *self, int vmci_connect_timeout);
6894
6895 // Get socket option `tos`.
6896 // Available from libzmq 4.1.0.
6897 // Caller owns return value and must destroy it when done.
6898 CZMQ_EXPORT int
6899 zsock_tos (void *self);
6900
6901 // Set socket option `tos`.
6902 // Available from libzmq 4.1.0.
6903 CZMQ_EXPORT void
6904 zsock_set_tos (void *self, int tos);
6905
6906 // Set socket option `router_handover`.
6907 // Available from libzmq 4.1.0.
6908 CZMQ_EXPORT void
6909 zsock_set_router_handover (void *self, int router_handover);
6910
6911 // Set socket option `connect_rid`.
6912 // Available from libzmq 4.1.0.
6913 CZMQ_EXPORT void
6914 zsock_set_connect_rid (void *self, const char *connect_rid);
6915
6916 // Set socket option `connect_rid` from 32-octet binary
6917 // Available from libzmq 4.1.0.
6918 CZMQ_EXPORT void
6919 zsock_set_connect_rid_bin (void *self, const byte *connect_rid);
6920
6921 // Get socket option `handshake_ivl`.
6922 // Available from libzmq 4.1.0.
6923 // Caller owns return value and must destroy it when done.
6924 CZMQ_EXPORT int
6925 zsock_handshake_ivl (void *self);
6926
6927 // Set socket option `handshake_ivl`.
6928 // Available from libzmq 4.1.0.
6929 CZMQ_EXPORT void
6930 zsock_set_handshake_ivl (void *self, int handshake_ivl);
6931
6932 // Get socket option `socks_proxy`.
6933 // Available from libzmq 4.1.0.
6934 // Caller owns return value and must destroy it when done.
6935 CZMQ_EXPORT char *
6936 zsock_socks_proxy (void *self);
6937
6938 // Set socket option `socks_proxy`.
6939 // Available from libzmq 4.1.0.
6940 CZMQ_EXPORT void
6941 zsock_set_socks_proxy (void *self, const char *socks_proxy);
6942
6943 // Set socket option `xpub_nodrop`.
6944 // Available from libzmq 4.1.0.
6945 CZMQ_EXPORT void
6946 zsock_set_xpub_nodrop (void *self, int xpub_nodrop);
6947
6948 // Set socket option `router_mandatory`.
6949 // Available from libzmq 4.0.0.
6950 CZMQ_EXPORT void
6951 zsock_set_router_mandatory (void *self, int router_mandatory);
6952
6953 // Set socket option `probe_router`.
6954 // Available from libzmq 4.0.0.
6955 CZMQ_EXPORT void
6956 zsock_set_probe_router (void *self, int probe_router);
6957
6958 // Set socket option `req_relaxed`.
6959 // Available from libzmq 4.0.0.
6960 CZMQ_EXPORT void
6961 zsock_set_req_relaxed (void *self, int req_relaxed);
6962
6963 // Set socket option `req_correlate`.
6964 // Available from libzmq 4.0.0.
6965 CZMQ_EXPORT void
6966 zsock_set_req_correlate (void *self, int req_correlate);
6967
6968 // Set socket option `conflate`.
6969 // Available from libzmq 4.0.0.
6970 CZMQ_EXPORT void
6971 zsock_set_conflate (void *self, int conflate);
6972
6973 // Get socket option `zap_domain`.
6974 // Available from libzmq 4.0.0.
6975 // Caller owns return value and must destroy it when done.
6976 CZMQ_EXPORT char *
6977 zsock_zap_domain (void *self);
6978
6979 // Set socket option `zap_domain`.
6980 // Available from libzmq 4.0.0.
6981 CZMQ_EXPORT void
6982 zsock_set_zap_domain (void *self, const char *zap_domain);
6983
6984 // Get socket option `mechanism`.
6985 // Available from libzmq 4.0.0.
6986 // Caller owns return value and must destroy it when done.
6987 CZMQ_EXPORT int
6988 zsock_mechanism (void *self);
6989
6990 // Get socket option `plain_server`.
6991 // Available from libzmq 4.0.0.
6992 // Caller owns return value and must destroy it when done.
6993 CZMQ_EXPORT int
6994 zsock_plain_server (void *self);
6995
6996 // Set socket option `plain_server`.
6997 // Available from libzmq 4.0.0.
6998 CZMQ_EXPORT void
6999 zsock_set_plain_server (void *self, int plain_server);
7000
7001 // Get socket option `plain_username`.
7002 // Available from libzmq 4.0.0.
7003 // Caller owns return value and must destroy it when done.
7004 CZMQ_EXPORT char *
7005 zsock_plain_username (void *self);
7006
7007 // Set socket option `plain_username`.
7008 // Available from libzmq 4.0.0.
7009 CZMQ_EXPORT void
7010 zsock_set_plain_username (void *self, const char *plain_username);
7011
7012 // Get socket option `plain_password`.
7013 // Available from libzmq 4.0.0.
7014 // Caller owns return value and must destroy it when done.
7015 CZMQ_EXPORT char *
7016 zsock_plain_password (void *self);
7017
7018 // Set socket option `plain_password`.
7019 // Available from libzmq 4.0.0.
7020 CZMQ_EXPORT void
7021 zsock_set_plain_password (void *self, const char *plain_password);
7022
7023 // Get socket option `curve_server`.
7024 // Available from libzmq 4.0.0.
7025 // Caller owns return value and must destroy it when done.
7026 CZMQ_EXPORT int
7027 zsock_curve_server (void *self);
7028
7029 // Set socket option `curve_server`.
7030 // Available from libzmq 4.0.0.
7031 CZMQ_EXPORT void
7032 zsock_set_curve_server (void *self, int curve_server);
7033
7034 // Get socket option `curve_publickey`.
7035 // Available from libzmq 4.0.0.
7036 // Caller owns return value and must destroy it when done.
7037 CZMQ_EXPORT char *
7038 zsock_curve_publickey (void *self);
7039
7040 // Set socket option `curve_publickey`.
7041 // Available from libzmq 4.0.0.
7042 CZMQ_EXPORT void
7043 zsock_set_curve_publickey (void *self, const char *curve_publickey);
7044
7045 // Set socket option `curve_publickey` from 32-octet binary
7046 // Available from libzmq 4.0.0.
7047 CZMQ_EXPORT void
7048 zsock_set_curve_publickey_bin (void *self, const byte *curve_publickey);
7049
7050 // Get socket option `curve_secretkey`.
7051 // Available from libzmq 4.0.0.
7052 // Caller owns return value and must destroy it when done.
7053 CZMQ_EXPORT char *
7054 zsock_curve_secretkey (void *self);
7055
7056 // Set socket option `curve_secretkey`.
7057 // Available from libzmq 4.0.0.
7058 CZMQ_EXPORT void
7059 zsock_set_curve_secretkey (void *self, const char *curve_secretkey);
7060
7061 // Set socket option `curve_secretkey` from 32-octet binary
7062 // Available from libzmq 4.0.0.
7063 CZMQ_EXPORT void
7064 zsock_set_curve_secretkey_bin (void *self, const byte *curve_secretkey);
7065
7066 // Get socket option `curve_serverkey`.
7067 // Available from libzmq 4.0.0.
7068 // Caller owns return value and must destroy it when done.
7069 CZMQ_EXPORT char *
7070 zsock_curve_serverkey (void *self);
7071
7072 // Set socket option `curve_serverkey`.
7073 // Available from libzmq 4.0.0.
7074 CZMQ_EXPORT void
7075 zsock_set_curve_serverkey (void *self, const char *curve_serverkey);
7076
7077 // Set socket option `curve_serverkey` from 32-octet binary
7078 // Available from libzmq 4.0.0.
7079 CZMQ_EXPORT void
7080 zsock_set_curve_serverkey_bin (void *self, const byte *curve_serverkey);
7081
7082 // Get socket option `gssapi_server`.
7083 // Available from libzmq 4.0.0.
7084 // Caller owns return value and must destroy it when done.
7085 CZMQ_EXPORT int
7086 zsock_gssapi_server (void *self);
7087
7088 // Set socket option `gssapi_server`.
7089 // Available from libzmq 4.0.0.
7090 CZMQ_EXPORT void
7091 zsock_set_gssapi_server (void *self, int gssapi_server);
7092
7093 // Get socket option `gssapi_plaintext`.
7094 // Available from libzmq 4.0.0.
7095 // Caller owns return value and must destroy it when done.
7096 CZMQ_EXPORT int
7097 zsock_gssapi_plaintext (void *self);
7098
7099 // Set socket option `gssapi_plaintext`.
7100 // Available from libzmq 4.0.0.
7101 CZMQ_EXPORT void
7102 zsock_set_gssapi_plaintext (void *self, int gssapi_plaintext);
7103
7104 // Get socket option `gssapi_principal`.
7105 // Available from libzmq 4.0.0.
7106 // Caller owns return value and must destroy it when done.
7107 CZMQ_EXPORT char *
7108 zsock_gssapi_principal (void *self);
7109
7110 // Set socket option `gssapi_principal`.
7111 // Available from libzmq 4.0.0.
7112 CZMQ_EXPORT void
7113 zsock_set_gssapi_principal (void *self, const char *gssapi_principal);
7114
7115 // Get socket option `gssapi_service_principal`.
7116 // Available from libzmq 4.0.0.
7117 // Caller owns return value and must destroy it when done.
7118 CZMQ_EXPORT char *
7119 zsock_gssapi_service_principal (void *self);
7120
7121 // Set socket option `gssapi_service_principal`.
7122 // Available from libzmq 4.0.0.
7123 CZMQ_EXPORT void
7124 zsock_set_gssapi_service_principal (void *self, const char *gssapi_service_principal);
7125
7126 // Get socket option `ipv6`.
7127 // Available from libzmq 4.0.0.
7128 // Caller owns return value and must destroy it when done.
7129 CZMQ_EXPORT int
7130 zsock_ipv6 (void *self);
7131
7132 // Set socket option `ipv6`.
7133 // Available from libzmq 4.0.0.
7134 CZMQ_EXPORT void
7135 zsock_set_ipv6 (void *self, int ipv6);
7136
7137 // Get socket option `immediate`.
7138 // Available from libzmq 4.0.0.
7139 // Caller owns return value and must destroy it when done.
7140 CZMQ_EXPORT int
7141 zsock_immediate (void *self);
7142
7143 // Set socket option `immediate`.
7144 // Available from libzmq 4.0.0.
7145 CZMQ_EXPORT void
7146 zsock_set_immediate (void *self, int immediate);
7147
7148 // Get socket option `sndhwm`.
7149 // Available from libzmq 3.0.0.
7150 // Caller owns return value and must destroy it when done.
7151 CZMQ_EXPORT int
7152 zsock_sndhwm (void *self);
7153
7154 // Set socket option `sndhwm`.
7155 // Available from libzmq 3.0.0.
7156 CZMQ_EXPORT void
7157 zsock_set_sndhwm (void *self, int sndhwm);
7158
7159 // Get socket option `rcvhwm`.
7160 // Available from libzmq 3.0.0.
7161 // Caller owns return value and must destroy it when done.
7162 CZMQ_EXPORT int
7163 zsock_rcvhwm (void *self);
7164
7165 // Set socket option `rcvhwm`.
7166 // Available from libzmq 3.0.0.
7167 CZMQ_EXPORT void
7168 zsock_set_rcvhwm (void *self, int rcvhwm);
7169
7170 // Get socket option `maxmsgsize`.
7171 // Available from libzmq 3.0.0.
7172 // Caller owns return value and must destroy it when done.
7173 CZMQ_EXPORT int
7174 zsock_maxmsgsize (void *self);
7175
7176 // Set socket option `maxmsgsize`.
7177 // Available from libzmq 3.0.0.
7178 CZMQ_EXPORT void
7179 zsock_set_maxmsgsize (void *self, int maxmsgsize);
7180
7181 // Get socket option `multicast_hops`.
7182 // Available from libzmq 3.0.0.
7183 // Caller owns return value and must destroy it when done.
7184 CZMQ_EXPORT int
7185 zsock_multicast_hops (void *self);
7186
7187 // Set socket option `multicast_hops`.
7188 // Available from libzmq 3.0.0.
7189 CZMQ_EXPORT void
7190 zsock_set_multicast_hops (void *self, int multicast_hops);
7191
7192 // Set socket option `xpub_verbose`.
7193 // Available from libzmq 3.0.0.
7194 CZMQ_EXPORT void
7195 zsock_set_xpub_verbose (void *self, int xpub_verbose);
7196
7197 // Get socket option `tcp_keepalive`.
7198 // Available from libzmq 3.0.0.
7199 // Caller owns return value and must destroy it when done.
7200 CZMQ_EXPORT int
7201 zsock_tcp_keepalive (void *self);
7202
7203 // Set socket option `tcp_keepalive`.
7204 // Available from libzmq 3.0.0.
7205 CZMQ_EXPORT void
7206 zsock_set_tcp_keepalive (void *self, int tcp_keepalive);
7207
7208 // Get socket option `tcp_keepalive_idle`.
7209 // Available from libzmq 3.0.0.
7210 // Caller owns return value and must destroy it when done.
7211 CZMQ_EXPORT int
7212 zsock_tcp_keepalive_idle (void *self);
7213
7214 // Set socket option `tcp_keepalive_idle`.
7215 // Available from libzmq 3.0.0.
7216 CZMQ_EXPORT void
7217 zsock_set_tcp_keepalive_idle (void *self, int tcp_keepalive_idle);
7218
7219 // Get socket option `tcp_keepalive_cnt`.
7220 // Available from libzmq 3.0.0.
7221 // Caller owns return value and must destroy it when done.
7222 CZMQ_EXPORT int
7223 zsock_tcp_keepalive_cnt (void *self);
7224
7225 // Set socket option `tcp_keepalive_cnt`.
7226 // Available from libzmq 3.0.0.
7227 CZMQ_EXPORT void
7228 zsock_set_tcp_keepalive_cnt (void *self, int tcp_keepalive_cnt);
7229
7230 // Get socket option `tcp_keepalive_intvl`.
7231 // Available from libzmq 3.0.0.
7232 // Caller owns return value and must destroy it when done.
7233 CZMQ_EXPORT int
7234 zsock_tcp_keepalive_intvl (void *self);
7235
7236 // Set socket option `tcp_keepalive_intvl`.
7237 // Available from libzmq 3.0.0.
7238 CZMQ_EXPORT void
7239 zsock_set_tcp_keepalive_intvl (void *self, int tcp_keepalive_intvl);
7240
7241 // Get socket option `tcp_accept_filter`.
7242 // Available from libzmq 3.0.0.
7243 // Caller owns return value and must destroy it when done.
7244 CZMQ_EXPORT char *
7245 zsock_tcp_accept_filter (void *self);
7246
7247 // Set socket option `tcp_accept_filter`.
7248 // Available from libzmq 3.0.0.
7249 CZMQ_EXPORT void
7250 zsock_set_tcp_accept_filter (void *self, const char *tcp_accept_filter);
7251
7252 // Get socket option `last_endpoint`.
7253 // Available from libzmq 3.0.0.
7254 // Caller owns return value and must destroy it when done.
7255 CZMQ_EXPORT char *
7256 zsock_last_endpoint (void *self);
7257
7258 // Set socket option `router_raw`.
7259 // Available from libzmq 3.0.0.
7260 CZMQ_EXPORT void
7261 zsock_set_router_raw (void *self, int router_raw);
7262
7263 // Get socket option `ipv4only`.
7264 // Available from libzmq 3.0.0.
7265 // Caller owns return value and must destroy it when done.
7266 CZMQ_EXPORT int
7267 zsock_ipv4only (void *self);
7268
7269 // Set socket option `ipv4only`.
7270 // Available from libzmq 3.0.0.
7271 CZMQ_EXPORT void
7272 zsock_set_ipv4only (void *self, int ipv4only);
7273
7274 // Set socket option `delay_attach_on_connect`.
7275 // Available from libzmq 3.0.0.
7276 CZMQ_EXPORT void
7277 zsock_set_delay_attach_on_connect (void *self, int delay_attach_on_connect);
7278
7279 // Get socket option `hwm`.
7280 // Available from libzmq 2.0.0 to 3.0.0.
7281 // Caller owns return value and must destroy it when done.
7282 CZMQ_EXPORT int
7283 zsock_hwm (void *self);
7284
7285 // Set socket option `hwm`.
7286 // Available from libzmq 2.0.0 to 3.0.0.
7287 CZMQ_EXPORT void
7288 zsock_set_hwm (void *self, int hwm);
7289
7290 // Get socket option `swap`.
7291 // Available from libzmq 2.0.0 to 3.0.0.
7292 // Caller owns return value and must destroy it when done.
7293 CZMQ_EXPORT int
7294 zsock_swap (void *self);
7295
7296 // Set socket option `swap`.
7297 // Available from libzmq 2.0.0 to 3.0.0.
7298 CZMQ_EXPORT void
7299 zsock_set_swap (void *self, int swap);
7300
7301 // Get socket option `affinity`.
7302 // Available from libzmq 2.0.0.
7303 // Caller owns return value and must destroy it when done.
7304 CZMQ_EXPORT int
7305 zsock_affinity (void *self);
7306
7307 // Set socket option `affinity`.
7308 // Available from libzmq 2.0.0.
7309 CZMQ_EXPORT void
7310 zsock_set_affinity (void *self, int affinity);
7311
7312 // Get socket option `identity`.
7313 // Available from libzmq 2.0.0.
7314 // Caller owns return value and must destroy it when done.
7315 CZMQ_EXPORT char *
7316 zsock_identity (void *self);
7317
7318 // Set socket option `identity`.
7319 // Available from libzmq 2.0.0.
7320 CZMQ_EXPORT void
7321 zsock_set_identity (void *self, const char *identity);
7322
7323 // Get socket option `rate`.
7324 // Available from libzmq 2.0.0.
7325 // Caller owns return value and must destroy it when done.
7326 CZMQ_EXPORT int
7327 zsock_rate (void *self);
7328
7329 // Set socket option `rate`.
7330 // Available from libzmq 2.0.0.
7331 CZMQ_EXPORT void
7332 zsock_set_rate (void *self, int rate);
7333
7334 // Get socket option `recovery_ivl`.
7335 // Available from libzmq 2.0.0.
7336 // Caller owns return value and must destroy it when done.
7337 CZMQ_EXPORT int
7338 zsock_recovery_ivl (void *self);
7339
7340 // Set socket option `recovery_ivl`.
7341 // Available from libzmq 2.0.0.
7342 CZMQ_EXPORT void
7343 zsock_set_recovery_ivl (void *self, int recovery_ivl);
7344
7345 // Get socket option `recovery_ivl_msec`.
7346 // Available from libzmq 2.0.0 to 3.0.0.
7347 // Caller owns return value and must destroy it when done.
7348 CZMQ_EXPORT int
7349 zsock_recovery_ivl_msec (void *self);
7350
7351 // Set socket option `recovery_ivl_msec`.
7352 // Available from libzmq 2.0.0 to 3.0.0.
7353 CZMQ_EXPORT void
7354 zsock_set_recovery_ivl_msec (void *self, int recovery_ivl_msec);
7355
7356 // Get socket option `mcast_loop`.
7357 // Available from libzmq 2.0.0 to 3.0.0.
7358 // Caller owns return value and must destroy it when done.
7359 CZMQ_EXPORT int
7360 zsock_mcast_loop (void *self);
7361
7362 // Set socket option `mcast_loop`.
7363 // Available from libzmq 2.0.0 to 3.0.0.
7364 CZMQ_EXPORT void
7365 zsock_set_mcast_loop (void *self, int mcast_loop);
7366
7367 // Get socket option `rcvtimeo`.
7368 // Available from libzmq 2.2.0.
7369 // Caller owns return value and must destroy it when done.
7370 CZMQ_EXPORT int
7371 zsock_rcvtimeo (void *self);
7372
7373 // Set socket option `rcvtimeo`.
7374 // Available from libzmq 2.2.0.
7375 CZMQ_EXPORT void
7376 zsock_set_rcvtimeo (void *self, int rcvtimeo);
7377
7378 // Get socket option `sndtimeo`.
7379 // Available from libzmq 2.2.0.
7380 // Caller owns return value and must destroy it when done.
7381 CZMQ_EXPORT int
7382 zsock_sndtimeo (void *self);
7383
7384 // Set socket option `sndtimeo`.
7385 // Available from libzmq 2.2.0.
7386 CZMQ_EXPORT void
7387 zsock_set_sndtimeo (void *self, int sndtimeo);
7388
7389 // Get socket option `sndbuf`.
7390 // Available from libzmq 2.0.0.
7391 // Caller owns return value and must destroy it when done.
7392 CZMQ_EXPORT int
7393 zsock_sndbuf (void *self);
7394
7395 // Set socket option `sndbuf`.
7396 // Available from libzmq 2.0.0.
7397 CZMQ_EXPORT void
7398 zsock_set_sndbuf (void *self, int sndbuf);
7399
7400 // Get socket option `rcvbuf`.
7401 // Available from libzmq 2.0.0.
7402 // Caller owns return value and must destroy it when done.
7403 CZMQ_EXPORT int
7404 zsock_rcvbuf (void *self);
7405
7406 // Set socket option `rcvbuf`.
7407 // Available from libzmq 2.0.0.
7408 CZMQ_EXPORT void
7409 zsock_set_rcvbuf (void *self, int rcvbuf);
7410
7411 // Get socket option `linger`.
7412 // Available from libzmq 2.0.0.
7413 // Caller owns return value and must destroy it when done.
7414 CZMQ_EXPORT int
7415 zsock_linger (void *self);
7416
7417 // Set socket option `linger`.
7418 // Available from libzmq 2.0.0.
7419 CZMQ_EXPORT void
7420 zsock_set_linger (void *self, int linger);
7421
7422 // Get socket option `reconnect_ivl`.
7423 // Available from libzmq 2.0.0.
7424 // Caller owns return value and must destroy it when done.
7425 CZMQ_EXPORT int
7426 zsock_reconnect_ivl (void *self);
7427
7428 // Set socket option `reconnect_ivl`.
7429 // Available from libzmq 2.0.0.
7430 CZMQ_EXPORT void
7431 zsock_set_reconnect_ivl (void *self, int reconnect_ivl);
7432
7433 // Get socket option `reconnect_ivl_max`.
7434 // Available from libzmq 2.0.0.
7435 // Caller owns return value and must destroy it when done.
7436 CZMQ_EXPORT int
7437 zsock_reconnect_ivl_max (void *self);
7438
7439 // Set socket option `reconnect_ivl_max`.
7440 // Available from libzmq 2.0.0.
7441 CZMQ_EXPORT void
7442 zsock_set_reconnect_ivl_max (void *self, int reconnect_ivl_max);
7443
7444 // Get socket option `backlog`.
7445 // Available from libzmq 2.0.0.
7446 // Caller owns return value and must destroy it when done.
7447 CZMQ_EXPORT int
7448 zsock_backlog (void *self);
7449
7450 // Set socket option `backlog`.
7451 // Available from libzmq 2.0.0.
7452 CZMQ_EXPORT void
7453 zsock_set_backlog (void *self, int backlog);
7454
7455 // Set socket option `subscribe`.
7456 // Available from libzmq 2.0.0.
7457 CZMQ_EXPORT void
7458 zsock_set_subscribe (void *self, const char *subscribe);
7459
7460 // Set socket option `unsubscribe`.
7461 // Available from libzmq 2.0.0.
7462 CZMQ_EXPORT void
7463 zsock_set_unsubscribe (void *self, const char *unsubscribe);
7464
7465 // Get socket option `type`.
7466 // Available from libzmq 2.0.0.
7467 // Caller owns return value and must destroy it when done.
7468 CZMQ_EXPORT int
7469 zsock_type (void *self);
7470
7471 // Get socket option `rcvmore`.
7472 // Available from libzmq 2.0.0.
7473 // Caller owns return value and must destroy it when done.
7474 CZMQ_EXPORT int
7475 zsock_rcvmore (void *self);
7476
7477 // Get socket option `fd`.
7478 // Available from libzmq 2.0.0.
7479 // Caller owns return value and must destroy it when done.
7480 CZMQ_EXPORT SOCKET
7481 zsock_fd (void *self);
7482
7483 // Get socket option `events`.
7484 // Available from libzmq 2.0.0.
7485 // Caller owns return value and must destroy it when done.
7486 CZMQ_EXPORT int
7487 zsock_events (void *self);
7488
7489 // Self test of this class.
7490 CZMQ_EXPORT void
7491 zsock_test (bool verbose);
7492
7493 #ifdef CZMQ_BUILD_DRAFT_API
7494 // *** Draft method, for development use, may change without warning ***
7495 // Create a SERVER socket. Default action is bind.
7496 CZMQ_EXPORT zsock_t *
7497 zsock_new_server (const char *endpoint);
7498
7499 // *** Draft method, for development use, may change without warning ***
7500 // Create a CLIENT socket. Default action is connect.
7501 CZMQ_EXPORT zsock_t *
7502 zsock_new_client (const char *endpoint);
7503
7504 // *** Draft method, for development use, may change without warning ***
7505 // Create a RADIO socket. Default action is bind.
7506 CZMQ_EXPORT zsock_t *
7507 zsock_new_radio (const char *endpoint);
7508
7509 // *** Draft method, for development use, may change without warning ***
7510 // Create a DISH socket. Default action is connect.
7511 CZMQ_EXPORT zsock_t *
7512 zsock_new_dish (const char *endpoint);
7513
7514 // *** Draft method, for development use, may change without warning ***
7515 // Create a GATHER socket. Default action is bind.
7516 CZMQ_EXPORT zsock_t *
7517 zsock_new_gather (const char *endpoint);
7518
7519 // *** Draft method, for development use, may change without warning ***
7520 // Create a SCATTER socket. Default action is connect.
7521 CZMQ_EXPORT zsock_t *
7522 zsock_new_scatter (const char *endpoint);
7523
7524 // *** Draft method, for development use, may change without warning ***
7525 // Return socket routing ID if any. This returns 0 if the socket is not
7526 // of type ZMQ_SERVER or if no request was already received on it.
7527 CZMQ_EXPORT uint32_t
7528 zsock_routing_id (zsock_t *self);
7529
7530 // *** Draft method, for development use, may change without warning ***
7531 // Set routing ID on socket. The socket MUST be of type ZMQ_SERVER.
7532 // This will be used when sending messages on the socket via the zsock API.
7533 CZMQ_EXPORT void
7534 zsock_set_routing_id (zsock_t *self, uint32_t routing_id);
7535
7536 // *** Draft method, for development use, may change without warning ***
7537 // Join a group for the RADIO-DISH pattern. Call only on ZMQ_DISH.
7538 // Returns 0 if OK, -1 if failed.
7539 CZMQ_EXPORT int
7540 zsock_join (void *self, const char *group);
7541
7542 // *** Draft method, for development use, may change without warning ***
7543 // Leave a group for the RADIO-DISH pattern. Call only on ZMQ_DISH.
7544 // Returns 0 if OK, -1 if failed.
7545 CZMQ_EXPORT int
7546 zsock_leave (void *self, const char *group);
7547
7548 #endif // CZMQ_BUILD_DRAFT_API
7549```
7550Please add '@interface' section in './../src/zsock.c'.
7551
7552This is the class self test code:
7553
7554```c
7555 zsock_t *writer = zsock_new_push ("@tcp://127.0.0.1:5560");
7556 assert (writer);
7557 assert (zsock_resolve (writer) != writer);
7558 assert (streq (zsock_type_str (writer), "PUSH"));
7559
7560 int rc;
7561 #if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (3, 2, 0))
7562 // Check unbind
7563 rc = zsock_unbind (writer, "tcp://127.0.0.1:%d", 5560);
7564 assert (rc == 0);
7565
7566 // In some cases and especially when running under Valgrind, doing
7567 // a bind immediately after an unbind causes an EADDRINUSE error.
7568 // Even a short sleep allows the OS to release the port for reuse.
7569 zclock_sleep (100);
7570
7571 // Bind again
7572 rc = zsock_bind (writer, "tcp://127.0.0.1:%d", 5560);
7573 assert (rc == 5560);
7574 assert (streq (zsock_endpoint (writer), "tcp://127.0.0.1:5560"));
7575 #endif
7576
7577 zsock_t *reader = zsock_new_pull (">tcp://127.0.0.1:5560");
7578 assert (reader);
7579 assert (zsock_resolve (reader) != reader);
7580 assert (streq (zsock_type_str (reader), "PULL"));
7581
7582 // Basic Hello, World
7583 zstr_send (writer, "Hello, World");
7584 zmsg_t *msg = zmsg_recv (reader);
7585 assert (msg);
7586 char *string = zmsg_popstr (msg);
7587 assert (streq (string, "Hello, World"));
7588 free (string);
7589 zmsg_destroy (&msg);
7590
7591 // Test resolve libzmq socket
7592 #if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (3, 2, 0))
7593 void *zmq_ctx = zmq_ctx_new ();
7594 #else
7595 void *zmq_ctx = zmq_ctx_new (1);
7596 #endif
7597 assert (zmq_ctx);
7598 void *zmq_sock = zmq_socket (zmq_ctx, ZMQ_PUB);
7599 assert (zmq_sock);
7600 assert (zsock_resolve (zmq_sock) == zmq_sock);
7601 zmq_close (zmq_sock);
7602 zmq_ctx_term (zmq_ctx);
7603
7604 // Test resolve zsock
7605 zsock_t *resolve = zsock_new_pub("@tcp://127.0.0.1:5561");
7606 assert (resolve);
7607 assert (zsock_resolve (resolve) == resolve->handle);
7608 zsock_destroy (&resolve);
7609
7610 // Test resolve FD
7611 SOCKET fd = zsock_fd (reader);
7612 assert (zsock_resolve ((void *) &fd) == NULL);
7613
7614 // Test binding to ephemeral ports, sequential and random
7615 int port = zsock_bind (writer, "tcp://127.0.0.1:*");
7616 assert (port >= DYNAMIC_FIRST && port <= DYNAMIC_LAST);
7617 port = zsock_bind (writer, "tcp://127.0.0.1:*[50000-]");
7618 assert (port >= 50000 && port <= DYNAMIC_LAST);
7619 port = zsock_bind (writer, "tcp://127.0.0.1:*[-50001]");
7620 assert (port >= DYNAMIC_FIRST && port <= 50001);
7621 port = zsock_bind (writer, "tcp://127.0.0.1:*[60000-60050]");
7622 assert (port >= 60000 && port <= 60050);
7623
7624 port = zsock_bind (writer, "tcp://127.0.0.1:!");
7625 assert (port >= DYNAMIC_FIRST && port <= DYNAMIC_LAST);
7626 port = zsock_bind (writer, "tcp://127.0.0.1:![50000-]");
7627 assert (port >= 50000 && port <= DYNAMIC_LAST);
7628 port = zsock_bind (writer, "tcp://127.0.0.1:![-50001]");
7629 assert (port >= DYNAMIC_FIRST && port <= 50001);
7630 port = zsock_bind (writer, "tcp://127.0.0.1:![60000-60050]");
7631 assert (port >= 60000 && port <= 60050);
7632
7633 // Test zsock_attach method
7634 zsock_t *server = zsock_new (ZMQ_DEALER);
7635 assert (server);
7636 rc = zsock_attach (server, "@inproc://myendpoint,tcp://127.0.0.1:5556,inproc://others", true);
7637 assert (rc == 0);
7638 rc = zsock_attach (server, "", false);
7639 assert (rc == 0);
7640 rc = zsock_attach (server, NULL, true);
7641 assert (rc == 0);
7642 rc = zsock_attach (server, ">a,@b, c,, ", false);
7643 assert (rc == -1);
7644 zsock_destroy (&server);
7645
7646 // Test zsock_endpoint method
7647 rc = zsock_bind (writer, "inproc://test.%s", "writer");
7648 assert (rc == 0);
7649 assert (streq (zsock_endpoint (writer), "inproc://test.writer"));
7650
7651 // Test error state when connecting to an invalid socket type
7652 // ('txp://' instead of 'tcp://', typo intentional)
7653 rc = zsock_connect (reader, "txp://127.0.0.1:5560");
7654 assert (rc == -1);
7655
7656 // Test signal/wait methods
7657 rc = zsock_signal (writer, 123);
7658 assert (rc == 0);
7659 rc = zsock_wait (reader);
7660 assert (rc == 123);
7661
7662 // Test zsock_send/recv pictures
7663 uint8_t number1 = 123;
7664 uint16_t number2 = 123 * 123;
7665 uint32_t number4 = 123 * 123;
7666 number4 *= 123;
7667 uint32_t number4_MAX = UINT32_MAX;
7668 uint64_t number8 = 123 * 123;
7669 number8 *= 123;
7670 number8 *= 123;
7671 uint64_t number8_MAX = UINT64_MAX;
7672
7673 zchunk_t *chunk = zchunk_new ("HELLO", 5);
7674 assert (chunk);
7675 zframe_t *frame = zframe_new ("WORLD", 5);
7676 assert (frame);
7677 zhashx_t *hash = zhashx_new ();
7678 assert (hash);
7679 zuuid_t *uuid = zuuid_new ();
7680 assert (uuid);
7681 zhashx_set_destructor (hash, (zhashx_destructor_fn *) zstr_free);
7682 zhashx_set_duplicator (hash, (zhashx_duplicator_fn *) strdup);
7683 zhashx_insert (hash, "1", "value A");
7684 zhashx_insert (hash, "2", "value B");
7685 char *original = "pointer";
7686
7687 // Test zsock_recv into each supported type
7688 zsock_send (writer, "i124488zsbcfUhp",
7689 -12345, number1, number2, number4, number4_MAX,
7690 number8, number8_MAX,
7691 "This is a string", "ABCDE", 5,
7692 chunk, frame, uuid, hash, original);
7693 char *uuid_str = strdup (zuuid_str (uuid));
7694 zchunk_destroy (&chunk);
7695 zframe_destroy (&frame);
7696 zuuid_destroy (&uuid);
7697 zhashx_destroy (&hash);
7698
7699 int integer;
7700 byte *data;
7701 size_t size;
7702 char *pointer;
7703 number8_MAX = number8 = number4_MAX = number4 = number2 = number1 = 0ULL;
7704 rc = zsock_recv (reader, "i124488zsbcfUhp",
7705 &integer, &number1, &number2, &number4, &number4_MAX,
7706 &number8, &number8_MAX, &string, &data, &size, &chunk,
7707 &frame, &uuid, &hash, &pointer);
7708 assert (rc == 0);
7709 assert (integer == -12345);
7710 assert (number1 == 123);
7711 assert (number2 == 123 * 123);
7712 assert (number4 == 123 * 123 * 123);
7713 assert (number4_MAX == UINT32_MAX);
7714 assert (number8 == 123 * 123 * 123 * 123);
7715 assert (number8_MAX == UINT64_MAX);
7716 assert (streq (string, "This is a string"));
7717 assert (memcmp (data, "ABCDE", 5) == 0);
7718 assert (size == 5);
7719 assert (memcmp (zchunk_data (chunk), "HELLO", 5) == 0);
7720 assert (zchunk_size (chunk) == 5);
7721 assert (streq (uuid_str, zuuid_str (uuid)));
7722 assert (memcmp (zframe_data (frame), "WORLD", 5) == 0);
7723 assert (zframe_size (frame) == 5);
7724 char *value = (char *) zhashx_lookup (hash, "1");
7725 assert (streq (value, "value A"));
7726 value = (char *) zhashx_lookup (hash, "2");
7727 assert (streq (value, "value B"));
7728 assert (original == pointer);
7729 free (string);
7730 free (data);
7731 free (uuid_str);
7732 zframe_destroy (&frame);
7733 zchunk_destroy (&chunk);
7734 zhashx_destroy (&hash);
7735 zuuid_destroy (&uuid);
7736
7737 // Test zsock_recv of short message; this lets us return a failure
7738 // with a status code and then nothing else; the receiver will get
7739 // the status code and NULL/zero for all other values
7740 zsock_send (writer, "i", -1);
7741 zsock_recv (reader, "izsbcfp",
7742 &integer, &string, &data, &size, &chunk, &frame, &pointer);
7743 assert (integer == -1);
7744 assert (string == NULL);
7745 assert (data == NULL);
7746 assert (size == 0);
7747 assert (chunk == NULL);
7748 assert (frame == NULL);
7749 assert (pointer == NULL);
7750
7751 msg = zmsg_new ();
7752 zmsg_addstr (msg, "frame 1");
7753 zmsg_addstr (msg, "frame 2");
7754 zsock_send (writer, "szm", "header", msg);
7755 zmsg_destroy (&msg);
7756
7757 zsock_recv (reader, "szm", &string, &msg);
7758
7759 assert (streq ("header", string));
7760 assert (zmsg_size (msg) == 2);
7761 assert (zframe_streq (zmsg_first (msg), "frame 1"));
7762 assert (zframe_streq (zmsg_next (msg), "frame 2"));
7763 zstr_free (&string);
7764 zmsg_destroy (&msg);
7765
7766 // Test zsock_recv with null arguments
7767 chunk = zchunk_new ("HELLO", 5);
7768 assert (chunk);
7769 frame = zframe_new ("WORLD", 5);
7770 assert (frame);
7771 zsock_send (writer, "izsbcfp",
7772 -12345, "This is a string", "ABCDE", 5, chunk, frame, original);
7773 zframe_destroy (&frame);
7774 zchunk_destroy (&chunk);
7775 zsock_recv (reader, "izsbcfp", &integer, NULL, NULL, NULL, &chunk, NULL, NULL);
7776 assert (integer == -12345);
7777 assert (memcmp (zchunk_data (chunk), "HELLO", 5) == 0);
7778 assert (zchunk_size (chunk) == 5);
7779 zchunk_destroy (&chunk);
7780
7781 // Test zsock_bsend/brecv pictures with binary encoding
7782 frame = zframe_new ("Hello", 5);
7783 chunk = zchunk_new ("World", 5);
7784
7785 msg = zmsg_new ();
7786 zmsg_addstr (msg, "Hello");
7787 zmsg_addstr (msg, "World");
7788
7789 zsock_bsend (writer, "1248sSpcfm",
7790 number1, number2, number4, number8,
7791 "Hello, World",
7792 "Goodbye cruel World!",
7793 original,
7794 chunk, frame, msg);
7795 zchunk_destroy (&chunk);
7796 zframe_destroy (&frame);
7797 zmsg_destroy (&msg);
7798
7799 number8 = number4 = number2 = number1 = 0;
7800 char *longstr;
7801 zsock_brecv (reader, "1248sSpcfm",
7802 &number1, &number2, &number4, &number8,
7803 &string, &longstr,
7804 &pointer,
7805 &chunk, &frame, &msg);
7806 assert (number1 == 123);
7807 assert (number2 == 123 * 123);
7808 assert (number4 == 123 * 123 * 123);
7809 assert (number8 == 123 * 123 * 123 * 123);
7810 assert (streq (string, "Hello, World"));
7811 assert (streq (longstr, "Goodbye cruel World!"));
7812 assert (pointer == original);
7813 zstr_free (&longstr);
7814 zchunk_destroy (&chunk);
7815 zframe_destroy (&frame);
7816 zmsg_destroy (&msg);
7817
7818 #ifdef ZMQ_SERVER
7819
7820 // Test zsock_bsend/brecv pictures with binary encoding on SERVER and CLIENT sockets
7821 server = zsock_new_server ("tcp://127.0.0.1:5561");
7822 assert (server);
7823 zsock_t* client = zsock_new_client ("tcp://127.0.0.1:5561");
7824 assert (client);
7825
7826 // From client to server
7827 chunk = zchunk_new ("World", 5);
7828 zsock_bsend (client, "1248sSpc",
7829 number1, number2, number4, number8,
7830 "Hello, World",
7831 "Goodbye cruel World!",
7832 original,
7833 chunk);
7834 zchunk_destroy (&chunk);
7835
7836 number8 = number4 = number2 = number1 = 0;
7837 zsock_brecv (server, "1248sSpc",
7838 &number1, &number2, &number4, &number8,
7839 &string, &longstr,
7840 &pointer,
7841 &chunk);
7842 assert (number1 == 123);
7843 assert (number2 == 123 * 123);
7844 assert (number4 == 123 * 123 * 123);
7845 assert (number8 == 123 * 123 * 123 * 123);
7846 assert (streq (string, "Hello, World"));
7847 assert (streq (longstr, "Goodbye cruel World!"));
7848 assert (pointer == original);
7849 assert (zsock_routing_id (server));
7850 zstr_free (&longstr);
7851 zchunk_destroy (&chunk);
7852
7853 // From server to client
7854 chunk = zchunk_new ("World", 5);
7855 zsock_bsend (server, "1248sSpc",
7856 number1, number2, number4, number8,
7857 "Hello, World",
7858 "Goodbye cruel World!",
7859 original,
7860 chunk);
7861 zchunk_destroy (&chunk);
7862
7863 number8 = number4 = number2 = number1 = 0;
7864 zsock_brecv (client, "1248sSpc",
7865 &number1, &number2, &number4, &number8,
7866 &string, &longstr,
7867 &pointer,
7868 &chunk);
7869 assert (number1 == 123);
7870 assert (number2 == 123 * 123);
7871 assert (number4 == 123 * 123 * 123);
7872 assert (number8 == 123 * 123 * 123 * 123);
7873 assert (streq (string, "Hello, World"));
7874 assert (streq (longstr, "Goodbye cruel World!"));
7875 assert (pointer == original);
7876 assert (zsock_routing_id (client) == 0);
7877 zstr_free (&longstr);
7878 zchunk_destroy (&chunk);
7879
7880 zsock_destroy (&client);
7881 zsock_destroy (&server);
7882
7883 #endif
7884
7885 #ifdef ZMQ_SCATTER
7886
7887 zsock_t* gather = zsock_new_gather ("inproc://test-gather-scatter");
7888 assert (gather);
7889 zsock_t* scatter = zsock_new_scatter ("inproc://test-gather-scatter");
7890 assert (scatter);
7891
7892 rc = zstr_send (scatter, "HELLO");
7893 assert (rc == 0);
7894
7895 char* message;
7896 message = zstr_recv (gather);
7897 assert (streq(message, "HELLO"));
7898 zstr_free (&message);
7899
7900 zsock_destroy (&gather);
7901 zsock_destroy (&scatter);
7902
7903 #endif
7904
7905 // Check that we can send a zproto format message
7906 zsock_bsend (writer, "1111sS4", 0xAA, 0xA0, 0x02, 0x01, "key", "value", 1234);
7907 zgossip_msg_t *gossip = zgossip_msg_new ();
7908 zgossip_msg_recv (gossip, reader);
7909 assert (zgossip_msg_id (gossip) == ZGOSSIP_MSG_PUBLISH);
7910 zgossip_msg_destroy (&gossip);
7911
7912 zsock_destroy (&reader);
7913 zsock_destroy (&writer);
7914
7915```
7916
7917#### zstr - sending and receiving strings
7918
7919The zstr class provides utility functions for sending and receiving C
7920strings across ØMQ sockets. It sends strings without a terminating null,
7921and appends a null byte on received strings. This class is for simple
7922message sending.
7923
7924 Memory Wire
7925 +-------------+---+ +---+-------------+
7926Send | S t r i n g | 0 | ----> | 6 | S t r i n g |
7927 +-------------+---+ +---+-------------+
7928
7929 Wire Heap
7930 +---+-------------+ +-------------+---+
7931Recv | 6 | S t r i n g | ----> | S t r i n g | 0 |
7932 +---+-------------+ +-------------+---+
7933
7934This is the class interface:
7935
7936```h
7937 // This is a stable class, and may not change except for emergencies. It
7938 // is provided in stable builds.
7939 // This class has draft methods, which may change over time. They are not
7940 // in stable releases, by default. Use --enable-drafts to enable.
7941 // Receive C string from socket. Caller must free returned string using
7942 // zstr_free(). Returns NULL if the context is being terminated or the
7943 // process was interrupted.
7944 // Caller owns return value and must destroy it when done.
7945 CZMQ_EXPORT char *
7946 zstr_recv (void *source);
7947
7948 // Receive a series of strings (until NULL) from multipart data.
7949 // Each string is allocated and filled with string data; if there
7950 // are not enough frames, unallocated strings are set to NULL.
7951 // Returns -1 if the message could not be read, else returns the
7952 // number of strings filled, zero or more. Free each returned string
7953 // using zstr_free(). If not enough strings are provided, remaining
7954 // multipart frames in the message are dropped.
7955 CZMQ_EXPORT int
7956 zstr_recvx (void *source, char **string_p, ...);
7957
7958 // Send a C string to a socket, as a frame. The string is sent without
7959 // trailing null byte; to read this you can use zstr_recv, or a similar
7960 // method that adds a null terminator on the received string. String
7961 // may be NULL, which is sent as "".
7962 CZMQ_EXPORT int
7963 zstr_send (void *dest, const char *string);
7964
7965 // Send a C string to a socket, as zstr_send(), with a MORE flag, so that
7966 // you can send further strings in the same multi-part message.
7967 CZMQ_EXPORT int
7968 zstr_sendm (void *dest, const char *string);
7969
7970 // Send a formatted string to a socket. Note that you should NOT use
7971 // user-supplied strings in the format (they may contain '%' which
7972 // will create security holes).
7973 CZMQ_EXPORT int
7974 zstr_sendf (void *dest, const char *format, ...) CHECK_PRINTF (2);
7975
7976 // Send a formatted string to a socket, as for zstr_sendf(), with a
7977 // MORE flag, so that you can send further strings in the same multi-part
7978 // message.
7979 CZMQ_EXPORT int
7980 zstr_sendfm (void *dest, const char *format, ...) CHECK_PRINTF (2);
7981
7982 // Send a series of strings (until NULL) as multipart data
7983 // Returns 0 if the strings could be sent OK, or -1 on error.
7984 CZMQ_EXPORT int
7985 zstr_sendx (void *dest, const char *string, ...);
7986
7987 // Free a provided string, and nullify the parent pointer. Safe to call on
7988 // a null pointer.
7989 CZMQ_EXPORT void
7990 zstr_free (char **string_p);
7991
7992 // Self test of this class.
7993 CZMQ_EXPORT void
7994 zstr_test (bool verbose);
7995
7996 #ifdef CZMQ_BUILD_DRAFT_API
7997 // *** Draft method, for development use, may change without warning ***
7998 // Accepts a void pointer and returns a fresh character string. If source
7999 // is null, returns an empty string.
8000 // Caller owns return value and must destroy it when done.
8001 CZMQ_EXPORT char *
8002 zstr_str (void *source);
8003
8004 #endif // CZMQ_BUILD_DRAFT_API
8005```
8006Please add '@interface' section in './../src/zstr.c'.
8007
8008This is the class self test code:
8009
8010```c
8011 // Create two PAIR sockets and connect over inproc
8012 zsock_t *output = zsock_new_pair ("@inproc://zstr.test");
8013 assert (output);
8014 zsock_t *input = zsock_new_pair (">inproc://zstr.test");
8015 assert (input);
8016
8017 // Send ten strings, five strings with MORE flag and then END
8018 int string_nbr;
8019 for (string_nbr = 0; string_nbr < 10; string_nbr++)
8020 zstr_sendf (output, "this is string %d", string_nbr);
8021 zstr_sendx (output, "This", "is", "almost", "the", "very", "END", NULL);
8022
8023 // Read and count until we receive END
8024 string_nbr = 0;
8025 for (string_nbr = 0;; string_nbr++) {
8026 char *string = zstr_recv (input);
8027 assert (string);
8028 if (streq (string, "END")) {
8029 zstr_free (&string);
8030 break;
8031 }
8032 zstr_free (&string);
8033 }
8034 assert (string_nbr == 15);
8035
8036 zsock_destroy (&input);
8037 zsock_destroy (&output);
8038
8039 #if defined (ZMQ_SERVER)
8040 // Test SERVER/CLIENT over zstr
8041 zsock_t *server = zsock_new_server ("inproc://zstr-test-routing");
8042 zsock_t *client = zsock_new_client ("inproc://zstr-test-routing");;
8043 assert (server);
8044 assert (client);
8045
8046 // Try normal ping-pong to check reply routing ID
8047 int rc = zstr_send (client, "Hello");
8048 assert (rc == 0);
8049 char *request = zstr_recv (server);
8050 assert (streq (request, "Hello"));
8051 assert (zsock_routing_id (server));
8052 free (request);
8053
8054 rc = zstr_send (server, "World");
8055 assert (rc == 0);
8056 char *reply = zstr_recv (client);
8057 assert (streq (reply, "World"));
8058 free (reply);
8059
8060 rc = zstr_sendf (server, "%s", "World");
8061 assert (rc == 0);
8062 reply = zstr_recv (client);
8063 assert (streq (reply, "World"));
8064 free (reply);
8065
8066 // Try ping-pong using sendx and recx
8067 rc = zstr_sendx (client, "Hello", NULL);
8068 assert (rc == 0);
8069 rc = zstr_recvx (server, &request, NULL);
8070 assert (rc >= 0);
8071 assert (streq (request, "Hello"));
8072 free (request);
8073
8074 rc = zstr_sendx (server, "World", NULL);
8075 assert (rc == 0);
8076 rc = zstr_recvx (client, &reply, NULL);
8077 assert (rc >= 0);
8078 assert (streq (reply, "World"));
8079 free (reply);
8080
8081 // Client and server disallow multipart
8082 rc = zstr_sendm (client, "Hello");
8083 assert (rc == -1);
8084 rc = zstr_sendm (server, "World");
8085 assert (rc == -1);
8086
8087 zsock_destroy (&client);
8088 zsock_destroy (&server);
8089 #endif
8090
8091 #if defined (__WINDOWS__)
8092 zsys_shutdown();
8093 #endif
8094```
8095
8096#### zsys - system-level methods
8097
8098The zsys class provides a portable wrapper for system calls. We collect
8099them here to reduce the number of weird #ifdefs in other classes. As far
8100as possible, the bulk of CZMQ classes are fully portable.
8101
8102Please add '@discuss' section in './../src/zsys.c'.
8103
8104This is the class interface:
8105
8106```h
8107 // This is a stable class, and may not change except for emergencies. It
8108 // is provided in stable builds.
8109 // Callback for interrupt signal handler
8110 typedef void (zsys_handler_fn) (
8111 int signal_value);
8112
8113 // Initialize CZMQ zsys layer; this happens automatically when you create
8114 // a socket or an actor; however this call lets you force initialization
8115 // earlier, so e.g. logging is properly set-up before you start working.
8116 // Not threadsafe, so call only from main thread. Safe to call multiple
8117 // times. Returns global CZMQ context.
8118 CZMQ_EXPORT void *
8119 zsys_init (void);
8120
8121 // Optionally shut down the CZMQ zsys layer; this normally happens automatically
8122 // when the process exits; however this call lets you force a shutdown
8123 // earlier, avoiding any potential problems with atexit() ordering, especially
8124 // with Windows dlls.
8125 CZMQ_EXPORT void
8126 zsys_shutdown (void);
8127
8128 // Get a new ZMQ socket, automagically creating a ZMQ context if this is
8129 // the first time. Caller is responsible for destroying the ZMQ socket
8130 // before process exits, to avoid a ZMQ deadlock. Note: you should not use
8131 // this method in CZMQ apps, use zsock_new() instead.
8132 // *** This is for CZMQ internal use only and may change arbitrarily ***
8133 CZMQ_EXPORT void *
8134 zsys_socket (int type, const char *filename, size_t line_nbr);
8135
8136 // Destroy/close a ZMQ socket. You should call this for every socket you
8137 // create using zsys_socket().
8138 // *** This is for CZMQ internal use only and may change arbitrarily ***
8139 CZMQ_EXPORT int
8140 zsys_close (void *handle, const char *filename, size_t line_nbr);
8141
8142 // Return ZMQ socket name for socket type
8143 // *** This is for CZMQ internal use only and may change arbitrarily ***
8144 CZMQ_EXPORT char *
8145 zsys_sockname (int socktype);
8146
8147 // Create a pipe, which consists of two PAIR sockets connected over inproc.
8148 // The pipe is configured to use the zsys_pipehwm setting. Returns the
8149 // frontend socket successful, NULL if failed.
8150 CZMQ_EXPORT zsock_t *
8151 zsys_create_pipe (zsock_t **backend_p);
8152
8153 // Set interrupt handler; this saves the default handlers so that a
8154 // zsys_handler_reset () can restore them. If you call this multiple times
8155 // then the last handler will take affect. If handler_fn is NULL, disables
8156 // default SIGINT/SIGTERM handling in CZMQ.
8157 CZMQ_EXPORT void
8158 zsys_handler_set (zsys_handler_fn *handler_fn);
8159
8160 // Reset interrupt handler, call this at exit if needed
8161 CZMQ_EXPORT void
8162 zsys_handler_reset (void);
8163
8164 // Set default interrupt handler, so Ctrl-C or SIGTERM will set
8165 // zsys_interrupted. Idempotent; safe to call multiple times.
8166 // *** This is for CZMQ internal use only and may change arbitrarily ***
8167 CZMQ_EXPORT void
8168 zsys_catch_interrupts (void);
8169
8170 // Return 1 if file exists, else zero
8171 CZMQ_EXPORT bool
8172 zsys_file_exists (const char *filename);
8173
8174 // Return file modification time. Returns 0 if the file does not exist.
8175 CZMQ_EXPORT time_t
8176 zsys_file_modified (const char *filename);
8177
8178 // Return file mode; provides at least support for the POSIX S_ISREG(m)
8179 // and S_ISDIR(m) macros and the S_IRUSR and S_IWUSR bits, on all boxes.
8180 // Returns a mode_t cast to int, or -1 in case of error.
8181 CZMQ_EXPORT int
8182 zsys_file_mode (const char *filename);
8183
8184 // Delete file. Does not complain if the file is absent
8185 CZMQ_EXPORT int
8186 zsys_file_delete (const char *filename);
8187
8188 // Check if file is 'stable'
8189 CZMQ_EXPORT bool
8190 zsys_file_stable (const char *filename);
8191
8192 // Create a file path if it doesn't exist. The file path is treated as
8193 // printf format.
8194 CZMQ_EXPORT int
8195 zsys_dir_create (const char *pathname, ...);
8196
8197 // Remove a file path if empty; the pathname is treated as printf format.
8198 CZMQ_EXPORT int
8199 zsys_dir_delete (const char *pathname, ...);
8200
8201 // Move to a specified working directory. Returns 0 if OK, -1 if this failed.
8202 CZMQ_EXPORT int
8203 zsys_dir_change (const char *pathname);
8204
8205 // Set private file creation mode; all files created from here will be
8206 // readable/writable by the owner only.
8207 CZMQ_EXPORT void
8208 zsys_file_mode_private (void);
8209
8210 // Reset default file creation mode; all files created from here will use
8211 // process file mode defaults.
8212 CZMQ_EXPORT void
8213 zsys_file_mode_default (void);
8214
8215 // Return the CZMQ version for run-time API detection; returns version
8216 // number into provided fields, providing reference isn't null in each case.
8217 CZMQ_EXPORT void
8218 zsys_version (int *major, int *minor, int *patch);
8219
8220 // Format a string using printf formatting, returning a freshly allocated
8221 // buffer. If there was insufficient memory, returns NULL. Free the returned
8222 // string using zstr_free().
8223 CZMQ_EXPORT char *
8224 zsys_sprintf (const char *format, ...);
8225
8226 // Format a string with a va_list argument, returning a freshly allocated
8227 // buffer. If there was insufficient memory, returns NULL. Free the returned
8228 // string using zstr_free().
8229 CZMQ_EXPORT char *
8230 zsys_vprintf (const char *format, va_list argptr);
8231
8232 // Create UDP beacon socket; if the routable option is true, uses
8233 // multicast (not yet implemented), else uses broadcast. This method
8234 // and related ones might _eventually_ be moved to a zudp class.
8235 // *** This is for CZMQ internal use only and may change arbitrarily ***
8236 CZMQ_EXPORT SOCKET
8237 zsys_udp_new (bool routable);
8238
8239 // Close a UDP socket
8240 // *** This is for CZMQ internal use only and may change arbitrarily ***
8241 CZMQ_EXPORT int
8242 zsys_udp_close (SOCKET handle);
8243
8244 // Send zframe to UDP socket, return -1 if sending failed due to
8245 // interface having disappeared (happens easily with WiFi)
8246 // *** This is for CZMQ internal use only and may change arbitrarily ***
8247 CZMQ_EXPORT int
8248 zsys_udp_send (SOCKET udpsock, zframe_t *frame, inaddr_t *address, int addrlen);
8249
8250 // Receive zframe from UDP socket, and set address of peer that sent it
8251 // The peername must be a char [INET_ADDRSTRLEN] array if IPv6 is disabled or
8252 // NI_MAXHOST if it's enabled. Returns NULL when failing to get peer address.
8253 // *** This is for CZMQ internal use only and may change arbitrarily ***
8254 CZMQ_EXPORT zframe_t *
8255 zsys_udp_recv (SOCKET udpsock, char *peername, int peerlen);
8256
8257 // Handle an I/O error on some socket operation; will report and die on
8258 // fatal errors, and continue silently on "try again" errors.
8259 // *** This is for CZMQ internal use only and may change arbitrarily ***
8260 CZMQ_EXPORT void
8261 zsys_socket_error (const char *reason);
8262
8263 // Return current host name, for use in public tcp:// endpoints. Caller gets
8264 // a freshly allocated string, should free it using zstr_free(). If the host
8265 // name is not resolvable, returns NULL.
8266 CZMQ_EXPORT char *
8267 zsys_hostname (void);
8268
8269 // Move the current process into the background. The precise effect depends
8270 // on the operating system. On POSIX boxes, moves to a specified working
8271 // directory (if specified), closes all file handles, reopens stdin, stdout,
8272 // and stderr to the null device, and sets the process to ignore SIGHUP. On
8273 // Windows, does nothing. Returns 0 if OK, -1 if there was an error.
8274 CZMQ_EXPORT int
8275 zsys_daemonize (const char *workdir);
8276
8277 // Drop the process ID into the lockfile, with exclusive lock, and switch
8278 // the process to the specified group and/or user. Any of the arguments
8279 // may be null, indicating a no-op. Returns 0 on success, -1 on failure.
8280 // Note if you combine this with zsys_daemonize, run after, not before
8281 // that method, or the lockfile will hold the wrong process ID.
8282 CZMQ_EXPORT int
8283 zsys_run_as (const char *lockfile, const char *group, const char *user);
8284
8285 // Returns true if the underlying libzmq supports CURVE security.
8286 // Uses a heuristic probe according to the version of libzmq being used.
8287 CZMQ_EXPORT bool
8288 zsys_has_curve (void);
8289
8290 // Configure the number of I/O threads that ZeroMQ will use. A good
8291 // rule of thumb is one thread per gigabit of traffic in or out. The
8292 // default is 1, sufficient for most applications. If the environment
8293 // variable ZSYS_IO_THREADS is defined, that provides the default.
8294 // Note that this method is valid only before any socket is created.
8295 CZMQ_EXPORT void
8296 zsys_set_io_threads (size_t io_threads);
8297
8298 // Configure the scheduling policy of the ZMQ context thread pool.
8299 // Not available on Windows. See the sched_setscheduler man page or sched.h
8300 // for more information. If the environment variable ZSYS_THREAD_SCHED_POLICY
8301 // is defined, that provides the default.
8302 // Note that this method is valid only before any socket is created.
8303 CZMQ_EXPORT void
8304 zsys_set_thread_sched_policy (int policy);
8305
8306 // Configure the scheduling priority of the ZMQ context thread pool.
8307 // Not available on Windows. See the sched_setscheduler man page or sched.h
8308 // for more information. If the environment variable ZSYS_THREAD_PRIORITY is
8309 // defined, that provides the default.
8310 // Note that this method is valid only before any socket is created.
8311 CZMQ_EXPORT void
8312 zsys_set_thread_priority (int priority);
8313
8314 // Configure the number of sockets that ZeroMQ will allow. The default
8315 // is 1024. The actual limit depends on the system, and you can query it
8316 // by using zsys_socket_limit (). A value of zero means "maximum".
8317 // Note that this method is valid only before any socket is created.
8318 CZMQ_EXPORT void
8319 zsys_set_max_sockets (size_t max_sockets);
8320
8321 // Return maximum number of ZeroMQ sockets that the system will support.
8322 CZMQ_EXPORT size_t
8323 zsys_socket_limit (void);
8324
8325 // Configure the maximum allowed size of a message sent.
8326 // The default is INT_MAX.
8327 CZMQ_EXPORT void
8328 zsys_set_max_msgsz (int max_msgsz);
8329
8330 // Return maximum message size.
8331 CZMQ_EXPORT int
8332 zsys_max_msgsz (void);
8333
8334 // Configure the default linger timeout in msecs for new zsock instances.
8335 // You can also set this separately on each zsock_t instance. The default
8336 // linger time is zero, i.e. any pending messages will be dropped. If the
8337 // environment variable ZSYS_LINGER is defined, that provides the default.
8338 // Note that process exit will typically be delayed by the linger time.
8339 CZMQ_EXPORT void
8340 zsys_set_linger (size_t linger);
8341
8342 // Configure the default outgoing pipe limit (HWM) for new zsock instances.
8343 // You can also set this separately on each zsock_t instance. The default
8344 // HWM is 1,000, on all versions of ZeroMQ. If the environment variable
8345 // ZSYS_SNDHWM is defined, that provides the default. Note that a value of
8346 // zero means no limit, i.e. infinite memory consumption.
8347 CZMQ_EXPORT void
8348 zsys_set_sndhwm (size_t sndhwm);
8349
8350 // Configure the default incoming pipe limit (HWM) for new zsock instances.
8351 // You can also set this separately on each zsock_t instance. The default
8352 // HWM is 1,000, on all versions of ZeroMQ. If the environment variable
8353 // ZSYS_RCVHWM is defined, that provides the default. Note that a value of
8354 // zero means no limit, i.e. infinite memory consumption.
8355 CZMQ_EXPORT void
8356 zsys_set_rcvhwm (size_t rcvhwm);
8357
8358 // Configure the default HWM for zactor internal pipes; this is set on both
8359 // ends of the pipe, for outgoing messages only (sndhwm). The default HWM is
8360 // 1,000, on all versions of ZeroMQ. If the environment var ZSYS_ACTORHWM is
8361 // defined, that provides the default. Note that a value of zero means no
8362 // limit, i.e. infinite memory consumption.
8363 CZMQ_EXPORT void
8364 zsys_set_pipehwm (size_t pipehwm);
8365
8366 // Return the HWM for zactor internal pipes.
8367 CZMQ_EXPORT size_t
8368 zsys_pipehwm (void);
8369
8370 // Configure use of IPv6 for new zsock instances. By default sockets accept
8371 // and make only IPv4 connections. When you enable IPv6, sockets will accept
8372 // and connect to both IPv4 and IPv6 peers. You can override the setting on
8373 // each zsock_t instance. The default is IPv4 only (ipv6 set to 0). If the
8374 // environment variable ZSYS_IPV6 is defined (as 1 or 0), this provides the
8375 // default. Note: has no effect on ZMQ v2.
8376 CZMQ_EXPORT void
8377 zsys_set_ipv6 (int ipv6);
8378
8379 // Return use of IPv6 for zsock instances.
8380 CZMQ_EXPORT int
8381 zsys_ipv6 (void);
8382
8383 // Set network interface name to use for broadcasts, particularly zbeacon.
8384 // This lets the interface be configured for test environments where required.
8385 // For example, on Mac OS X, zbeacon cannot bind to 255.255.255.255 which is
8386 // the default when there is no specified interface. If the environment
8387 // variable ZSYS_INTERFACE is set, use that as the default interface name.
8388 // Setting the interface to "*" means "use all available interfaces".
8389 CZMQ_EXPORT void
8390 zsys_set_interface (const char *value);
8391
8392 // Return network interface to use for broadcasts, or "" if none was set.
8393 CZMQ_EXPORT const char *
8394 zsys_interface (void);
8395
8396 // Set IPv6 address to use zbeacon socket, particularly for receiving zbeacon.
8397 // This needs to be set IPv6 is enabled as IPv6 can have multiple addresses
8398 // on a given interface. If the environment variable ZSYS_IPV6_ADDRESS is set,
8399 // use that as the default IPv6 address.
8400 CZMQ_EXPORT void
8401 zsys_set_ipv6_address (const char *value);
8402
8403 // Return IPv6 address to use for zbeacon reception, or "" if none was set.
8404 CZMQ_EXPORT const char *
8405 zsys_ipv6_address (void);
8406
8407 // Set IPv6 milticast address to use for sending zbeacon messages. This needs
8408 // to be set if IPv6 is enabled. If the environment variable
8409 // ZSYS_IPV6_MCAST_ADDRESS is set, use that as the default IPv6 multicast
8410 // address.
8411 CZMQ_EXPORT void
8412 zsys_set_ipv6_mcast_address (const char *value);
8413
8414 // Return IPv6 multicast address to use for sending zbeacon, or "" if none was
8415 // set.
8416 CZMQ_EXPORT const char *
8417 zsys_ipv6_mcast_address (void);
8418
8419 // Configure the automatic use of pre-allocated FDs when creating new sockets.
8420 // If 0 (default), nothing will happen. Else, when a new socket is bound, the
8421 // system API will be used to check if an existing pre-allocated FD with a
8422 // matching port (if TCP) or path (if IPC) exists, and if it does it will be
8423 // set via the ZMQ_USE_FD socket option so that the library will use it
8424 // instead of creating a new socket.
8425 CZMQ_EXPORT void
8426 zsys_set_auto_use_fd (int auto_use_fd);
8427
8428 // Return use of automatic pre-allocated FDs for zsock instances.
8429 CZMQ_EXPORT int
8430 zsys_auto_use_fd (void);
8431
8432 // Set log identity, which is a string that prefixes all log messages sent
8433 // by this process. The log identity defaults to the environment variable
8434 // ZSYS_LOGIDENT, if that is set.
8435 CZMQ_EXPORT void
8436 zsys_set_logident (const char *value);
8437
8438 // Set stream to receive log traffic. By default, log traffic is sent to
8439 // stdout. If you set the stream to NULL, no stream will receive the log
8440 // traffic (it may still be sent to the system facility).
8441 CZMQ_EXPORT void
8442 zsys_set_logstream (FILE *stream);
8443
8444 // Sends log output to a PUB socket bound to the specified endpoint. To
8445 // collect such log output, create a SUB socket, subscribe to the traffic
8446 // you care about, and connect to the endpoint. Log traffic is sent as a
8447 // single string frame, in the same format as when sent to stdout. The
8448 // log system supports a single sender; multiple calls to this method will
8449 // bind the same sender to multiple endpoints. To disable the sender, call
8450 // this method with a null argument.
8451 CZMQ_EXPORT void
8452 zsys_set_logsender (const char *endpoint);
8453
8454 // Enable or disable logging to the system facility (syslog on POSIX boxes,
8455 // event log on Windows). By default this is disabled.
8456 CZMQ_EXPORT void
8457 zsys_set_logsystem (bool logsystem);
8458
8459 // Log error condition - highest priority
8460 CZMQ_EXPORT void
8461 zsys_error (const char *format, ...);
8462
8463 // Log warning condition - high priority
8464 CZMQ_EXPORT void
8465 zsys_warning (const char *format, ...);
8466
8467 // Log normal, but significant, condition - normal priority
8468 CZMQ_EXPORT void
8469 zsys_notice (const char *format, ...);
8470
8471 // Log informational message - low priority
8472 CZMQ_EXPORT void
8473 zsys_info (const char *format, ...);
8474
8475 // Log debug-level message - lowest priority
8476 CZMQ_EXPORT void
8477 zsys_debug (const char *format, ...);
8478
8479 // Self test of this class.
8480 CZMQ_EXPORT void
8481 zsys_test (bool verbose);
8482
8483```
8484Please add '@interface' section in './../src/zsys.c'.
8485
8486This is the class self test code:
8487
8488```c
8489 zsys_catch_interrupts ();
8490
8491 // Check capabilities without using the return value
8492 int rc = zsys_has_curve ();
8493
8494 if (verbose) {
8495 char *hostname = zsys_hostname ();
8496 zsys_info ("host name is %s", hostname);
8497 free (hostname);
8498 zsys_info ("system limit is %zu ZeroMQ sockets", zsys_socket_limit ());
8499 }
8500 zsys_set_linger (0);
8501 zsys_set_sndhwm (1000);
8502 zsys_set_rcvhwm (1000);
8503 zsys_set_pipehwm (2500);
8504 assert (zsys_pipehwm () == 2500);
8505 zsys_set_ipv6 (0);
8506 zsys_set_thread_priority (-1);
8507 zsys_set_thread_sched_policy (-1);
8508
8509 // Test pipe creation
8510 zsock_t *pipe_back;
8511 zsock_t *pipe_front = zsys_create_pipe (&pipe_back);
8512 zstr_send (pipe_front, "Hello");
8513 char *string = zstr_recv (pipe_back);
8514 assert (streq (string, "Hello"));
8515 free (string);
8516 zsock_destroy (&pipe_back);
8517 zsock_destroy (&pipe_front);
8518
8519 // Test file manipulation
8520 rc = zsys_file_delete ("nosuchfile");
8521 assert (rc == -1);
8522
8523 bool rc_bool = zsys_file_exists ("nosuchfile");
8524 assert (rc_bool != true);
8525
8526 rc = (int) zsys_file_size ("nosuchfile");
8527 assert (rc == -1);
8528
8529 time_t when = zsys_file_modified (".");
8530 assert (when > 0);
8531
8532 int mode = zsys_file_mode (".");
8533 assert (S_ISDIR (mode));
8534 assert (mode & S_IRUSR);
8535 assert (mode & S_IWUSR);
8536
8537 zsys_file_mode_private ();
8538 rc = zsys_dir_create ("%s/%s", ".", ".testsys/subdir");
8539 assert (rc == 0);
8540 when = zsys_file_modified ("./.testsys/subdir");
8541 assert (when > 0);
8542 assert (!zsys_file_stable ("./.testsys/subdir"));
8543 rc = zsys_dir_delete ("%s/%s", ".", ".testsys/subdir");
8544 assert (rc == 0);
8545 rc = zsys_dir_delete ("%s/%s", ".", ".testsys");
8546 assert (rc == 0);
8547 zsys_file_mode_default ();
8548 assert (zsys_dir_change (".") == 0);
8549
8550 int major, minor, patch;
8551 zsys_version (&major, &minor, &patch);
8552 assert (major == CZMQ_VERSION_MAJOR);
8553 assert (minor == CZMQ_VERSION_MINOR);
8554 assert (patch == CZMQ_VERSION_PATCH);
8555
8556 string = zsys_sprintf ("%s %02x", "Hello", 16);
8557 assert (streq (string, "Hello 10"));
8558 free (string);
8559
8560 char *str64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,.";
8561 int num10 = 1234567890;
8562 string = zsys_sprintf ("%s%s%s%s%d", str64, str64, str64, str64, num10);
8563 assert (strlen (string) == (4 * 64 + 10));
8564 free (string);
8565
8566 // Test logging system
8567 zsys_set_logident ("czmq_selftest");
8568 zsys_set_logsender ("inproc://logging");
8569 void *logger = zsys_socket (ZMQ_SUB, NULL, 0);
8570 assert (logger);
8571 rc = zmq_connect (logger, "inproc://logging");
8572 assert (rc == 0);
8573 rc = zmq_setsockopt (logger, ZMQ_SUBSCRIBE, "", 0);
8574 assert (rc == 0);
8575
8576 if (verbose) {
8577 zsys_error ("This is an %s message", "error");
8578 zsys_warning ("This is a %s message", "warning");
8579 zsys_notice ("This is a %s message", "notice");
8580 zsys_info ("This is a %s message", "info");
8581 zsys_debug ("This is a %s message", "debug");
8582 zsys_set_logident ("hello, world");
8583 zsys_info ("This is a %s message", "info");
8584 zsys_debug ("This is a %s message", "debug");
8585
8586 // Check that logsender functionality is working
8587 char *received = zstr_recv (logger);
8588 assert (received);
8589 zstr_free (&received);
8590 }
8591 zsys_close (logger, NULL, 0);
8592```
8593
8594#### ztimerset - timer set
8595
8596ztimerset - timer set
8597
8598Please add '@discuss' section in './../src/ztimerset.c'.
8599
8600This is the class interface:
8601
8602```h
8603 // This is a draft class, and may change without notice. It is disabled in
8604 // stable builds by default. If you use this in applications, please ask
8605 // for it to be pushed to stable state. Use --enable-drafts to enable.
8606 #ifdef CZMQ_BUILD_DRAFT_API
8607 // Callback function for timer event.
8608 typedef void (ztimerset_fn) (
8609 int timer_id, void *arg);
8610
8611 // *** Draft method, for development use, may change without warning ***
8612 // Create new timer set.
8613 CZMQ_EXPORT ztimerset_t *
8614 ztimerset_new (void);
8615
8616 // *** Draft method, for development use, may change without warning ***
8617 // Destroy a timer set
8618 CZMQ_EXPORT void
8619 ztimerset_destroy (ztimerset_t **self_p);
8620
8621 // *** Draft method, for development use, may change without warning ***
8622 // Add a timer to the set. Returns timer id if OK, -1 on failure.
8623 CZMQ_EXPORT int
8624 ztimerset_add (ztimerset_t *self, size_t interval, ztimerset_fn handler, void *arg);
8625
8626 // *** Draft method, for development use, may change without warning ***
8627 // Cancel a timer. Returns 0 if OK, -1 on failure.
8628 CZMQ_EXPORT int
8629 ztimerset_cancel (ztimerset_t *self, int timer_id);
8630
8631 // *** Draft method, for development use, may change without warning ***
8632 // Set timer interval. Returns 0 if OK, -1 on failure.
8633 // This method is slow, canceling the timer and adding a new one yield better performance.
8634 CZMQ_EXPORT int
8635 ztimerset_set_interval (ztimerset_t *self, int timer_id, size_t interval);
8636
8637 // *** Draft method, for development use, may change without warning ***
8638 // Reset timer to start interval counting from current time. Returns 0 if OK, -1 on failure.
8639 // This method is slow, canceling the timer and adding a new one yield better performance.
8640 CZMQ_EXPORT int
8641 ztimerset_reset (ztimerset_t *self, int timer_id);
8642
8643 // *** Draft method, for development use, may change without warning ***
8644 // Return the time until the next interval.
8645 // Should be used as timeout parameter for the zpoller wait method.
8646 // The timeout is in msec.
8647 CZMQ_EXPORT int
8648 ztimerset_timeout (ztimerset_t *self);
8649
8650 // *** Draft method, for development use, may change without warning ***
8651 // Invoke callback function of all timers which their interval has elapsed.
8652 // Should be call after zpoller wait method.
8653 // Returns 0 if OK, -1 on failure.
8654 CZMQ_EXPORT int
8655 ztimerset_execute (ztimerset_t *self);
8656
8657 // *** Draft method, for development use, may change without warning ***
8658 // Self test of this class.
8659 CZMQ_EXPORT void
8660 ztimerset_test (bool verbose);
8661
8662 #endif // CZMQ_BUILD_DRAFT_API
8663```
8664Please add '@interface' section in './../src/ztimerset.c'.
8665
8666This is the class self test code:
8667
8668```c
8669 // Simple create/destroy test
8670 ztimerset_t *self = ztimerset_new ();
8671 assert (self);
8672
8673 // Adding timer
8674 bool timer_invoked = false;
8675 int timer_id = ztimerset_add (self, 100, handler, &timer_invoked);
8676 assert (timer_id != -1);
8677 int rc = ztimerset_execute (self);
8678 assert (rc == 0);
8679 assert (!timer_invoked);
8680 int timeout = ztimerset_timeout (self);
8681 assert (timeout > 0);
8682 zclock_sleep (timeout);
8683 rc = ztimerset_execute (self);
8684 assert (rc == 0);
8685 assert (timer_invoked);
8686
8687 // Cancel timer
8688 timeout = ztimerset_timeout (self);
8689 assert (timeout > 0);
8690 rc = ztimerset_cancel (self, timer_id);
8691 assert (rc == 0);
8692 timeout = ztimerset_timeout (self);
8693 assert(timeout == -1);
8694
8695 // Reset a timer
8696 timer_id = ztimerset_add (self, 100, handler, &timer_invoked);
8697 assert (timer_id != -1);
8698 timeout = ztimerset_timeout (self);
8699 assert (timeout > 0);
8700 zclock_sleep (timeout / 2);
8701 timeout = ztimerset_timeout (self);
8702 rc = ztimerset_reset(self, timer_id);
8703 assert (rc == 0);
8704 int timeout2 = ztimerset_timeout (self);
8705 assert (timeout2 > timeout);
8706 rc = ztimerset_cancel (self, timer_id);
8707 assert (rc == 0);
8708
8709 // Set interval
8710 timer_id = ztimerset_add (self, 100, handler, &timer_invoked);
8711 assert (timer_id != -1);
8712 timeout = ztimerset_timeout (self);
8713 rc = ztimerset_set_interval(self, timer_id, 200);
8714 timeout2 = ztimerset_timeout (self);
8715 assert (timeout2 > timeout);
8716
8717 ztimerset_destroy (&self);
8718
8719 #if defined (__WINDOWS__)
8720 zsys_shutdown();
8721 #endif
8722```
8723
8724#### ztrie - simple trie for tokenizable strings
8725
8726This is a variant of a trie or prefix tree where all the descendants of a
8727node have a common prefix of the string associated with that node. This
8728implementation is specialized for strings that can be tokenized by a delimiter
8729like a URL, URI or URN. Routes in the tree can be matched by regular expressions
8730and by using capturing groups parts of a matched route can be easily obtained.
8731
8732Note that the performance for pure string based matching is okay but on short
8733strings zhash and zhashx are 3-4 times faster.
8734
8735This is the class interface:
8736
8737```h
8738 // This is a draft class, and may change without notice. It is disabled in
8739 // stable builds by default. If you use this in applications, please ask
8740 // for it to be pushed to stable state. Use --enable-drafts to enable.
8741 #ifdef CZMQ_BUILD_DRAFT_API
8742 // Callback function for ztrie_node to destroy node data.
8743 typedef void (ztrie_destroy_data_fn) (
8744 void **data);
8745
8746 // *** Draft method, for development use, may change without warning ***
8747 // Creates a new ztrie.
8748 CZMQ_EXPORT ztrie_t *
8749 ztrie_new (char delimiter);
8750
8751 // *** Draft method, for development use, may change without warning ***
8752 // Destroy the ztrie.
8753 CZMQ_EXPORT void
8754 ztrie_destroy (ztrie_t **self_p);
8755
8756 // *** Draft method, for development use, may change without warning ***
8757 // Inserts a new route into the tree and attaches the data. Returns -1
8758 // if the route already exists, otherwise 0. This method takes ownership of
8759 // the provided data if a destroy_data_fn is provided.
8760 CZMQ_EXPORT int
8761 ztrie_insert_route (ztrie_t *self, const char *path, void *data, ztrie_destroy_data_fn destroy_data_fn);
8762
8763 // *** Draft method, for development use, may change without warning ***
8764 // Removes a route from the trie and destroys its data. Returns -1 if the
8765 // route does not exists, otherwise 0.
8766 // the start of the list call zlist_first (). Advances the cursor.
8767 CZMQ_EXPORT int
8768 ztrie_remove_route (ztrie_t *self, const char *path);
8769
8770 // *** Draft method, for development use, may change without warning ***
8771 // Returns true if the path matches a route in the tree, otherwise false.
8772 CZMQ_EXPORT bool
8773 ztrie_matches (ztrie_t *self, const char *path);
8774
8775 // *** Draft method, for development use, may change without warning ***
8776 // Returns the data of a matched route from last ztrie_matches. If the path
8777 // did not match, returns NULL. Do not delete the data as it's owned by
8778 // ztrie.
8779 CZMQ_EXPORT void *
8780 ztrie_hit_data (ztrie_t *self);
8781
8782 // *** Draft method, for development use, may change without warning ***
8783 // Returns the count of parameters that a matched route has.
8784 CZMQ_EXPORT size_t
8785 ztrie_hit_parameter_count (ztrie_t *self);
8786
8787 // *** Draft method, for development use, may change without warning ***
8788 // Returns the parameters of a matched route with named regexes from last
8789 // ztrie_matches. If the path did not match or the route did not contain any
8790 // named regexes, returns NULL.
8791 CZMQ_EXPORT zhashx_t *
8792 ztrie_hit_parameters (ztrie_t *self);
8793
8794 // *** Draft method, for development use, may change without warning ***
8795 // Returns the asterisk matched part of a route, if there has been no match
8796 // or no asterisk match, returns NULL.
8797 CZMQ_EXPORT const char *
8798 ztrie_hit_asterisk_match (ztrie_t *self);
8799
8800 // *** Draft method, for development use, may change without warning ***
8801 // Print the trie
8802 CZMQ_EXPORT void
8803 ztrie_print (ztrie_t *self);
8804
8805 // *** Draft method, for development use, may change without warning ***
8806 // Self test of this class.
8807 CZMQ_EXPORT void
8808 ztrie_test (bool verbose);
8809
8810 #endif // CZMQ_BUILD_DRAFT_API
8811```
8812Please add '@interface' section in './../src/ztrie.c'.
8813
8814This is the class self test code:
8815
8816```c
8817 // Create a new trie for matching strings that can be tokenized by a slash
8818 // (e.g. URLs minus the protocol, address and port).
8819 ztrie_t *self = ztrie_new ('/');
8820 assert (self);
8821
8822 int ret = 0;
8823
8824 // Let's start by inserting a couple of routes into the trie.
8825 // This one is for the route '/foo/bar' the slash at the beginning of the
8826 // route is important because everything before the first delimiter will be
8827 // discarded. A slash at the end of a route is optional though. The data
8828 // associated with this node is passed without destroy function which means
8829 // it must be destroyed by the caller.
8830 int foo_bar_data = 10;
8831 ret = ztrie_insert_route (self, "/foo/bar", &foo_bar_data, NULL);
8832 assert (ret == 0);
8833
8834 // Now suppose we like to match all routes with two tokens that start with
8835 // '/foo/' but aren't '/foo/bar'. This is possible by using regular
8836 // expressions which are enclosed in an opening and closing curly bracket.
8837 // Tokens that contain regular expressions are always match after string
8838 // based tokens.
8839 // Note: There is no order in which regular expressions are sorted thus
8840 // if you enter multiple expressions for a route you will have to make
8841 // sure they don't have overlapping results. For example '/foo/{[^/]+}'
8842 // and '/foo/{\d+} having could turn out badly.
8843 int foo_other_data = 100;
8844 ret = ztrie_insert_route (self, "/foo/{[^/]+}", &foo_other_data, NULL);
8845 assert (ret == 0);
8846
8847 // Regular expression are only matched against tokens of the same level.
8848 // This allows us to append to are route with a regular expression as if
8849 // it were a string.
8850 ret = ztrie_insert_route (self, "/foo/{[^/]+}/gulp", NULL, NULL);
8851 assert (ret == 0);
8852
8853 // Routes are identified by their endpoint, which is the last token of the route.
8854 // It is possible to insert routes for a node that already exists but isn't an
8855 // endpoint yet. The delimiter at the end of a route is optional and has no effect.
8856 ret = ztrie_insert_route (self, "/foo/", NULL, NULL);
8857 assert (ret == 0);
8858
8859 // If you try to insert a route which already exists the method will return -1.
8860 ret = ztrie_insert_route (self, "/foo", NULL, NULL);
8861 assert (ret == -1);
8862
8863 // It is not allowed to insert routes with empty tokens.
8864 ret = ztrie_insert_route (self, "//foo", NULL, NULL);
8865 assert (ret == -1);
8866
8867 // Everything before the first delimiter is ignored so 'foo/bar/baz' is equivalent
8868 // to '/bar/baz'.
8869 ret = ztrie_insert_route (self, "foo/bar/baz", NULL, NULL);
8870 assert (ret == 0);
8871 ret = ztrie_insert_route (self, "/bar/baz", NULL, NULL);
8872 assert (ret == -1);
8873
8874 // Of course you are allowed to remove routes, in case there is data associated with a
8875 // route and a destroy data function has been supplied that data will be destroyed.
8876 ret = ztrie_remove_route (self, "/foo");
8877 assert (ret == 0);
8878
8879 // Removing a non existent route will as well return -1.
8880 ret = ztrie_remove_route (self, "/foo");
8881 assert (ret == -1);
8882
8883 // Removing a route with a regular expression must exactly match the entered one.
8884 ret = ztrie_remove_route (self, "/foo/{[^/]+}");
8885 assert (ret == 0);
8886
8887 // Next we like to match a path by regular expressions and also extract matched
8888 // parts of a route. This can be done by naming the regular expression. The name of a
8889 // regular expression is entered at the beginning of the curly brackets and separated
8890 // by a colon from the regular expression. The first one in this examples is named
8891 // 'name' and names the expression '[^/]'. If there is no capturing group defined in
8892 // the expression the whole matched string will be associated with this parameter. In
8893 // case you don't like the get the whole matched string use a capturing group, like
8894 // it has been done for the 'id' parameter. This is nice but you can even match as
8895 // many parameter for a token as you like. Therefore simply put the parameter names
8896 // separated by colons in front of the regular expression and make sure to add a
8897 // capturing group for each parameter. The first parameter will be associated with
8898 // the first capturing and so on.
8899 char *data = (char *) malloc (80);
8900 sprintf (data, "%s", "Hello World!");
8901 ret = ztrie_insert_route (self, "/baz/{name:[^/]+}/{id:--(\\d+)}/{street:nr:(\\a+)(\\d+)}", data, NULL);
8902 assert (ret == 0);
8903
8904 // There is a lot you can do with regular expression but matching routes
8905 // of arbitrary length wont work. Therefore we make use of the asterisk
8906 // operator. Just place it at the end of your route, e.g. '/config/bar/*'.
8907 ret = ztrie_insert_route (self, "/config/bar/*", NULL, NULL);
8908 assert (ret == 0);
8909
8910 // Appending to an asterisk as you would to with a regular expression
8911 // isn't valid.
8912 ret = ztrie_insert_route (self, "/config/bar/*/bar", NULL, NULL);
8913 assert (ret == -1);
8914
8915 // The asterisk operator will only work as a leaf in the tree. If you
8916 // enter an asterisk in the middle of your route it will simply be
8917 // interpreted as a string.
8918 ret = ztrie_insert_route (self, "/test/*/bar", NULL, NULL);
8919 assert (ret == 0);
8920
8921 // If a parent has an asterisk as child it is not allowed to have
8922 // other siblings.
8923 ret = ztrie_insert_route (self, "/config/bar/foo/glup", NULL, NULL);
8924 assert (ret != 0);
8925
8926 // Test matches
8927 bool hasMatch = false;
8928
8929 // The route '/bar/foo' will fail to match as this route has never been inserted.
8930 hasMatch = ztrie_matches (self, "/bar/foo");
8931 assert (!hasMatch);
8932
8933 // The route '/foo/bar' will match and we can obtain the data associated with it.
8934 hasMatch = ztrie_matches (self, "/foo/bar");
8935 assert (hasMatch);
8936 int foo_bar_hit_data = *((int *) ztrie_hit_data (self));
8937 assert (foo_bar_data == foo_bar_hit_data);
8938
8939 // This route is part of another but is no endpoint itself thus the matches will fail.
8940 hasMatch = ztrie_matches (self, "/baz/blub");
8941 assert (!hasMatch);
8942
8943 // This route will match our named regular expressions route. Thus we can extract data
8944 // from the route by their names.
8945 hasMatch = ztrie_matches (self, "/baz/blub/--11/abc23");
8946 assert (hasMatch);
8947 char *match_data = (char *) ztrie_hit_data (self);
8948 assert (streq ("Hello World!", match_data));
8949 zhashx_t *parameters = ztrie_hit_parameters (self);
8950 assert (zhashx_size (parameters) == 4);
8951 assert (streq ("blub", (char *) zhashx_lookup (parameters, "name")));
8952 assert (streq ("11", (char *) zhashx_lookup (parameters, "id")));
8953 assert (streq ("abc", (char *) zhashx_lookup (parameters, "street")));
8954 assert (streq ("23", (char *) zhashx_lookup (parameters, "nr")));
8955 zhashx_destroy (¶meters);
8956
8957 // This will match our asterisk route '/config/bar/*'. As the result we
8958 // can obtain the asterisk matched part of the route.
8959 hasMatch = ztrie_matches (self, "/config/bar/foo/bar");
8960 assert (hasMatch);
8961 assert (streq (ztrie_hit_asterisk_match (self), "foo/bar"));
8962
8963 zstr_free (&data);
8964 ztrie_destroy (&self);
8965
8966 #if defined (__WINDOWS__)
8967 zsys_shutdown();
8968 #endif
8969```
8970
8971#### zuuid - UUID support class
8972
8973The zuuid class generates UUIDs and provides methods for working with
8974them. If you build CZMQ with libuuid, on Unix/Linux, it will use that
8975library. On Windows it will use UuidCreate(). Otherwise it will use a
8976random number generator to produce convincing imitations of UUIDs.
8977
8978Please add '@discuss' section in './../src/zuuid.c'.
8979
8980This is the class interface:
8981
8982```h
8983 // This is a stable class, and may not change except for emergencies. It
8984 // is provided in stable builds.
8985 // Create a new UUID object.
8986 CZMQ_EXPORT zuuid_t *
8987 zuuid_new (void);
8988
8989 // Create UUID object from supplied ZUUID_LEN-octet value.
8990 CZMQ_EXPORT zuuid_t *
8991 zuuid_new_from (const byte *source);
8992
8993 // Destroy a specified UUID object.
8994 CZMQ_EXPORT void
8995 zuuid_destroy (zuuid_t **self_p);
8996
8997 // Set UUID to new supplied ZUUID_LEN-octet value.
8998 CZMQ_EXPORT void
8999 zuuid_set (zuuid_t *self, const byte *source);
9000
9001 // Set UUID to new supplied string value skipping '-' and '{' '}'
9002 // optional delimiters. Return 0 if OK, else returns -1.
9003 CZMQ_EXPORT int
9004 zuuid_set_str (zuuid_t *self, const char *source);
9005
9006 // Return UUID binary data.
9007 CZMQ_EXPORT const byte *
9008 zuuid_data (zuuid_t *self);
9009
9010 // Return UUID binary size
9011 CZMQ_EXPORT size_t
9012 zuuid_size (zuuid_t *self);
9013
9014 // Returns UUID as string
9015 CZMQ_EXPORT const char *
9016 zuuid_str (zuuid_t *self);
9017
9018 // Return UUID in the canonical string format: 8-4-4-4-12, in lower
9019 // case. Caller does not modify or free returned value. See
9020 // http://en.wikipedia.org/wiki/Universally_unique_identifier
9021 CZMQ_EXPORT const char *
9022 zuuid_str_canonical (zuuid_t *self);
9023
9024 // Store UUID blob in target array
9025 CZMQ_EXPORT void
9026 zuuid_export (zuuid_t *self, byte *target);
9027
9028 // Check if UUID is same as supplied value
9029 CZMQ_EXPORT bool
9030 zuuid_eq (zuuid_t *self, const byte *compare);
9031
9032 // Check if UUID is different from supplied value
9033 CZMQ_EXPORT bool
9034 zuuid_neq (zuuid_t *self, const byte *compare);
9035
9036 // Make copy of UUID object; if uuid is null, or memory was exhausted,
9037 // returns null.
9038 CZMQ_EXPORT zuuid_t *
9039 zuuid_dup (zuuid_t *self);
9040
9041 // Self test of this class.
9042 CZMQ_EXPORT void
9043 zuuid_test (bool verbose);
9044
9045```
9046Please add '@interface' section in './../src/zuuid.c'.
9047
9048This is the class self test code:
9049
9050```c
9051 // Simple create/destroy test
9052 assert (ZUUID_LEN == 16);
9053 assert (ZUUID_STR_LEN == 32);
9054
9055 zuuid_t *uuid = zuuid_new ();
9056 assert (uuid);
9057 assert (zuuid_size (uuid) == ZUUID_LEN);
9058 assert (strlen (zuuid_str (uuid)) == ZUUID_STR_LEN);
9059 zuuid_t *copy = zuuid_dup (uuid);
9060 assert (streq (zuuid_str (uuid), zuuid_str (copy)));
9061
9062 // Check set/set_str/export methods
9063 const char *myuuid = "8CB3E9A9649B4BEF8DE225E9C2CEBB38";
9064 const char *myuuid2 = "8CB3E9A9-649B-4BEF-8DE2-25E9C2CEBB38";
9065 const char *myuuid3 = "{8CB3E9A9-649B-4BEF-8DE2-25E9C2CEBB38}";
9066 const char *myuuid4 = "8CB3E9A9649B4BEF8DE225E9C2CEBB3838";
9067 int rc = zuuid_set_str (uuid, myuuid);
9068 assert (rc == 0);
9069 assert (streq (zuuid_str (uuid), myuuid));
9070 rc = zuuid_set_str (uuid, myuuid2);
9071 assert (rc == 0);
9072 assert (streq (zuuid_str (uuid), myuuid));
9073 rc = zuuid_set_str (uuid, myuuid3);
9074 assert (rc == 0);
9075 assert (streq (zuuid_str (uuid), myuuid));
9076 rc = zuuid_set_str (uuid, myuuid4);
9077 assert (rc == -1);
9078 byte copy_uuid [ZUUID_LEN];
9079 zuuid_export (uuid, copy_uuid);
9080 zuuid_set (uuid, copy_uuid);
9081 assert (streq (zuuid_str (uuid), myuuid));
9082
9083 // Check the canonical string format
9084 assert (streq (zuuid_str_canonical (uuid),
9085 "8cb3e9a9-649b-4bef-8de2-25e9c2cebb38"));
9086
9087 zuuid_destroy (&uuid);
9088 zuuid_destroy (©);
9089
9090 #if defined (__WINDOWS__)
9091 zsys_shutdown();
9092 #endif
9093```
9094
9095
9096## Error Handling
9097
9098The CZMQ policy is to reduce the error flow to 0/-1 where possible. libzmq still does a lot of errno setting. CZMQ does not do that, as it creates a fuzzy API. Things either work as expected, or they fail, and the application's best strategy is usually to assert on non-zero return codes.
9099
9100Some older libraries still return plethora of error codes, to indicate different types of failure. This ironically makes both library and application more likely to be buggy. The reason is simply that it needs more code on both sides of the API, and the more code, the more bugs.
9101
9102The use of black/white error handling fits the CLASS style for APIs where each call is explicit and without side effects of any kind, and where damage is either impossible, or fatal.
9103
9104The one exception is running out of resources (memory, sockets). In that case, there are two strategies that work, for different types of app. One is to assert, to force better sizing of the machine and/or limits such as max connections. Two is to degrade carefully, e.g. refuse new connections, however that is considerably harder to do correctly and probably unrealistic for most developers.
9105
9106Some CZMQ methods used to actually assert, e.g. in zsocket_bind, if the action failed, instead of returning -1. That was just closer to the majority case where the action MUST work, or nothing can continue. However there's a small slice of cases where failure means something positive, and for these cases, such calls return -1 on failure. 99% of calling code simply asserts the return value is not -1.
9107
9108There are a few cases where the return value is overloaded to return -1, 0, or other values. These are somewhat confusing special cases and we aim to eliminate them over time.
9109
9110The overall goal with this strategy is robustness, and absolute minimal and predictable expression in the code. You can see that it works: the CZMQ code is generally very simple and clear, with a few exceptions of places where people have used their old C style (we fix these over time).
9111
9112## CZMQ Actors
9113
9114The v2 API had a zthread class that let you create "attached threads" connected to their parent by an inproc:// PIPE socket. In v3 this has been simplified and better wrapped as the zactor class. CZMQ actors are in effect threads with a socket interface. A zactor_t instance works like a socket, and the CZMQ classes that deal with sockets (like zmsg and zpoller) all accept zactor_t references as well as zsock_t and libzmq void * socket handles.
9115
9116To write an actor, use this template. Note that your actor is a single function "void myname (zsock_t *pipe, void *args)" function:
9117
9118 /* =========================================================================
9119 someclass - some description
9120
9121 Copyright (c) the Contributors as noted in the AUTHORS file.
9122 This file is part of CZMQ, the high-level C binding for ØMQ:
9123 http://czmq.zeromq.org.
9124
9125 This Source Code Form is subject to the terms of the Mozilla Public
9126 License, v. 2.0. If a copy of the MPL was not distributed with this
9127 file, You can obtain one at http://mozilla.org/MPL/2.0/.
9128 =========================================================================
9129 */
9130
9131 /*
9132 @header
9133 Please take e.g. include/zmonitor.h as basis for your public API.
9134 And delete this text, and write your own, when you create an actor :-)
9135 @discuss
9136
9137 @end
9138 */
9139
9140 #include "../include/czmq.h"
9141
9142 // --------------------------------------------------------------------------
9143 // The self_t structure holds the state for one actor instance
9144
9145 typedef struct {
9146 zsock_t *pipe; // Actor command pipe
9147 zpoller_t *poller; // Socket poller
9148 // ... you'll be adding other stuff here
9149 bool terminated; // Did caller ask us to quit?
9150 bool verbose; // Verbose logging enabled?
9151 } self_t;
9152
9153 static self_t *
9154 s_self_new (zsock_t *pipe)
9155 {
9156 self_t *self = (self_t *) zmalloc (sizeof (self_t));
9157 self->pipe = pipe;
9158 // ... initialize your own state including any other
9159 // sockets, which you can add to the poller:
9160 self->poller = zpoller_new (self->pipe, NULL);
9161 return self;
9162 }
9163
9164 static void
9165 s_self_destroy (self_t **self_p)
9166 {
9167 assert (self_p);
9168 if (*self_p) {
9169 self_t *self = *self_p;
9170 zpoller_destroy (&self->poller);
9171 // ... destroy your own state here
9172 free (self);
9173 *self_p = NULL;
9174 }
9175 }
9176
9177
9178 // --------------------------------------------------------------------------
9179 // Handle a command from calling application
9180
9181 static int
9182 s_self_handle_pipe (self_t *self)
9183 {
9184 // Get the whole message off the pipe in one go
9185 zmsg_t *request = zmsg_recv (self->pipe);
9186 if (!request)
9187 return -1; // Interrupted
9188
9189 char *command = zmsg_popstr (request);
9190 if (self->verbose)
9191 zsys_info ("zxxx: API command=%s", command);
9192 if (streq (command, "VERBOSE"))
9193 self->verbose = true;
9194 else
9195 // An example of a command that the caller would wait for
9196 // via a signal, so that the two threads synchronize
9197 if (streq (command, "WAIT"))
9198 zsock_signal (self->pipe, 0);
9199 else
9200 if (streq (command, "$TERM"))
9201 self->terminated = true;
9202 else {
9203 zsys_error ("zxxx: - invalid command: %s", command);
9204 assert (false);
9205 }
9206 zstr_free (&command);
9207 zmsg_destroy (&request);
9208 return 0;
9209 }
9210
9211
9212 // --------------------------------------------------------------------------
9213 // zxxx() implements the zxxx actor interface
9214
9215 void
9216 zxxx (zsock_t *pipe, void *args)
9217 {
9218 self_t *self = s_self_new (pipe);
9219 // Signal successful initialization
9220 zsock_signal (pipe, 0);
9221
9222 while (!self->terminated) {
9223 zsock_t *which = (zsock_t *) zpoller_wait (self->poller, -1);
9224 if (which == self->pipe)
9225 s_self_handle_pipe (self);
9226 else
9227 if (zpoller_terminated (self->poller))
9228 break; // Interrupted
9229 }
9230 s_self_destroy (&self);
9231 }
9232
9233
9234 // --------------------------------------------------------------------------
9235 // Selftest
9236
9237 void
9238 zxxx_test (bool verbose)
9239 {
9240 printf (" * zxxx: ");
9241 if (verbose)
9242 printf ("\n");
9243
9244 // @selftest
9245 zactor_t *xxx = zactor_new (zxxx, NULL);
9246 assert (xxx);
9247 if (verbose)
9248 zstr_sendx (xxx, "VERBOSE", NULL);
9249
9250 zactor_destroy (&xxx);
9251 // @end
9252 printf ("OK\n");
9253 }
9254
9255The selftest code shows how to create, talk to, and destroy an actor.
9256
9257## Under the Hood
9258
9259### Adding a New Class
9260
9261If you define a new CZMQ class `myclass` you need to:
9262
9263* Write the `zmyclass.c` and `zmyclass.h` source files, in `src` and `include` respectively.
9264* Add`#include <zmyclass.h>` to `include/czmq.h`.
9265* Add the myclass header and test call to `src/czmq_selftest.c`.
9266* Add a reference documentation to 'doc/zmyclass.txt'.
9267* Add myclass to 'model/projects.xml` and read model/README.txt.
9268* Add a section to README.txt.
9269
9270### Documentation
9271
9272Man pages are generated from the class header and source files via the doc/mkman tool, and similar functionality in the gitdown tool (http://github.com/imatix/gitdown). The header file for a class must wrap its interface as follows (example is from include/zclock.h):
9273
9274 // @interface
9275 // Sleep for a number of milliseconds
9276 void
9277 zclock_sleep (int msecs);
9278
9279 // Return current system clock as milliseconds
9280 int64_t
9281 zclock_time (void);
9282
9283 // Self test of this class
9284 int
9285 zclock_test (Bool verbose);
9286 // @end
9287
9288The source file for a class must provide documentation as follows:
9289
9290 /*
9291 @header
9292 ...short explanation of class...
9293 @discuss
9294 ...longer discussion of how it works...
9295 @end
9296 */
9297
9298The source file for a class then provides the self test example as follows:
9299
9300 // @selftest
9301 int64_t start = zclock_time ();
9302 zclock_sleep (10);
9303 assert ((zclock_time () - start) >= 10);
9304 // @end
9305
9306The template for man pages is in doc/mkman.
9307
9308### Development
9309
9310CZMQ is developed through a test-driven process that guarantees no memory violations or leaks in the code:
9311
9312* Modify a class or method.
9313* Update the test method for that class.
9314* Run the 'selftest' script, which uses the Valgrind memcheck tool.
9315* Repeat until perfect.
9316
9317### Porting CZMQ
9318
9319When you try CZMQ on an OS that it's not been used on (ever, or for a while), you will hit code that does not compile. In some cases the patches are trivial, in other cases (usually when porting to Windows), the work needed to build equivalent functionality may be non-trivial. In any case, the benefit is that once ported, the functionality is available to all applications.
9320
9321Before attempting to patch code for portability, please read the `czmq_prelude.h` header file. There are several typical types of changes you may need to make to get functionality working on a specific operating system:
9322
9323* Defining typedefs which are missing on that specific compiler: do this in czmq_prelude.h.
9324* Defining macros that rename exotic library functions to more conventional names: do this in czmq_prelude.h.
9325* Reimplementing specific methods to use a non-standard API: this is typically needed on Windows. Do this in the relevant class, using #ifdefs to properly differentiate code for different platforms.
9326
9327### Hints to Contributors
9328
9329CZMQ is a nice, neat library, and you may not immediately appreciate why. Read the CLASS style guide please, and write your code to make it indistinguishable from the rest of the code in the library. That is the only real criteria for good style: it's invisible.
9330
9331Don't include system headers in source files. The right place for these is czmq_prelude.h. If you need to check against configured libraries and/or headers, include platform.h in the source before including czmq.h.
9332
9333Do read your code after you write it and ask, "Can I make this simpler?" We do use a nice minimalist and yet readable style. Learn it, adopt it, use it.
9334
9335Before opening a pull request read our [contribution guidelines](https://github.com/zeromq/czmq/blob/master/CONTRIBUTING.md). Thanks!
9336
9337### Code Generation
9338
9339We generate the zsockopt class using [GSL](https://github.com/imatix/gsl), using a code generator script in scripts/sockopts.gsl. We also generate the project files.
9340
9341### This Document
9342
9343This document is originally at README.txt and is built using [gitdown](http://github.com/imatix/gitdown).
9344
9345_This documentation was generated from czmq/README.txt using [Gitdown](https://github.com/zeromq/gitdown)_
9346