From 6d8baea714d1a140b1940791787a47fe145ef089 Mon Sep 17 00:00:00 2001 From: sigiesec Date: Thu, 1 Feb 2018 11:41:18 +0100 Subject: [PATCH 1/7] Problem: no definition for applying automated formatting Solution: added .clang-format file --- .clang-format | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..9d699ec978 --- /dev/null +++ b/.clang-format @@ -0,0 +1,53 @@ +BasedOnStyle: LLVM +IndentWidth: 4 +UseTab: Never +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: true + AfterControlStatement: false + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: false + IndentBraces: false + +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AllowShortIfStatementsOnASingleLine: false +IndentCaseLabels: true +BinPackArguments: true +BinPackParameters: false +AlignTrailingComments: true +AllowShortBlocksOnASingleLine: false +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortFunctionsOnASingleLine: InlineOnly +AlwaysBreakTemplateDeclarations: false +ColumnLimit: 80 +MaxEmptyLinesToKeep: 2 +KeepEmptyLinesAtTheStartOfBlocks: false +ContinuationIndentWidth: 2 +PointerAlignment: Right +ReflowComments: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: Always +SpaceInEmptyParentheses: false +SpacesInAngles: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 + +SortIncludes: false + +FixNamespaceComments: false +BreakBeforeBinaryOperators: NonAssignment +SpaceAfterTemplateKeyword: true +AlignAfterOpenBracket: Align +AlignOperands: true +BreakConstructorInitializers: AfterColon +ConstructorInitializerAllOnOneLineOrOnePerLine: true +SpaceAfterCStyleCast: true +BreakBeforeTernaryOperators: true From 41f459e1dc6f7cdedd1268298153c970e290b2ce Mon Sep 17 00:00:00 2001 From: sigiesec Date: Thu, 1 Feb 2018 11:46:09 +0100 Subject: [PATCH 2/7] Problem: formatting inconsistent Solution: applied clang-format --- include/zmq.h | 245 +++++----- include/zmq_utils.h | 6 +- perf/inproc_lat.cpp | 10 +- perf/inproc_thr.cpp | 15 +- perf/local_lat.cpp | 10 +- perf/local_thr.cpp | 21 +- perf/remote_lat.cpp | 10 +- perf/remote_thr.cpp | 25 +- src/address.cpp | 39 +- src/address.hpp | 48 +- src/array.hpp | 200 ++++---- src/atomic_counter.hpp | 239 +++++----- src/atomic_ptr.hpp | 215 ++++----- src/blob.hpp | 232 +++++----- src/client.cpp | 1 - src/client.hpp | 70 ++- src/clock.cpp | 93 ++-- src/clock.hpp | 44 +- src/command.hpp | 292 ++++++------ src/condition_variable.hpp | 275 +++++------ src/config.hpp | 118 +++-- src/ctx.cpp | 279 ++++++------ src/ctx.hpp | 320 ++++++------- src/curve_client.cpp | 51 +-- src/curve_client.hpp | 73 ++- src/curve_client_tools.hpp | 10 +- src/curve_mechanism_base.cpp | 44 +- src/curve_mechanism_base.hpp | 2 +- src/curve_server.cpp | 114 ++--- src/curve_server.hpp | 87 ++-- src/dbuffer.hpp | 151 +++---- src/dealer.cpp | 8 +- src/dealer.hpp | 86 ++-- src/decoder.hpp | 267 ++++++----- src/decoder_allocators.cpp | 69 +-- src/decoder_allocators.hpp | 168 +++---- src/devpoll.cpp | 58 ++- src/devpoll.hpp | 100 ++-- src/dgram.cpp | 8 +- src/dgram.hpp | 73 ++- src/dish.cpp | 55 +-- src/dish.hpp | 146 +++--- src/dist.cpp | 23 +- src/dist.hpp | 114 +++-- src/encoder.hpp | 233 +++++----- src/epoll.cpp | 45 +- src/epoll.hpp | 98 ++-- src/err.cpp | 628 +++++++++++++------------- src/err.hpp | 158 +++---- src/fd.hpp | 23 +- src/fq.cpp | 21 +- src/fq.hpp | 94 ++-- src/gather.cpp | 1 - src/gather.hpp | 59 ++- src/gssapi_client.cpp | 77 ++-- src/gssapi_client.hpp | 82 ++-- src/gssapi_mechanism_base.cpp | 108 ++--- src/gssapi_mechanism_base.hpp | 126 +++--- src/gssapi_server.cpp | 61 ++- src/gssapi_server.hpp | 91 ++-- src/i_decoder.hpp | 36 +- src/i_encoder.hpp | 31 +- src/i_engine.hpp | 43 +- src/i_mailbox.hpp | 27 +- src/i_poll_events.hpp | 26 +- src/io_object.cpp | 3 +- src/io_object.hpp | 83 ++-- src/io_thread.cpp | 2 +- src/io_thread.hpp | 76 ++-- src/ip.cpp | 58 ++- src/ip.hpp | 34 +- src/ipc_address.cpp | 19 +- src/ipc_address.hpp | 40 +- src/ipc_connecter.cpp | 51 +-- src/ipc_connecter.hpp | 136 +++--- src/ipc_listener.cpp | 127 +++--- src/ipc_listener.hpp | 109 +++-- src/kqueue.cpp | 48 +- src/kqueue.hpp | 108 +++-- src/lb.cpp | 24 +- src/lb.hpp | 70 ++- src/macros.hpp | 11 +- src/mailbox.hpp | 66 ++- src/mailbox_safe.cpp | 24 +- src/mailbox_safe.hpp | 66 ++- src/mechanism.cpp | 64 ++- src/mechanism.hpp | 154 +++---- src/mechanism_base.cpp | 3 +- src/mechanism_base.hpp | 5 +- src/metadata.cpp | 10 +- src/metadata.hpp | 41 +- src/msg.cpp | 182 ++++---- src/msg.hpp | 401 ++++++++-------- src/mtrie.cpp | 184 ++++---- src/mtrie.hpp | 113 ++--- src/mutex.hpp | 240 +++++----- src/norm_engine.cpp | 602 ++++++++++++------------ src/norm_engine.hpp | 305 ++++++------- src/null_mechanism.cpp | 45 +- src/null_mechanism.hpp | 64 ++- src/object.cpp | 200 ++++---- src/object.hpp | 225 +++++---- src/options.cpp | 164 ++++--- src/options.hpp | 344 +++++++------- src/own.cpp | 6 +- src/own.hpp | 209 +++++---- src/pair.cpp | 3 +- src/pair.hpp | 67 ++- src/pgm_receiver.cpp | 23 +- src/pgm_receiver.hpp | 158 ++++--- src/pgm_sender.cpp | 20 +- src/pgm_sender.hpp | 122 +++-- src/pgm_socket.cpp | 277 ++++++------ src/pgm_socket.hpp | 110 ++--- src/pipe.cpp | 101 +++-- src/pipe.hpp | 393 ++++++++-------- src/plain_client.cpp | 35 +- src/plain_client.hpp | 60 ++- src/plain_server.cpp | 31 +- src/plain_server.hpp | 54 +-- src/poll.cpp | 70 ++- src/poll.hpp | 98 ++-- src/poller.hpp | 24 +- src/poller_base.cpp | 4 +- src/poller_base.hpp | 81 ++-- src/pollset.cpp | 86 ++-- src/pollset.hpp | 102 ++--- src/precompiled.hpp | 2 +- src/proxy.cpp | 392 ++++++++-------- src/proxy.hpp | 10 +- src/pub.hpp | 42 +- src/pull.hpp | 59 ++- src/push.hpp | 56 +-- src/radio.cpp | 52 ++- src/radio.hpp | 121 +++-- src/random.cpp | 15 +- src/random.hpp | 25 +- src/raw_decoder.cpp | 22 +- src/raw_decoder.hpp | 40 +- src/raw_encoder.cpp | 4 +- src/raw_encoder.hpp | 26 +- src/reaper.cpp | 9 +- src/reaper.hpp | 72 ++- src/rep.cpp | 5 +- src/rep.hpp | 61 ++- src/req.cpp | 83 ++-- src/req.hpp | 154 +++---- src/router.cpp | 111 +++-- src/router.hpp | 152 +++---- src/scatter.hpp | 56 +-- src/select.cpp | 52 +-- src/select.hpp | 4 +- src/server.cpp | 12 +- src/server.hpp | 84 ++-- src/session_base.cpp | 228 +++++----- src/session_base.hpp | 241 +++++----- src/signaler.cpp | 140 +++--- src/signaler.hpp | 79 ++-- src/socket_base.cpp | 533 +++++++++++----------- src/socket_base.hpp | 459 ++++++++++--------- src/socket_poller.cpp | 165 +++---- src/socket_poller.hpp | 137 +++--- src/socks.cpp | 130 +++--- src/socks.hpp | 182 ++++---- src/socks_connecter.cpp | 164 +++---- src/socks_connecter.hpp | 188 ++++---- src/stdint.hpp | 2 +- src/stream.cpp | 54 ++- src/stream.hpp | 121 +++-- src/stream_engine.cpp | 327 +++++++------- src/stream_engine.hpp | 271 +++++------ src/sub.cpp | 10 +- src/sub.hpp | 43 +- src/tcp.cpp | 158 +++---- src/tcp.hpp | 62 +-- src/tcp_address.cpp | 347 +++++++------- src/tcp_address.hpp | 116 ++--- src/tcp_connecter.cpp | 81 ++-- src/tcp_connecter.hpp | 142 +++--- src/tcp_listener.cpp | 55 +-- src/tcp_listener.hpp | 81 ++-- src/thread.cpp | 149 +++--- src/thread.hpp | 90 ++-- src/timers.hpp | 105 +++-- src/tipc_address.cpp | 15 +- src/tipc_address.hpp | 39 +- src/tipc_connecter.cpp | 54 ++- src/tipc_connecter.hpp | 136 +++--- src/tipc_listener.cpp | 26 +- src/tipc_listener.hpp | 80 ++-- src/trie.cpp | 125 +++-- src/trie.hpp | 85 ++-- src/tweetnacl.h | 23 +- src/udp_address.cpp | 12 +- src/udp_address.hpp | 51 +-- src/udp_engine.cpp | 101 ++--- src/udp_engine.hpp | 82 ++-- src/v1_decoder.cpp | 29 +- src/v1_decoder.hpp | 43 +- src/v1_encoder.cpp | 15 +- src/v1_encoder.hpp | 29 +- src/v2_decoder.cpp | 63 +-- src/v2_decoder.hpp | 54 ++- src/v2_encoder.cpp | 11 +- src/v2_encoder.hpp | 29 +- src/v2_protocol.hpp | 20 +- src/vmci.cpp | 26 +- src/vmci.hpp | 12 +- src/vmci_address.cpp | 59 ++- src/vmci_address.hpp | 48 +- src/vmci_connecter.cpp | 81 ++-- src/vmci_connecter.hpp | 135 +++--- src/vmci_listener.cpp | 62 +-- src/vmci_listener.hpp | 76 ++-- src/windows.hpp | 20 +- src/wire.hpp | 122 +++-- src/xpub.cpp | 130 +++--- src/xpub.hpp | 153 +++---- src/xsub.cpp | 23 +- src/xsub.hpp | 111 +++-- src/ypipe.hpp | 297 ++++++------ src/ypipe_base.hpp | 30 +- src/ypipe_conflate.hpp | 138 +++--- src/yqueue.hpp | 314 +++++++------ src/zap_client.cpp | 18 +- src/zap_client.hpp | 1 + src/zmq.cpp | 410 +++++++++-------- src/zmq_draft.h | 60 +-- src/zmq_utils.cpp | 101 ++--- tests/test_abstract_ipc.cpp | 10 +- tests/test_ancillaries.cpp | 5 +- tests/test_base85.cpp | 72 +-- tests/test_bind_after_connect_tcp.cpp | 8 +- tests/test_bind_src_address.cpp | 2 +- tests/test_capabilities.cpp | 24 +- tests/test_client_server.cpp | 6 +- tests/test_conflate.cpp | 12 +- tests/test_connect_delay_tipc.cpp | 24 +- tests/test_connect_resolve.cpp | 6 +- tests/test_connect_rid.cpp | 38 +- tests/test_ctx_destroy.cpp | 20 +- tests/test_ctx_options.cpp | 79 ++-- tests/test_dgram.cpp | 14 +- tests/test_diffserv.cpp | 7 +- tests/test_disconnect_inproc.cpp | 109 +++-- tests/test_filter_ipc.cpp | 38 +- tests/test_fork.cpp | 13 +- tests/test_getsockopt_memset.cpp | 12 +- tests/test_heartbeats.cpp | 143 +++--- tests/test_hwm.cpp | 47 +- tests/test_hwm_pubsub.cpp | 67 ++- tests/test_immediate.cpp | 54 +-- tests/test_inproc_connect.cpp | 71 ++- tests/test_invalid_rep.cpp | 17 +- tests/test_iov.cpp | 21 +- tests/test_ipc_wildcard.cpp | 8 +- tests/test_issue_566.cpp | 12 +- tests/test_last_endpoint.cpp | 9 +- tests/test_many_sockets.cpp | 8 +- tests/test_metadata.cpp | 18 +- tests/test_monitor.cpp | 18 +- tests/test_msg_ffn.cpp | 81 ++-- tests/test_msg_flags.cpp | 25 +- tests/test_pair_inproc.cpp | 14 +- tests/test_pair_ipc.cpp | 6 +- tests/test_pair_tcp.cpp | 6 +- tests/test_pair_tipc.cpp | 2 +- tests/test_pair_vmci.cpp | 10 +- tests/test_poller.cpp | 37 +- tests/test_probe_router.cpp | 14 +- tests/test_proxy.cpp | 179 ++++---- tests/test_proxy_single_socket.cpp | 14 +- tests/test_proxy_terminate.cpp | 5 +- tests/test_pub_invert_matching.cpp | 38 +- tests/test_radio_dish.cpp | 29 +- tests/test_rebind_ipc.cpp | 10 +- tests/test_reconnect_ivl.cpp | 4 +- tests/test_req_correlate.cpp | 4 +- tests/test_req_relaxed.cpp | 44 +- tests/test_reqrep_device.cpp | 10 +- tests/test_reqrep_device_tipc.cpp | 4 +- tests/test_reqrep_inproc.cpp | 6 +- tests/test_reqrep_ipc.cpp | 10 +- tests/test_reqrep_tcp.cpp | 44 +- tests/test_reqrep_tipc.cpp | 2 +- tests/test_reqrep_vmci.cpp | 10 +- tests/test_router_handover.cpp | 21 +- tests/test_router_mandatory.cpp | 16 +- tests/test_router_mandatory_hwm.cpp | 35 +- tests/test_router_mandatory_tipc.cpp | 5 +- tests/test_scatter_gather.cpp | 14 +- tests/test_security_curve.cpp | 119 +++-- tests/test_security_gssapi.cpp | 102 +++-- tests/test_security_null.cpp | 48 +- tests/test_security_plain.cpp | 55 +-- tests/test_security_zap.cpp | 14 +- tests/test_setsockopt.cpp | 32 +- tests/test_shutdown_stress.cpp | 39 +- tests/test_shutdown_stress_tipc.cpp | 28 +- tests/test_sockopt_hwm.cpp | 131 +++--- tests/test_sodium.cpp | 21 +- tests/test_spec_dealer.cpp | 43 +- tests/test_spec_pushpull.cpp | 61 ++- tests/test_spec_rep.cpp | 40 +- tests/test_spec_req.cpp | 58 +-- tests/test_spec_router.cpp | 42 +- tests/test_srcfd.cpp | 39 +- tests/test_stream.cpp | 66 ++- tests/test_stream_disconnect.cpp | 154 ++++--- tests/test_stream_empty.cpp | 17 +- tests/test_stream_exceeds_buffer.cpp | 104 ++--- tests/test_stream_timeout.cpp | 45 +- tests/test_sub_forward.cpp | 6 +- tests/test_sub_forward_tipc.cpp | 4 +- tests/test_system.cpp | 45 +- tests/test_term_endpoint.cpp | 30 +- tests/test_thread_safe.cpp | 4 +- tests/test_timeo.cpp | 18 +- tests/test_timers.cpp | 24 +- tests/test_udp.cpp | 23 +- tests/test_unbind_inproc.cpp | 2 +- tests/test_unbind_wildcard.cpp | 18 +- tests/test_use_fd_ipc.cpp | 37 +- tests/test_use_fd_tcp.cpp | 57 ++- tests/test_xpub_manual.cpp | 220 ++++----- tests/test_xpub_nodrop.cpp | 17 +- tests/test_xpub_welcome_msg.cpp | 10 +- tests/test_zmq_poll_fd.cpp | 33 +- tests/testutil.hpp | 159 ++++--- tests/testutil_security.hpp | 10 +- tools/curve_keygen.cpp | 26 +- 331 files changed, 13278 insertions(+), 13761 deletions(-) diff --git a/include/zmq.h b/include/zmq.h index ddc851469b..3e80b73f54 100644 --- a/include/zmq.h +++ b/include/zmq.h @@ -43,10 +43,10 @@ #define ZMQ_VERSION_MINOR 2 #define ZMQ_VERSION_PATCH 4 -#define ZMQ_MAKE_VERSION(major, minor, patch) \ - ((major) * 10000 + (minor) * 100 + (patch)) -#define ZMQ_VERSION \ - ZMQ_MAKE_VERSION(ZMQ_VERSION_MAJOR, ZMQ_VERSION_MINOR, ZMQ_VERSION_PATCH) +#define ZMQ_MAKE_VERSION(major, minor, patch) \ + ((major) *10000 + (minor) *100 + (patch)) +#define ZMQ_VERSION \ + ZMQ_MAKE_VERSION (ZMQ_VERSION_MAJOR, ZMQ_VERSION_MINOR, ZMQ_VERSION_PATCH) #ifdef __cplusplus extern "C" { @@ -66,7 +66,7 @@ extern "C" { #ifdef __MINGW32__ // Require Windows XP or higher with MinGW for getaddrinfo(). -#if(_WIN32_WINNT >= 0x0501) +#if (_WIN32_WINNT >= 0x0501) #else #error You need at least Windows XP target #endif @@ -76,49 +76,49 @@ extern "C" { /* Handle DSO symbol visibility */ #if defined _WIN32 -# if defined ZMQ_STATIC -# define ZMQ_EXPORT -# elif defined DLL_EXPORT -# define ZMQ_EXPORT __declspec(dllexport) -# else -# define ZMQ_EXPORT __declspec(dllimport) -# endif +#if defined ZMQ_STATIC +#define ZMQ_EXPORT +#elif defined DLL_EXPORT +#define ZMQ_EXPORT __declspec(dllexport) #else -# if defined __SUNPRO_C || defined __SUNPRO_CC -# define ZMQ_EXPORT __global -# elif (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER -# define ZMQ_EXPORT __attribute__ ((visibility("default"))) -# else -# define ZMQ_EXPORT -# endif +#define ZMQ_EXPORT __declspec(dllimport) +#endif +#else +#if defined __SUNPRO_C || defined __SUNPRO_CC +#define ZMQ_EXPORT __global +#elif (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER +#define ZMQ_EXPORT __attribute__ ((visibility ("default"))) +#else +#define ZMQ_EXPORT +#endif #endif /* Define integer types needed for event interface */ #define ZMQ_DEFINED_STDINT 1 #if defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_OPENVMS -# include +#include #elif defined _MSC_VER && _MSC_VER < 1600 -# ifndef int32_t - typedef __int32 int32_t; -# endif -# ifndef uint32_t - typedef unsigned __int32 uint32_t; -# endif -# ifndef uint16_t - typedef unsigned __int16 uint16_t; -# endif -# ifndef uint8_t - typedef unsigned __int8 uint8_t; -# endif +#ifndef int32_t +typedef __int32 int32_t; +#endif +#ifndef uint32_t +typedef unsigned __int32 uint32_t; +#endif +#ifndef uint16_t +typedef unsigned __int16 uint16_t; +#endif +#ifndef uint8_t +typedef unsigned __int8 uint8_t; +#endif #else -# include +#include #endif // 32-bit AIX's pollfd struct members are called reqevents and rtnevents so it // defines compatibility macros for them. Need to include that header first to // stop build failures since zmq_pollset_t defines them as events and revents. #ifdef ZMQ_HAVE_AIX - #include +#include #endif @@ -209,7 +209,7 @@ ZMQ_EXPORT void zmq_version (int *major, int *minor, int *patch); /******************************************************************************/ /* Context options */ -#define ZMQ_IO_THREADS 1 +#define ZMQ_IO_THREADS 1 #define ZMQ_MAX_SOCKETS 2 #define ZMQ_SOCKET_LIMIT 3 #define ZMQ_THREAD_PRIORITY 3 @@ -217,7 +217,7 @@ ZMQ_EXPORT void zmq_version (int *major, int *minor, int *patch); #define ZMQ_MAX_MSGSZ 5 /* Default for new contexts */ -#define ZMQ_IO_THREADS_DFLT 1 +#define ZMQ_IO_THREADS_DFLT 1 #define ZMQ_MAX_SOCKETS_DFLT 1023 #define ZMQ_THREAD_PRIORITY_DFLT -1 #define ZMQ_THREAD_SCHED_POLICY_DFLT -1 @@ -242,26 +242,27 @@ ZMQ_EXPORT int zmq_ctx_destroy (void *context); * alignment and raise sigbus on violations. Make sure applications allocate * zmq_msg_t on addresses aligned on a pointer-size boundary to avoid this issue. */ -typedef struct zmq_msg_t { -#if defined (__GNUC__) || defined ( __INTEL_COMPILER) || \ - (defined (__SUNPRO_C) && __SUNPRO_C >= 0x590) || \ - (defined (__SUNPRO_CC) && __SUNPRO_CC >= 0x590) - unsigned char _ [64] __attribute__ ((aligned (sizeof (void *)))); -#elif defined (_MSC_VER) && (defined (_M_X64) || defined (_M_ARM64)) - __declspec (align (8)) unsigned char _ [64]; -#elif defined (_MSC_VER) && (defined (_M_IX86) || defined (_M_ARM_ARMV7VE)) - __declspec (align (4)) unsigned char _ [64]; +typedef struct zmq_msg_t +{ +#if defined(__GNUC__) || defined(__INTEL_COMPILER) \ + || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x590) \ + || (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x590) + unsigned char _[64] __attribute__ ((aligned (sizeof (void *)))); +#elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) + __declspec(align (8)) unsigned char _[64]; +#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_ARM_ARMV7VE)) + __declspec(align (4)) unsigned char _[64]; #else - unsigned char _ [64]; + unsigned char _[64]; #endif } zmq_msg_t; -typedef void (zmq_free_fn) (void *data, void *hint); +typedef void(zmq_free_fn) (void *data, void *hint); ZMQ_EXPORT int zmq_msg_init (zmq_msg_t *msg); ZMQ_EXPORT int zmq_msg_init_size (zmq_msg_t *msg, size_t size); -ZMQ_EXPORT int zmq_msg_init_data (zmq_msg_t *msg, void *data, - size_t size, zmq_free_fn *ffn, void *hint); +ZMQ_EXPORT int zmq_msg_init_data ( + zmq_msg_t *msg, void *data, size_t size, zmq_free_fn *ffn, void *hint); ZMQ_EXPORT int zmq_msg_send (zmq_msg_t *msg, void *s, int flags); ZMQ_EXPORT int zmq_msg_recv (zmq_msg_t *msg, void *s, int flags); ZMQ_EXPORT int zmq_msg_close (zmq_msg_t *msg); @@ -272,7 +273,8 @@ ZMQ_EXPORT size_t zmq_msg_size (const zmq_msg_t *msg); ZMQ_EXPORT int zmq_msg_more (const zmq_msg_t *msg); ZMQ_EXPORT int zmq_msg_get (const zmq_msg_t *msg, int property); ZMQ_EXPORT int zmq_msg_set (zmq_msg_t *msg, int property, int optval); -ZMQ_EXPORT const char *zmq_msg_gets (const zmq_msg_t *msg, const char *property); +ZMQ_EXPORT const char *zmq_msg_gets (const zmq_msg_t *msg, + const char *property); /******************************************************************************/ /* 0MQ socket definition. */ @@ -386,20 +388,20 @@ ZMQ_EXPORT const char *zmq_msg_gets (const zmq_msg_t *msg, const char *property) #define ZMQ_GSSAPI 3 /* RADIO-DISH protocol */ -#define ZMQ_GROUP_MAX_LENGTH 15 +#define ZMQ_GROUP_MAX_LENGTH 15 /* Deprecated options and aliases */ -#define ZMQ_IDENTITY ZMQ_ROUTING_ID -#define ZMQ_CONNECT_RID ZMQ_CONNECT_ROUTING_ID -#define ZMQ_TCP_ACCEPT_FILTER 38 -#define ZMQ_IPC_FILTER_PID 58 -#define ZMQ_IPC_FILTER_UID 59 -#define ZMQ_IPC_FILTER_GID 60 -#define ZMQ_IPV4ONLY 31 +#define ZMQ_IDENTITY ZMQ_ROUTING_ID +#define ZMQ_CONNECT_RID ZMQ_CONNECT_ROUTING_ID +#define ZMQ_TCP_ACCEPT_FILTER 38 +#define ZMQ_IPC_FILTER_PID 58 +#define ZMQ_IPC_FILTER_UID 59 +#define ZMQ_IPC_FILTER_GID 60 +#define ZMQ_IPV4ONLY 31 #define ZMQ_DELAY_ATTACH_ON_CONNECT ZMQ_IMMEDIATE -#define ZMQ_NOBLOCK ZMQ_DONTWAIT -#define ZMQ_FAIL_UNROUTABLE ZMQ_ROUTER_MANDATORY -#define ZMQ_ROUTER_BEHAVIOR ZMQ_ROUTER_MANDATORY +#define ZMQ_NOBLOCK ZMQ_DONTWAIT +#define ZMQ_FAIL_UNROUTABLE ZMQ_ROUTER_MANDATORY +#define ZMQ_ROUTER_BEHAVIOR ZMQ_ROUTER_MANDATORY /* Deprecated Message options */ #define ZMQ_SRCFD 2 @@ -410,25 +412,25 @@ ZMQ_EXPORT const char *zmq_msg_gets (const zmq_msg_t *msg, const char *property) /* Socket transport events (TCP, IPC and TIPC only) */ -#define ZMQ_EVENT_CONNECTED 0x0001 -#define ZMQ_EVENT_CONNECT_DELAYED 0x0002 -#define ZMQ_EVENT_CONNECT_RETRIED 0x0004 -#define ZMQ_EVENT_LISTENING 0x0008 -#define ZMQ_EVENT_BIND_FAILED 0x0010 -#define ZMQ_EVENT_ACCEPTED 0x0020 -#define ZMQ_EVENT_ACCEPT_FAILED 0x0040 -#define ZMQ_EVENT_CLOSED 0x0080 -#define ZMQ_EVENT_CLOSE_FAILED 0x0100 -#define ZMQ_EVENT_DISCONNECTED 0x0200 -#define ZMQ_EVENT_MONITOR_STOPPED 0x0400 -#define ZMQ_EVENT_ALL 0xFFFF +#define ZMQ_EVENT_CONNECTED 0x0001 +#define ZMQ_EVENT_CONNECT_DELAYED 0x0002 +#define ZMQ_EVENT_CONNECT_RETRIED 0x0004 +#define ZMQ_EVENT_LISTENING 0x0008 +#define ZMQ_EVENT_BIND_FAILED 0x0010 +#define ZMQ_EVENT_ACCEPTED 0x0020 +#define ZMQ_EVENT_ACCEPT_FAILED 0x0040 +#define ZMQ_EVENT_CLOSED 0x0080 +#define ZMQ_EVENT_CLOSE_FAILED 0x0100 +#define ZMQ_EVENT_DISCONNECTED 0x0200 +#define ZMQ_EVENT_MONITOR_STOPPED 0x0400 +#define ZMQ_EVENT_ALL 0xFFFF ZMQ_EXPORT void *zmq_socket (void *, int type); ZMQ_EXPORT int zmq_close (void *s); -ZMQ_EXPORT int zmq_setsockopt (void *s, int option, const void *optval, - size_t optvallen); -ZMQ_EXPORT int zmq_getsockopt (void *s, int option, void *optval, - size_t *optvallen); +ZMQ_EXPORT int +zmq_setsockopt (void *s, int option, const void *optval, size_t optvallen); +ZMQ_EXPORT int +zmq_getsockopt (void *s, int option, void *optval, size_t *optvallen); ZMQ_EXPORT int zmq_bind (void *s, const char *addr); ZMQ_EXPORT int zmq_connect (void *s, const char *addr); ZMQ_EXPORT int zmq_unbind (void *s, const char *addr); @@ -462,14 +464,17 @@ typedef struct zmq_pollitem_t #define ZMQ_POLLITEMS_DFLT 16 -ZMQ_EXPORT int zmq_poll (zmq_pollitem_t *items, int nitems, long timeout); +ZMQ_EXPORT int zmq_poll (zmq_pollitem_t *items, int nitems, long timeout); /******************************************************************************/ /* Message proxying */ /******************************************************************************/ ZMQ_EXPORT int zmq_proxy (void *frontend, void *backend, void *capture); -ZMQ_EXPORT int zmq_proxy_steerable (void *frontend, void *backend, void *capture, void *control); +ZMQ_EXPORT int zmq_proxy_steerable (void *frontend, + void *backend, + void *capture, + void *control); /******************************************************************************/ /* Probe library capabilities */ @@ -488,8 +493,10 @@ ZMQ_EXPORT int zmq_device (int type, void *frontend, void *backend); ZMQ_EXPORT int zmq_sendmsg (void *s, zmq_msg_t *msg, int flags); ZMQ_EXPORT int zmq_recvmsg (void *s, zmq_msg_t *msg, int flags); struct iovec; -ZMQ_EXPORT int zmq_sendiov (void *s, struct iovec *iov, size_t count, int flags); -ZMQ_EXPORT int zmq_recviov (void *s, struct iovec *iov, size_t *count, int flags); +ZMQ_EXPORT int +zmq_sendiov (void *s, struct iovec *iov, size_t count, int flags); +ZMQ_EXPORT int +zmq_recviov (void *s, struct iovec *iov, size_t *count, int flags); /******************************************************************************/ /* Encryption functions */ @@ -507,7 +514,8 @@ ZMQ_EXPORT int zmq_curve_keypair (char *z85_public_key, char *z85_secret_key); /* Derive the z85-encoded public key from the z85-encoded secret key. */ /* Returns 0 on success. */ -ZMQ_EXPORT int zmq_curve_public (char *z85_public_key, const char *z85_secret_key); +ZMQ_EXPORT int zmq_curve_public (char *z85_public_key, + const char *z85_secret_key); /******************************************************************************/ /* Atomic utility methods */ @@ -540,13 +548,13 @@ ZMQ_EXPORT unsigned long zmq_stopwatch_stop (void *watch_); /* Sleeps for specified number of seconds. */ ZMQ_EXPORT void zmq_sleep (int seconds_); -typedef void (zmq_thread_fn) (void*); +typedef void(zmq_thread_fn) (void *); /* Start a thread. Returns a handle to the thread. */ -ZMQ_EXPORT void *zmq_threadstart (zmq_thread_fn* func, void* arg); +ZMQ_EXPORT void *zmq_threadstart (zmq_thread_fn *func, void *arg); /* Wait for thread to complete then free up resources. */ -ZMQ_EXPORT void zmq_threadclose (void* thread); +ZMQ_EXPORT void zmq_threadclose (void *thread); /******************************************************************************/ @@ -573,16 +581,16 @@ ZMQ_EXPORT void zmq_threadclose (void* thread); /* DRAFT 0MQ socket events and monitoring */ /* Unspecified system errors during handshake. Event value is an errno. */ -#define ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL 0x0800 +#define ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL 0x0800 /* Handshake complete successfully with successful authentication (if * * enabled). Event value is unused. */ -#define ZMQ_EVENT_HANDSHAKE_SUCCEEDED 0x1000 +#define ZMQ_EVENT_HANDSHAKE_SUCCEEDED 0x1000 /* Protocol errors between ZMTP peers or between server and ZAP handler. * * Event value is one of ZMQ_PROTOCOL_ERROR_* */ -#define ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL 0x2000 +#define ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL 0x2000 /* Failed authentication requests. Event value is the numeric ZAP status * * code, i.e. 300, 400 or 500. */ -#define ZMQ_EVENT_HANDSHAKE_FAILED_AUTH 0x4000 +#define ZMQ_EVENT_HANDSHAKE_FAILED_AUTH 0x4000 #define ZMQ_PROTOCOL_ERROR_ZMTP_UNSPECIFIED 0x10000000 #define ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND 0x10000001 @@ -601,7 +609,7 @@ ZMQ_EXPORT void zmq_threadclose (void* thread); #define ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC 0x11000001 #define ZMQ_PROTOCOL_ERROR_ZMTP_MECHANISM_MISMATCH 0x11000002 -#define ZMQ_PROTOCOL_ERROR_ZAP_UNSPECIFIED 0x20000000 +#define ZMQ_PROTOCOL_ERROR_ZAP_UNSPECIFIED 0x20000000 #define ZMQ_PROTOCOL_ERROR_ZAP_MALFORMED_REPLY 0x20000001 #define ZMQ_PROTOCOL_ERROR_ZAP_BAD_REQUEST_ID 0x20000002 #define ZMQ_PROTOCOL_ERROR_ZAP_BAD_VERSION 0x20000003 @@ -619,16 +627,16 @@ ZMQ_EXPORT int zmq_join (void *s, const char *group); ZMQ_EXPORT int zmq_leave (void *s, const char *group); /* DRAFT Msg methods. */ -ZMQ_EXPORT int zmq_msg_set_routing_id(zmq_msg_t *msg, uint32_t routing_id); -ZMQ_EXPORT uint32_t zmq_msg_routing_id(zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_set_group(zmq_msg_t *msg, const char *group); -ZMQ_EXPORT const char *zmq_msg_group(zmq_msg_t *msg); +ZMQ_EXPORT int zmq_msg_set_routing_id (zmq_msg_t *msg, uint32_t routing_id); +ZMQ_EXPORT uint32_t zmq_msg_routing_id (zmq_msg_t *msg); +ZMQ_EXPORT int zmq_msg_set_group (zmq_msg_t *msg, const char *group); +ZMQ_EXPORT const char *zmq_msg_group (zmq_msg_t *msg); /* DRAFT Msg property names. */ -#define ZMQ_MSG_PROPERTY_ROUTING_ID "Routing-Id" -#define ZMQ_MSG_PROPERTY_SOCKET_TYPE "Socket-Type" -#define ZMQ_MSG_PROPERTY_USER_ID "User-Id" -#define ZMQ_MSG_PROPERTY_PEER_ADDRESS "Peer-Address" +#define ZMQ_MSG_PROPERTY_ROUTING_ID "Routing-Id" +#define ZMQ_MSG_PROPERTY_SOCKET_TYPE "Socket-Type" +#define ZMQ_MSG_PROPERTY_USER_ID "User-Id" +#define ZMQ_MSG_PROPERTY_PEER_ADDRESS "Peer-Address" /******************************************************************************/ /* Poller polling on sockets,fd and thread-safe sockets */ @@ -649,19 +657,26 @@ typedef struct zmq_poller_event_t } zmq_poller_event_t; ZMQ_EXPORT void *zmq_poller_new (void); -ZMQ_EXPORT int zmq_poller_destroy (void **poller_p); -ZMQ_EXPORT int zmq_poller_add (void *poller, void *socket, void *user_data, short events); -ZMQ_EXPORT int zmq_poller_modify (void *poller, void *socket, short events); -ZMQ_EXPORT int zmq_poller_remove (void *poller, void *socket); -ZMQ_EXPORT int zmq_poller_wait (void *poller, zmq_poller_event_t *event, long timeout); -ZMQ_EXPORT int zmq_poller_wait_all (void *poller, zmq_poller_event_t *events, int n_events, long timeout); +ZMQ_EXPORT int zmq_poller_destroy (void **poller_p); +ZMQ_EXPORT int +zmq_poller_add (void *poller, void *socket, void *user_data, short events); +ZMQ_EXPORT int zmq_poller_modify (void *poller, void *socket, short events); +ZMQ_EXPORT int zmq_poller_remove (void *poller, void *socket); +ZMQ_EXPORT int +zmq_poller_wait (void *poller, zmq_poller_event_t *event, long timeout); +ZMQ_EXPORT int zmq_poller_wait_all (void *poller, + zmq_poller_event_t *events, + int n_events, + long timeout); #if defined _WIN32 -ZMQ_EXPORT int zmq_poller_add_fd (void *poller, SOCKET fd, void *user_data, short events); +ZMQ_EXPORT int +zmq_poller_add_fd (void *poller, SOCKET fd, void *user_data, short events); ZMQ_EXPORT int zmq_poller_modify_fd (void *poller, SOCKET fd, short events); ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, SOCKET fd); #else -ZMQ_EXPORT int zmq_poller_add_fd (void *poller, int fd, void *user_data, short events); +ZMQ_EXPORT int +zmq_poller_add_fd (void *poller, int fd, void *user_data, short events); ZMQ_EXPORT int zmq_poller_modify_fd (void *poller, int fd, short events); ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, int fd); #endif @@ -676,16 +691,18 @@ ZMQ_EXPORT int zmq_socket_get_peer_state (void *socket, #define ZMQ_HAVE_TIMERS -typedef void (zmq_timer_fn)(int timer_id, void *arg); +typedef void(zmq_timer_fn) (int timer_id, void *arg); ZMQ_EXPORT void *zmq_timers_new (void); -ZMQ_EXPORT int zmq_timers_destroy (void **timers_p); -ZMQ_EXPORT int zmq_timers_add (void *timers, size_t interval, zmq_timer_fn handler, void *arg); -ZMQ_EXPORT int zmq_timers_cancel (void *timers, int timer_id); -ZMQ_EXPORT int zmq_timers_set_interval (void *timers, int timer_id, size_t interval); -ZMQ_EXPORT int zmq_timers_reset (void *timers, int timer_id); -ZMQ_EXPORT long zmq_timers_timeout (void *timers); -ZMQ_EXPORT int zmq_timers_execute (void *timers); +ZMQ_EXPORT int zmq_timers_destroy (void **timers_p); +ZMQ_EXPORT int +zmq_timers_add (void *timers, size_t interval, zmq_timer_fn handler, void *arg); +ZMQ_EXPORT int zmq_timers_cancel (void *timers, int timer_id); +ZMQ_EXPORT int +zmq_timers_set_interval (void *timers, int timer_id, size_t interval); +ZMQ_EXPORT int zmq_timers_reset (void *timers, int timer_id); +ZMQ_EXPORT long zmq_timers_timeout (void *timers); +ZMQ_EXPORT int zmq_timers_execute (void *timers); /******************************************************************************/ /* GSSAPI definitions */ diff --git a/include/zmq_utils.h b/include/zmq_utils.h index f29638d553..b9398d57e1 100644 --- a/include/zmq_utils.h +++ b/include/zmq_utils.h @@ -34,14 +34,16 @@ compilers even have an equivalent concept. So in the worst case, this include file is treated as silently empty. */ -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) || defined(_MSC_VER) +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) \ + || defined(_MSC_VER) #if defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic push #pragma GCC diagnostic warning "-Wcpp" #pragma GCC diagnostic ignored "-Werror" #pragma GCC diagnostic ignored "-Wall" #endif -#pragma message("Warning: zmq_utils.h is deprecated. All its functionality is provided by zmq.h.") +#pragma message( \ + "Warning: zmq_utils.h is deprecated. All its functionality is provided by zmq.h.") #if defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic pop #endif diff --git a/perf/inproc_lat.cpp b/perf/inproc_lat.cpp index 19dae8d22a..bf89e9983f 100644 --- a/perf/inproc_lat.cpp +++ b/perf/inproc_lat.cpp @@ -106,7 +106,7 @@ static void *worker (void *ctx_) #endif } -int main (int argc, char *argv []) +int main (int argc, char *argv[]) { #if defined ZMQ_HAVE_WINDOWS HANDLE local_thread; @@ -127,8 +127,8 @@ int main (int argc, char *argv []) return 1; } - message_size = atoi (argv [1]); - roundtrip_count = atoi (argv [2]); + message_size = atoi (argv[1]); + roundtrip_count = atoi (argv[2]); ctx = zmq_init (1); if (!ctx) { @@ -149,8 +149,7 @@ int main (int argc, char *argv []) } #if defined ZMQ_HAVE_WINDOWS - local_thread = (HANDLE) _beginthreadex (NULL, 0, - worker, ctx, 0 , NULL); + local_thread = (HANDLE) _beginthreadex (NULL, 0, worker, ctx, 0, NULL); if (local_thread == 0) { printf ("error in _beginthreadex\n"); return -1; @@ -237,4 +236,3 @@ int main (int argc, char *argv []) return 0; } - diff --git a/perf/inproc_thr.cpp b/perf/inproc_thr.cpp index e16d5b34a2..2dcf64228d 100644 --- a/perf/inproc_thr.cpp +++ b/perf/inproc_thr.cpp @@ -71,7 +71,6 @@ static void *worker (void *ctx_) } for (i = 0; i != message_count; i++) { - rc = zmq_msg_init_size (&msg, message_size); if (rc != 0) { printf ("error in zmq_msg_init_size: %s\n", zmq_strerror (errno)); @@ -106,7 +105,7 @@ static void *worker (void *ctx_) #endif } -int main (int argc, char *argv []) +int main (int argc, char *argv[]) { #if defined ZMQ_HAVE_WINDOWS HANDLE local_thread; @@ -128,8 +127,8 @@ int main (int argc, char *argv []) return 1; } - message_size = atoi (argv [1]); - message_count = atoi (argv [2]); + message_size = atoi (argv[1]); + message_count = atoi (argv[2]); ctx = zmq_init (1); if (!ctx) { @@ -150,8 +149,7 @@ int main (int argc, char *argv []) } #if defined ZMQ_HAVE_WINDOWS - local_thread = (HANDLE) _beginthreadex (NULL, 0, - worker, ctx, 0 , NULL); + local_thread = (HANDLE) _beginthreadex (NULL, 0, worker, ctx, 0, NULL); if (local_thread == 0) { printf ("error in _beginthreadex\n"); return -1; @@ -238,8 +236,8 @@ int main (int argc, char *argv []) return -1; } - throughput = (unsigned long) - ((double) message_count / (double) elapsed * 1000000); + throughput = + (unsigned long) ((double) message_count / (double) elapsed * 1000000); megabits = (double) (throughput * message_size * 8) / 1000000; printf ("mean throughput: %d [msg/s]\n", (int) throughput); @@ -247,4 +245,3 @@ int main (int argc, char *argv []) return 0; } - diff --git a/perf/local_lat.cpp b/perf/local_lat.cpp index 09e4cc291c..dc14cc30dc 100644 --- a/perf/local_lat.cpp +++ b/perf/local_lat.cpp @@ -31,7 +31,7 @@ #include #include -int main (int argc, char *argv []) +int main (int argc, char *argv[]) { const char *bind_to; int roundtrip_count; @@ -44,12 +44,12 @@ int main (int argc, char *argv []) if (argc != 4) { printf ("usage: local_lat " - "\n"); + "\n"); return 1; } - bind_to = argv [1]; - message_size = atoi (argv [2]); - roundtrip_count = atoi (argv [3]); + bind_to = argv[1]; + message_size = atoi (argv[2]); + roundtrip_count = atoi (argv[3]); ctx = zmq_init (1); if (!ctx) { diff --git a/perf/local_thr.cpp b/perf/local_thr.cpp index c3de7f2706..07dd75b130 100644 --- a/perf/local_thr.cpp +++ b/perf/local_thr.cpp @@ -34,7 +34,7 @@ // keys are arbitrary but must match remote_lat.cpp const char server_prvkey[] = "{X}#>t#jRGaQ}gMhv=30r(Mw+87YGs+5%kh=i@f8"; -int main (int argc, char *argv []) +int main (int argc, char *argv[]) { const char *bind_to; int message_count; @@ -51,13 +51,14 @@ int main (int argc, char *argv []) int curve = 0; if (argc != 4 && argc != 5) { - printf ("usage: local_thr []\n"); + printf ("usage: local_thr " + "[]\n"); return 1; } - bind_to = argv [1]; - message_size = atoi (argv [2]); - message_count = atoi (argv [3]); - if (argc >= 5 && atoi (argv [4])) { + bind_to = argv[1]; + message_size = atoi (argv[2]); + message_count = atoi (argv[3]); + if (argc >= 5 && atoi (argv[4])) { curve = 1; } @@ -76,13 +77,14 @@ int main (int argc, char *argv []) // Add your socket options here. // For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. if (curve) { - rc = zmq_setsockopt (s, ZMQ_CURVE_SECRETKEY, server_prvkey, sizeof(server_prvkey)); + rc = zmq_setsockopt (s, ZMQ_CURVE_SECRETKEY, server_prvkey, + sizeof (server_prvkey)); if (rc != 0) { printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno)); return -1; } int server = 1; - rc = zmq_setsockopt (s, ZMQ_CURVE_SERVER, &server, sizeof(int)); + rc = zmq_setsockopt (s, ZMQ_CURVE_SERVER, &server, sizeof (int)); if (rc != 0) { printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno)); return -1; @@ -135,8 +137,7 @@ int main (int argc, char *argv []) return -1; } - throughput = - ((double) message_count / (double) elapsed * 1000000); + throughput = ((double) message_count / (double) elapsed * 1000000); megabits = ((double) throughput * message_size * 8) / 1000000; printf ("message size: %d [B]\n", (int) message_size); diff --git a/perf/remote_lat.cpp b/perf/remote_lat.cpp index f9f59408cf..a21b0a5d28 100644 --- a/perf/remote_lat.cpp +++ b/perf/remote_lat.cpp @@ -32,7 +32,7 @@ #include #include -int main (int argc, char *argv []) +int main (int argc, char *argv[]) { const char *connect_to; int roundtrip_count; @@ -48,12 +48,12 @@ int main (int argc, char *argv []) if (argc != 4) { printf ("usage: remote_lat " - "\n"); + "\n"); return 1; } - connect_to = argv [1]; - message_size = atoi (argv [2]); - roundtrip_count = atoi (argv [3]); + connect_to = argv[1]; + message_size = atoi (argv[2]); + roundtrip_count = atoi (argv[3]); ctx = zmq_init (1); if (!ctx) { diff --git a/perf/remote_thr.cpp b/perf/remote_thr.cpp index e190f0acf1..8378950cd9 100644 --- a/perf/remote_thr.cpp +++ b/perf/remote_thr.cpp @@ -37,7 +37,7 @@ const char server_pubkey[] = "DX4nh=yUn{-9ugra0X3Src4SU-4xTgqxcYY.+ " - " []\n"); + " []\n"); return 1; } - connect_to = argv [1]; - message_size = atoi (argv [2]); - message_count = atoi (argv [3]); - if (argc >= 5 && atoi (argv [4])) { + connect_to = argv[1]; + message_size = atoi (argv[2]); + message_count = atoi (argv[3]); + if (argc >= 5 && atoi (argv[4])) { curve = 1; } @@ -76,19 +76,22 @@ int main (int argc, char *argv []) // Add your socket options here. // For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. if (curve) { - rc = zmq_setsockopt (s, ZMQ_CURVE_SECRETKEY, client_prvkey, sizeof (client_prvkey)); + rc = zmq_setsockopt (s, ZMQ_CURVE_SECRETKEY, client_prvkey, + sizeof (client_prvkey)); if (rc != 0) { printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno)); return -1; } - - rc = zmq_setsockopt (s, ZMQ_CURVE_PUBLICKEY, client_pubkey, sizeof (client_pubkey)); + + rc = zmq_setsockopt (s, ZMQ_CURVE_PUBLICKEY, client_pubkey, + sizeof (client_pubkey)); if (rc != 0) { printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno)); return -1; } - - rc = zmq_setsockopt (s, ZMQ_CURVE_SERVERKEY, server_pubkey, sizeof (server_pubkey)); + + rc = zmq_setsockopt (s, ZMQ_CURVE_SERVERKEY, server_pubkey, + sizeof (server_pubkey)); if (rc != 0) { printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno)); return -1; diff --git a/src/address.cpp b/src/address.cpp index 6e3d9954df..a14e5d0784 100644 --- a/src/address.cpp +++ b/src/address.cpp @@ -44,11 +44,12 @@ #include #include -zmq::address_t::address_t ( - const std::string &protocol_, const std::string &address_, ctx_t *parent_) - : protocol (protocol_), - address (address_), - parent (parent_) +zmq::address_t::address_t (const std::string &protocol_, + const std::string &address_, + ctx_t *parent_) : + protocol (protocol_), + address (address_), + parent (parent_) { memset (&resolved, 0, sizeof resolved); } @@ -57,35 +58,32 @@ zmq::address_t::~address_t () { if (protocol == "tcp") { if (resolved.tcp_addr) { - LIBZMQ_DELETE(resolved.tcp_addr); + LIBZMQ_DELETE (resolved.tcp_addr); } } if (protocol == "udp") { if (resolved.udp_addr) { - LIBZMQ_DELETE(resolved.udp_addr); + LIBZMQ_DELETE (resolved.udp_addr); } } #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS - else - if (protocol == "ipc") { + else if (protocol == "ipc") { if (resolved.ipc_addr) { - LIBZMQ_DELETE(resolved.ipc_addr); + LIBZMQ_DELETE (resolved.ipc_addr); } } #endif #if defined ZMQ_HAVE_TIPC - else - if (protocol == "tipc") { + else if (protocol == "tipc") { if (resolved.tipc_addr) { - LIBZMQ_DELETE(resolved.tipc_addr); + LIBZMQ_DELETE (resolved.tipc_addr); } } #endif #if defined ZMQ_HAVE_VMCI - else - if (protocol == "vmci") { + else if (protocol == "vmci") { if (resolved.vmci_addr) { - LIBZMQ_DELETE(resolved.vmci_addr); + LIBZMQ_DELETE (resolved.vmci_addr); } } #endif @@ -102,22 +100,19 @@ int zmq::address_t::to_string (std::string &addr_) const return resolved.udp_addr->to_string (addr_); } #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS - else - if (protocol == "ipc") { + else if (protocol == "ipc") { if (resolved.ipc_addr) return resolved.ipc_addr->to_string (addr_); } #endif #if defined ZMQ_HAVE_TIPC - else - if (protocol == "tipc") { + else if (protocol == "tipc") { if (resolved.tipc_addr) return resolved.tipc_addr->to_string (addr_); } #endif #if defined ZMQ_HAVE_VMCI - else - if (protocol == "vmci") { + else if (protocol == "vmci") { if (resolved.vmci_addr) return resolved.vmci_addr->to_string (addr_); } diff --git a/src/address.hpp b/src/address.hpp index 61feb4287a..f94d9ad6c6 100644 --- a/src/address.hpp +++ b/src/address.hpp @@ -34,44 +34,48 @@ namespace zmq { - class ctx_t; - class tcp_address_t; - class udp_address_t; +class ctx_t; +class tcp_address_t; +class udp_address_t; #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS - class ipc_address_t; +class ipc_address_t; #endif #if defined ZMQ_HAVE_LINUX - class tipc_address_t; +class tipc_address_t; #endif #if defined ZMQ_HAVE_VMCI - class vmci_address_t; +class vmci_address_t; #endif - struct address_t { - address_t (const std::string &protocol_, const std::string &address_, ctx_t *parent_); +struct address_t +{ + address_t (const std::string &protocol_, + const std::string &address_, + ctx_t *parent_); - ~address_t (); + ~address_t (); - const std::string protocol; - const std::string address; - ctx_t *parent; + const std::string protocol; + const std::string address; + ctx_t *parent; - // Protocol specific resolved address - union { - tcp_address_t *tcp_addr; - udp_address_t *udp_addr; + // Protocol specific resolved address + union + { + tcp_address_t *tcp_addr; + udp_address_t *udp_addr; #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS - ipc_address_t *ipc_addr; + ipc_address_t *ipc_addr; #endif #if defined ZMQ_HAVE_LINUX - tipc_address_t *tipc_addr; + tipc_address_t *tipc_addr; #endif #if defined ZMQ_HAVE_VMCI - vmci_address_t *vmci_addr; + vmci_address_t *vmci_addr; #endif - } resolved; + } resolved; - int to_string (std::string &addr_) const; - }; + int to_string (std::string &addr_) const; +}; } #endif diff --git a/src/array.hpp b/src/array.hpp index c6b5d93d7c..de252c06c5 100644 --- a/src/array.hpp +++ b/src/array.hpp @@ -35,133 +35,101 @@ namespace zmq { - // Implementation of fast arrays with O(1) access, insertion and - // removal. The array stores pointers rather than objects. - // O(1) is achieved by making items inheriting from - // array_item_t class which internally stores the position - // in the array. - // The ID template argument is used to differentiate among arrays - // and thus let an object be stored in different arrays. - - // Base class for objects stored in the array. If you want to store - // same object in multiple arrays, each of those arrays has to have - // different ID. The item itself has to be derived from instantiations of - // array_item_t template for all relevant IDs. - - template class array_item_t - { - public: +// Implementation of fast arrays with O(1) access, insertion and +// removal. The array stores pointers rather than objects. +// O(1) is achieved by making items inheriting from +// array_item_t class which internally stores the position +// in the array. +// The ID template argument is used to differentiate among arrays +// and thus let an object be stored in different arrays. + +// Base class for objects stored in the array. If you want to store +// same object in multiple arrays, each of those arrays has to have +// different ID. The item itself has to be derived from instantiations of +// array_item_t template for all relevant IDs. + +template class array_item_t +{ + public: + inline array_item_t () : array_index (-1) {} + + // The destructor doesn't have to be virtual. It is made virtual + // just to keep ICC and code checking tools from complaining. + inline virtual ~array_item_t () {} + + inline void set_array_index (int index_) { array_index = index_; } + + inline int get_array_index () { return array_index; } - inline array_item_t () : - array_index (-1) - { - } + private: + int array_index; - // The destructor doesn't have to be virtual. It is made virtual - // just to keep ICC and code checking tools from complaining. - inline virtual ~array_item_t () - { - } + array_item_t (const array_item_t &); + const array_item_t &operator= (const array_item_t &); +}; - inline void set_array_index (int index_) - { - array_index = index_; - } - inline int get_array_index () - { - return array_index; - } +template class array_t +{ + private: + typedef array_item_t item_t; + + public: + typedef typename std::vector::size_type size_type; + + inline array_t () {} - private: + inline ~array_t () {} - int array_index; + inline size_type size () { return items.size (); } - array_item_t (const array_item_t&); - const array_item_t &operator = (const array_item_t&); - }; + inline bool empty () { return items.empty (); } + inline T *&operator[] (size_type index_) { return items[index_]; } + + inline void push_back (T *item_) + { + if (item_) + ((item_t *) item_)->set_array_index ((int) items.size ()); + items.push_back (item_); + } - template class array_t + inline void erase (T *item_) { - private: - - typedef array_item_t item_t; - - public: - - typedef typename std::vector ::size_type size_type; - - inline array_t () - { - } - - inline ~array_t () - { - } - - inline size_type size () - { - return items.size (); - } - - inline bool empty () - { - return items.empty (); - } - - inline T *&operator [] (size_type index_) - { - return items [index_]; - } - - inline void push_back (T *item_) - { - if (item_) - ((item_t*) item_)->set_array_index ((int) items.size ()); - items.push_back (item_); - } - - inline void erase (T *item_) { - erase (((item_t*) item_)->get_array_index ()); - } - - inline void erase (size_type index_) { - if (items.back ()) - ((item_t*) items.back ())->set_array_index ((int) index_); - items [index_] = items.back (); - items.pop_back (); - } - - inline void swap (size_type index1_, size_type index2_) - { - if (items [index1_]) - ((item_t*) items [index1_])->set_array_index ((int) index2_); - if (items [index2_]) - ((item_t*) items [index2_])->set_array_index ((int) index1_); - std::swap (items [index1_], items [index2_]); - } - - inline void clear () - { - items.clear (); - } - - inline size_type index (T *item_) - { - return (size_type) ((item_t*) item_)->get_array_index (); - } - - private: - - typedef std::vector items_t; - items_t items; - - array_t (const array_t&); - const array_t &operator = (const array_t&); - }; + erase (((item_t *) item_)->get_array_index ()); + } + inline void erase (size_type index_) + { + if (items.back ()) + ((item_t *) items.back ())->set_array_index ((int) index_); + items[index_] = items.back (); + items.pop_back (); + } + + inline void swap (size_type index1_, size_type index2_) + { + if (items[index1_]) + ((item_t *) items[index1_])->set_array_index ((int) index2_); + if (items[index2_]) + ((item_t *) items[index2_])->set_array_index ((int) index1_); + std::swap (items[index1_], items[index2_]); + } + + inline void clear () { items.clear (); } + + inline size_type index (T *item_) + { + return (size_type) ((item_t *) item_)->get_array_index (); + } + + private: + typedef std::vector items_t; + items_t items; + + array_t (const array_t &); + const array_t &operator= (const array_t &); +}; } #endif - diff --git a/src/atomic_counter.hpp b/src/atomic_counter.hpp index 23a7c50869..e8a0e6c3bd 100644 --- a/src/atomic_counter.hpp +++ b/src/atomic_counter.hpp @@ -44,7 +44,8 @@ #define ZMQ_ATOMIC_COUNTER_ARM #elif defined ZMQ_HAVE_WINDOWS #define ZMQ_ATOMIC_COUNTER_WINDOWS -#elif (defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_NETBSD || defined ZMQ_HAVE_GNU) +#elif (defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_NETBSD \ + || defined ZMQ_HAVE_GNU) #define ZMQ_ATOMIC_COUNTER_ATOMIC_H #elif defined __tile__ #define ZMQ_ATOMIC_COUNTER_TILE @@ -66,174 +67,158 @@ namespace zmq { - - // This class represents an integer that can be incremented/decremented - // in atomic fashion. - // - // In zmq::shared_message_memory_allocator a buffer with an atomic_counter_t - // at the start is allocated. If the class does not align to pointer size, - // access to pointers in structures in the buffer will cause SIGBUS on - // architectures that do not allow mis-aligned pointers (eg: SPARC). - // Force the compiler to align to pointer size, which will cause the object - // to grow from 4 bytes to 8 bytes on 64 bit architectures (when not using - // mutexes). - -#if defined (_MSC_VER) && (defined (_M_X64) || defined (_M_ARM64)) - class __declspec (align (8)) atomic_counter_t -#elif defined (_MSC_VER) && (defined (_M_IX86) || defined (_M_ARM_ARMV7VE)) - class __declspec (align (4)) atomic_counter_t +// This class represents an integer that can be incremented/decremented +// in atomic fashion. +// +// In zmq::shared_message_memory_allocator a buffer with an atomic_counter_t +// at the start is allocated. If the class does not align to pointer size, +// access to pointers in structures in the buffer will cause SIGBUS on +// architectures that do not allow mis-aligned pointers (eg: SPARC). +// Force the compiler to align to pointer size, which will cause the object +// to grow from 4 bytes to 8 bytes on 64 bit architectures (when not using +// mutexes). + +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) +class __declspec(align (8)) atomic_counter_t +#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_ARM_ARMV7VE)) +class __declspec(align (4)) atomic_counter_t #else - class atomic_counter_t +class atomic_counter_t #endif - { - public: - - typedef uint32_t integer_t; +{ + public: + typedef uint32_t integer_t; - inline atomic_counter_t (integer_t value_ = 0) : - value (value_) - { - } + inline atomic_counter_t (integer_t value_ = 0) : value (value_) {} - inline ~atomic_counter_t () - { - } + inline ~atomic_counter_t () {} - // Set counter value (not thread-safe). - inline void set (integer_t value_) - { - value = value_; - } + // Set counter value (not thread-safe). + inline void set (integer_t value_) { value = value_; } - // Atomic addition. Returns the old value. - inline integer_t add (integer_t increment_) - { - integer_t old_value; + // Atomic addition. Returns the old value. + inline integer_t add (integer_t increment_) + { + integer_t old_value; #if defined ZMQ_ATOMIC_COUNTER_WINDOWS - old_value = InterlockedExchangeAdd ((LONG*) &value, increment_); + old_value = InterlockedExchangeAdd ((LONG *) &value, increment_); #elif defined ZMQ_ATOMIC_COUNTER_INTRINSIC - old_value = __atomic_fetch_add(&value, increment_, __ATOMIC_ACQ_REL); + old_value = __atomic_fetch_add (&value, increment_, __ATOMIC_ACQ_REL); #elif defined ZMQ_ATOMIC_COUNTER_CXX11 - old_value = value.fetch_add(increment_, std::memory_order_acq_rel); + old_value = value.fetch_add (increment_, std::memory_order_acq_rel); #elif defined ZMQ_ATOMIC_COUNTER_ATOMIC_H - integer_t new_value = atomic_add_32_nv (&value, increment_); - old_value = new_value - increment_; + integer_t new_value = atomic_add_32_nv (&value, increment_); + old_value = new_value - increment_; #elif defined ZMQ_ATOMIC_COUNTER_TILE - old_value = arch_atomic_add (&value, increment_); + old_value = arch_atomic_add (&value, increment_); #elif defined ZMQ_ATOMIC_COUNTER_X86 - __asm__ volatile ( - "lock; xadd %0, %1 \n\t" - : "=r" (old_value), "=m" (value) - : "0" (increment_), "m" (value) - : "cc", "memory"); + __asm__ volatile("lock; xadd %0, %1 \n\t" + : "=r"(old_value), "=m"(value) + : "0"(increment_), "m"(value) + : "cc", "memory"); #elif defined ZMQ_ATOMIC_COUNTER_ARM - integer_t flag, tmp; - __asm__ volatile ( - " dmb sy\n\t" - "1: ldrex %0, [%5]\n\t" - " add %2, %0, %4\n\t" - " strex %1, %2, [%5]\n\t" - " teq %1, #0\n\t" - " bne 1b\n\t" - " dmb sy\n\t" - : "=&r"(old_value), "=&r"(flag), "=&r"(tmp), "+Qo"(value) - : "Ir"(increment_), "r"(&value) - : "cc"); + integer_t flag, tmp; + __asm__ volatile(" dmb sy\n\t" + "1: ldrex %0, [%5]\n\t" + " add %2, %0, %4\n\t" + " strex %1, %2, [%5]\n\t" + " teq %1, #0\n\t" + " bne 1b\n\t" + " dmb sy\n\t" + : "=&r"(old_value), "=&r"(flag), "=&r"(tmp), + "+Qo"(value) + : "Ir"(increment_), "r"(&value) + : "cc"); #elif defined ZMQ_ATOMIC_COUNTER_MUTEX - sync.lock (); - old_value = value; - value += increment_; - sync.unlock (); + sync.lock (); + old_value = value; + value += increment_; + sync.unlock (); #else #error atomic_counter is not implemented for this platform #endif - return old_value; - } + return old_value; + } - // Atomic subtraction. Returns false if the counter drops to zero. - inline bool sub (integer_t decrement) - { + // Atomic subtraction. Returns false if the counter drops to zero. + inline bool sub (integer_t decrement) + { #if defined ZMQ_ATOMIC_COUNTER_WINDOWS - LONG delta = - ((LONG) decrement); - integer_t old = InterlockedExchangeAdd ((LONG*) &value, delta); - return old - decrement != 0; + LONG delta = -((LONG) decrement); + integer_t old = InterlockedExchangeAdd ((LONG *) &value, delta); + return old - decrement != 0; #elif defined ZMQ_ATOMIC_COUNTER_INTRINSIC - integer_t nv = __atomic_sub_fetch(&value, decrement, __ATOMIC_ACQ_REL); - return nv != 0; + integer_t nv = __atomic_sub_fetch (&value, decrement, __ATOMIC_ACQ_REL); + return nv != 0; #elif defined ZMQ_ATOMIC_COUNTER_CXX11 - integer_t old = value.fetch_sub(decrement, std::memory_order_acq_rel); - return old - decrement != 0; + integer_t old = value.fetch_sub (decrement, std::memory_order_acq_rel); + return old - decrement != 0; #elif defined ZMQ_ATOMIC_COUNTER_ATOMIC_H - int32_t delta = - ((int32_t) decrement); - integer_t nv = atomic_add_32_nv (&value, delta); - return nv != 0; + int32_t delta = -((int32_t) decrement); + integer_t nv = atomic_add_32_nv (&value, delta); + return nv != 0; #elif defined ZMQ_ATOMIC_COUNTER_TILE - int32_t delta = - ((int32_t) decrement); - integer_t nv = arch_atomic_add (&value, delta); - return nv != 0; + int32_t delta = -((int32_t) decrement); + integer_t nv = arch_atomic_add (&value, delta); + return nv != 0; #elif defined ZMQ_ATOMIC_COUNTER_X86 - integer_t oldval = -decrement; - volatile integer_t *val = &value; - __asm__ volatile ("lock; xaddl %0,%1" - : "=r" (oldval), "=m" (*val) - : "0" (oldval), "m" (*val) - : "cc", "memory"); - return oldval != decrement; + integer_t oldval = -decrement; + volatile integer_t *val = &value; + __asm__ volatile("lock; xaddl %0,%1" + : "=r"(oldval), "=m"(*val) + : "0"(oldval), "m"(*val) + : "cc", "memory"); + return oldval != decrement; #elif defined ZMQ_ATOMIC_COUNTER_ARM - integer_t old_value, flag, tmp; - __asm__ volatile ( - " dmb sy\n\t" - "1: ldrex %0, [%5]\n\t" - " sub %2, %0, %4\n\t" - " strex %1, %2, [%5]\n\t" - " teq %1, #0\n\t" - " bne 1b\n\t" - " dmb sy\n\t" - : "=&r"(old_value), "=&r"(flag), "=&r"(tmp), "+Qo"(value) - : "Ir"(decrement), "r"(&value) - : "cc"); - return old_value - decrement != 0; + integer_t old_value, flag, tmp; + __asm__ volatile(" dmb sy\n\t" + "1: ldrex %0, [%5]\n\t" + " sub %2, %0, %4\n\t" + " strex %1, %2, [%5]\n\t" + " teq %1, #0\n\t" + " bne 1b\n\t" + " dmb sy\n\t" + : "=&r"(old_value), "=&r"(flag), "=&r"(tmp), + "+Qo"(value) + : "Ir"(decrement), "r"(&value) + : "cc"); + return old_value - decrement != 0; #elif defined ZMQ_ATOMIC_COUNTER_MUTEX - sync.lock (); - value -= decrement; - bool result = value ? true : false; - sync.unlock (); - return result; + sync.lock (); + value -= decrement; + bool result = value ? true : false; + sync.unlock (); + return result; #else #error atomic_counter is not implemented for this platform #endif - } + } - inline integer_t get () const - { - return value; - } - - private: + inline integer_t get () const { return value; } + private: #if defined ZMQ_ATOMIC_COUNTER_CXX11 - std::atomic value; + std::atomic value; #else - volatile integer_t value; + volatile integer_t value; #endif #if defined ZMQ_ATOMIC_COUNTER_MUTEX - mutex_t sync; + mutex_t sync; #endif -#if ! defined ZMQ_ATOMIC_COUNTER_CXX11 - atomic_counter_t (const atomic_counter_t&); - const atomic_counter_t& operator = (const atomic_counter_t&); +#if !defined ZMQ_ATOMIC_COUNTER_CXX11 + atomic_counter_t (const atomic_counter_t &); + const atomic_counter_t &operator= (const atomic_counter_t &); #endif -#if defined (__GNUC__) || defined ( __INTEL_COMPILER) || \ - (defined (__SUNPRO_C) && __SUNPRO_C >= 0x590) || \ - (defined (__SUNPRO_CC) && __SUNPRO_CC >= 0x590) - } __attribute__ ((aligned (sizeof (void *)))); +#if defined(__GNUC__) || defined(__INTEL_COMPILER) \ + || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x590) \ + || (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x590) +} __attribute__ ((aligned (sizeof (void *)))); #else - }; +}; #endif - } // Remove macros local to this file. diff --git a/src/atomic_ptr.hpp b/src/atomic_ptr.hpp index 53b0d5da17..875a41762c 100644 --- a/src/atomic_ptr.hpp +++ b/src/atomic_ptr.hpp @@ -44,7 +44,8 @@ #define ZMQ_ATOMIC_PTR_TILE #elif defined ZMQ_HAVE_WINDOWS #define ZMQ_ATOMIC_PTR_WINDOWS -#elif (defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_NETBSD || defined ZMQ_HAVE_GNU) +#elif (defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_NETBSD \ + || defined ZMQ_HAVE_GNU) #define ZMQ_ATOMIC_PTR_ATOMIC_H #else #define ZMQ_ATOMIC_PTR_MUTEX @@ -64,154 +65,138 @@ namespace zmq { +// This class encapsulates several atomic operations on pointers. - // This class encapsulates several atomic operations on pointers. +template class atomic_ptr_t +{ + public: + // Initialise atomic pointer + inline atomic_ptr_t () { ptr = NULL; } + + // Destroy atomic pointer + inline ~atomic_ptr_t () {} + + // Set value of atomic pointer in a non-threadsafe way + // Use this function only when you are sure that at most one + // thread is accessing the pointer at the moment. + inline void set (T *ptr_) { this->ptr = ptr_; } - template class atomic_ptr_t + // Perform atomic 'exchange pointers' operation. Pointer is set + // to the 'val' value. Old value is returned. + inline T *xchg (T *val_) { - public: - - // Initialise atomic pointer - inline atomic_ptr_t () - { - ptr = NULL; - } - - // Destroy atomic pointer - inline ~atomic_ptr_t () - { - } - - // Set value of atomic pointer in a non-threadsafe way - // Use this function only when you are sure that at most one - // thread is accessing the pointer at the moment. - inline void set (T *ptr_) - { - this->ptr = ptr_; - } - - // Perform atomic 'exchange pointers' operation. Pointer is set - // to the 'val' value. Old value is returned. - inline T *xchg (T *val_) - { #if defined ZMQ_ATOMIC_PTR_WINDOWS - return (T*) InterlockedExchangePointer ((PVOID*) &ptr, val_); + return (T *) InterlockedExchangePointer ((PVOID *) &ptr, val_); #elif defined ZMQ_ATOMIC_PTR_INTRINSIC - return (T*) __atomic_exchange_n (&ptr, val_, __ATOMIC_ACQ_REL); + return (T *) __atomic_exchange_n (&ptr, val_, __ATOMIC_ACQ_REL); #elif defined ZMQ_ATOMIC_PTR_CXX11 - return ptr.exchange(val_, std::memory_order_acq_rel); + return ptr.exchange (val_, std::memory_order_acq_rel); #elif defined ZMQ_ATOMIC_PTR_ATOMIC_H - return (T*) atomic_swap_ptr (&ptr, val_); + return (T *) atomic_swap_ptr (&ptr, val_); #elif defined ZMQ_ATOMIC_PTR_TILE - return (T*) arch_atomic_exchange (&ptr, val_); + return (T *) arch_atomic_exchange (&ptr, val_); #elif defined ZMQ_ATOMIC_PTR_X86 - T *old; - __asm__ volatile ( - "lock; xchg %0, %2" - : "=r" (old), "=m" (ptr) - : "m" (ptr), "0" (val_)); - return old; + T *old; + __asm__ volatile("lock; xchg %0, %2" + : "=r"(old), "=m"(ptr) + : "m"(ptr), "0"(val_)); + return old; #elif defined ZMQ_ATOMIC_PTR_ARM - T* old; - unsigned int flag; - __asm__ volatile ( - " dmb sy\n\t" - "1: ldrex %1, [%3]\n\t" - " strex %0, %4, [%3]\n\t" - " teq %0, #0\n\t" - " bne 1b\n\t" - " dmb sy\n\t" - : "=&r"(flag), "=&r"(old), "+Qo"(ptr) - : "r"(&ptr), "r"(val_) - : "cc"); - return old; + T *old; + unsigned int flag; + __asm__ volatile(" dmb sy\n\t" + "1: ldrex %1, [%3]\n\t" + " strex %0, %4, [%3]\n\t" + " teq %0, #0\n\t" + " bne 1b\n\t" + " dmb sy\n\t" + : "=&r"(flag), "=&r"(old), "+Qo"(ptr) + : "r"(&ptr), "r"(val_) + : "cc"); + return old; #elif defined ZMQ_ATOMIC_PTR_MUTEX - sync.lock (); - T *old = (T*) ptr; - ptr = val_; - sync.unlock (); - return old; + sync.lock (); + T *old = (T *) ptr; + ptr = val_; + sync.unlock (); + return old; #else #error atomic_ptr is not implemented for this platform #endif - } - - // Perform atomic 'compare and swap' operation on the pointer. - // The pointer is compared to 'cmp' argument and if they are - // equal, its value is set to 'val'. Old value of the pointer - // is returned. - inline T *cas (T *cmp_, T *val_) - { + } + + // Perform atomic 'compare and swap' operation on the pointer. + // The pointer is compared to 'cmp' argument and if they are + // equal, its value is set to 'val'. Old value of the pointer + // is returned. + inline T *cas (T *cmp_, T *val_) + { #if defined ZMQ_ATOMIC_PTR_WINDOWS - return (T*) InterlockedCompareExchangePointer ( - (volatile PVOID*) &ptr, val_, cmp_); + return (T *) InterlockedCompareExchangePointer ((volatile PVOID *) &ptr, + val_, cmp_); #elif defined ZMQ_ATOMIC_PTR_INTRINSIC - T *old = cmp_; - __atomic_compare_exchange_n (&ptr, (volatile T**) &old, val_, false, - __ATOMIC_RELEASE, __ATOMIC_ACQUIRE); - return old; + T *old = cmp_; + __atomic_compare_exchange_n (&ptr, (volatile T **) &old, val_, false, + __ATOMIC_RELEASE, __ATOMIC_ACQUIRE); + return old; #elif defined ZMQ_ATOMIC_PTR_CXX11 - ptr.compare_exchange_strong(cmp_, val_, std::memory_order_acq_rel); - return cmp_; + ptr.compare_exchange_strong (cmp_, val_, std::memory_order_acq_rel); + return cmp_; #elif defined ZMQ_ATOMIC_PTR_ATOMIC_H - return (T*) atomic_cas_ptr (&ptr, cmp_, val_); + return (T *) atomic_cas_ptr (&ptr, cmp_, val_); #elif defined ZMQ_ATOMIC_PTR_TILE - return (T*) arch_atomic_val_compare_and_exchange (&ptr, cmp_, val_); + return (T *) arch_atomic_val_compare_and_exchange (&ptr, cmp_, val_); #elif defined ZMQ_ATOMIC_PTR_X86 - T *old; - __asm__ volatile ( - "lock; cmpxchg %2, %3" - : "=a" (old), "=m" (ptr) - : "r" (val_), "m" (ptr), "0" (cmp_) - : "cc"); - return old; + T *old; + __asm__ volatile("lock; cmpxchg %2, %3" + : "=a"(old), "=m"(ptr) + : "r"(val_), "m"(ptr), "0"(cmp_) + : "cc"); + return old; #elif defined ZMQ_ATOMIC_PTR_ARM - T *old; - unsigned int flag; - __asm__ volatile ( - " dmb sy\n\t" - "1: ldrex %1, [%3]\n\t" - " mov %0, #0\n\t" - " teq %1, %4\n\t" - " it eq\n\t" - " strexeq %0, %5, [%3]\n\t" - " teq %0, #0\n\t" - " bne 1b\n\t" - " dmb sy\n\t" - : "=&r"(flag), "=&r"(old), "+Qo"(ptr) - : "r"(&ptr), "r"(cmp_), "r"(val_) - : "cc"); - return old; + T *old; + unsigned int flag; + __asm__ volatile(" dmb sy\n\t" + "1: ldrex %1, [%3]\n\t" + " mov %0, #0\n\t" + " teq %1, %4\n\t" + " it eq\n\t" + " strexeq %0, %5, [%3]\n\t" + " teq %0, #0\n\t" + " bne 1b\n\t" + " dmb sy\n\t" + : "=&r"(flag), "=&r"(old), "+Qo"(ptr) + : "r"(&ptr), "r"(cmp_), "r"(val_) + : "cc"); + return old; #elif defined ZMQ_ATOMIC_PTR_MUTEX - sync.lock (); - T *old = (T*) ptr; - if (ptr == cmp_) - ptr = val_; - sync.unlock (); - return old; + sync.lock (); + T *old = (T *) ptr; + if (ptr == cmp_) + ptr = val_; + sync.unlock (); + return old; #else #error atomic_ptr is not implemented for this platform #endif - } - - private: + } + private: #if defined ZMQ_ATOMIC_PTR_CXX11 - std::atomic ptr; + std::atomic ptr; #else - volatile T *ptr; + volatile T *ptr; #endif #if defined ZMQ_ATOMIC_PTR_MUTEX - mutex_t sync; + mutex_t sync; #endif -#if ! defined ZMQ_ATOMIC_PTR_CXX11 - atomic_ptr_t (const atomic_ptr_t&); - const atomic_ptr_t &operator = (const atomic_ptr_t&); +#if !defined ZMQ_ATOMIC_PTR_CXX11 + atomic_ptr_t (const atomic_ptr_t &); + const atomic_ptr_t &operator= (const atomic_ptr_t &); #endif - }; - +}; } // Remove macros local to this file. diff --git a/src/blob.hpp b/src/blob.hpp index 808750ac38..e907f1f09c 100644 --- a/src/blob.hpp +++ b/src/blob.hpp @@ -36,7 +36,7 @@ #if __cplusplus >= 201103L || defined(_MSC_VER) && _MSC_VER > 1700 #define ZMQ_HAS_MOVE_SEMANTICS -#define ZMQ_MAP_INSERT_OR_EMPLACE(k, v) emplace (k,v) +#define ZMQ_MAP_INSERT_OR_EMPLACE(k, v) emplace (k, v) #define ZMQ_PUSH_OR_EMPLACE_BACK emplace_back #define ZMQ_MOVE(x) std::move (x) #else @@ -47,140 +47,140 @@ namespace zmq { - struct reference_tag_t {}; +struct reference_tag_t +{ +}; - // Object to hold dynamically allocated opaque binary data. - // On modern compilers, it will be movable but not copyable. Copies - // must be explicitly created by set_deep_copy. - // On older compilers, it is copyable for syntactical reasons. - struct blob_t +// Object to hold dynamically allocated opaque binary data. +// On modern compilers, it will be movable but not copyable. Copies +// must be explicitly created by set_deep_copy. +// On older compilers, it is copyable for syntactical reasons. +struct blob_t +{ + // Creates an empty blob_t. + blob_t () : data_ (0), size_ (0), owned_ (true) {} + + // Creates a blob_t of a given size, with uninitialized content. + blob_t (const size_t size) : + data_ ((unsigned char *) malloc (size)), + size_ (size), + owned_ (true) { - // Creates an empty blob_t. - blob_t () : data_ (0), size_ (0), owned_ (true) {} - - // Creates a blob_t of a given size, with uninitialized content. - blob_t (const size_t size) - : data_ ((unsigned char*)malloc (size)) - , size_ (size) - , owned_ (true) - { - } - - // Creates a blob_t of a given size, an initializes content by copying - // from another buffer. - blob_t(const unsigned char * const data, const size_t size) - : data_ ((unsigned char*)malloc (size)) - , size_ (size) - , owned_ (true) - { - memcpy(data_, data, size_); - } - - // Creates a blob_t for temporary use that only references a - // pre-allocated block of data. - // Use with caution and ensure that the blob_t will not outlive - // the referenced data. - blob_t (unsigned char * const data, const size_t size, reference_tag_t) - : data_ (data) - , size_ (size) - , owned_ (false) - { - } - - // Returns the size of the blob_t. - size_t size () const { return size_; } - - // Returns a pointer to the data of the blob_t. - const unsigned char *data() const { - return data_; - } + } + + // Creates a blob_t of a given size, an initializes content by copying + // from another buffer. + blob_t (const unsigned char *const data, const size_t size) : + data_ ((unsigned char *) malloc (size)), + size_ (size), + owned_ (true) + { + memcpy (data_, data, size_); + } + + // Creates a blob_t for temporary use that only references a + // pre-allocated block of data. + // Use with caution and ensure that the blob_t will not outlive + // the referenced data. + blob_t (unsigned char *const data, const size_t size, reference_tag_t) : + data_ (data), + size_ (size), + owned_ (false) + { + } - // Returns a pointer to the data of the blob_t. - unsigned char *data() { - return data_; - } + // Returns the size of the blob_t. + size_t size () const { return size_; } - // Defines an order relationship on blob_t. - bool operator< (blob_t const &other) const { - int cmpres = memcmp (data_, other.data_, std::min (size_, other.size_)); - return cmpres < 0 || (cmpres == 0 && size_ < other.size_); - } + // Returns a pointer to the data of the blob_t. + const unsigned char *data () const { return data_; } - // Sets a blob_t to a deep copy of another blob_t. - void set_deep_copy (blob_t const &other) - { - clear (); - data_ = (unsigned char*)malloc (other.size_); - size_ = other.size_; - owned_ = true; - memcpy (data_, other.data_, size_); - } + // Returns a pointer to the data of the blob_t. + unsigned char *data () { return data_; } - // Sets a blob_t to a copy of a given buffer. - void set (const unsigned char * const data, const size_t size) - { - clear (); - data_ = (unsigned char*)malloc (size); - size_ = size; - owned_ = true; - memcpy (data_, data, size_); - } + // Defines an order relationship on blob_t. + bool operator< (blob_t const &other) const + { + int cmpres = memcmp (data_, other.data_, std::min (size_, other.size_)); + return cmpres < 0 || (cmpres == 0 && size_ < other.size_); + } - // Empties a blob_t. - void clear () { - if (owned_) { free (data_); } - data_ = 0; size_ = 0; + // Sets a blob_t to a deep copy of another blob_t. + void set_deep_copy (blob_t const &other) + { + clear (); + data_ = (unsigned char *) malloc (other.size_); + size_ = other.size_; + owned_ = true; + memcpy (data_, other.data_, size_); + } + + // Sets a blob_t to a copy of a given buffer. + void set (const unsigned char *const data, const size_t size) + { + clear (); + data_ = (unsigned char *) malloc (size); + size_ = size; + owned_ = true; + memcpy (data_, data, size_); + } + + // Empties a blob_t. + void clear () + { + if (owned_) { + free (data_); } + data_ = 0; + size_ = 0; + } - ~blob_t () { - if (owned_) { free (data_); } + ~blob_t () + { + if (owned_) { + free (data_); } + } #ifdef ZMQ_HAS_MOVE_SEMANTICS - blob_t (const blob_t &) = delete; - blob_t &operator= (const blob_t &) = delete; - - blob_t (blob_t&& other) - : data_ (other.data_) - , size_ (other.size_) - , owned_ (other.owned_) - { + blob_t (const blob_t &) = delete; + blob_t &operator= (const blob_t &) = delete; + + blob_t (blob_t &&other) : + data_ (other.data_), + size_ (other.size_), + owned_ (other.owned_) + { + other.owned_ = false; + } + blob_t &operator= (blob_t &&other) + { + if (this != &other) { + clear (); + data_ = other.data_; + size_ = other.size_; + owned_ = other.owned_; other.owned_ = false; } - blob_t &operator= (blob_t&& other) { - if (this != &other) - { - clear (); - data_ = other.data_; - size_ = other.size_; - owned_ = other.owned_; - other.owned_ = false; - } - return *this; - } + return *this; + } #else - blob_t (const blob_t &other) - : owned_(false) - { + blob_t (const blob_t &other) : owned_ (false) { set_deep_copy (other); } + blob_t &operator= (const blob_t &other) + { + if (this != &other) { + clear (); set_deep_copy (other); } - blob_t &operator= (const blob_t &other) { - if (this != &other) - { - clear (); - set_deep_copy (other); - } - return *this; - } + return *this; + } #endif - private: - unsigned char *data_; - size_t size_; - bool owned_; - }; - + private: + unsigned char *data_; + size_t size_; + bool owned_; +}; } #endif - diff --git a/src/client.cpp b/src/client.cpp index 61f85e1df1..7d49be36fe 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -69,7 +69,6 @@ int zmq::client_t::xrecv (msg_t *msg_) // Drop any messages with more flag while (rc == 0 && msg_->flags () & msg_t::more) { - // drop all frames of the current multi-frame message rc = fq.recvpipe (msg_, NULL); diff --git a/src/client.hpp b/src/client.hpp index 6d9be5f083..31239e3106 100644 --- a/src/client.hpp +++ b/src/client.hpp @@ -37,45 +37,39 @@ namespace zmq { +class ctx_t; +class msg_t; +class pipe_t; +class io_thread_t; +class socket_base_t; - class ctx_t; - class msg_t; - class pipe_t; - class io_thread_t; - class socket_base_t; - - class client_t : - public socket_base_t - { - public: - - client_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); - ~client_t (); - - protected: - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsend (zmq::msg_t *msg_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - bool xhas_out (); - const blob_t &get_credential () const; - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - - // Messages are fair-queued from inbound pipes. And load-balanced to - // the outbound pipes. - fq_t fq; - lb_t lb; - - client_t (const client_t &); - const client_t &operator = (const client_t&); - }; - +class client_t : public socket_base_t +{ + public: + client_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); + ~client_t (); + + protected: + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsend (zmq::msg_t *msg_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + bool xhas_out (); + const blob_t &get_credential () const; + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + // Messages are fair-queued from inbound pipes. And load-balanced to + // the outbound pipes. + fq_t fq; + lb_t lb; + + client_t (const client_t &); + const client_t &operator= (const client_t &); +}; } #endif diff --git a/src/clock.cpp b/src/clock.cpp index b15bd743c5..f868bacadc 100644 --- a/src/clock.cpp +++ b/src/clock.cpp @@ -72,58 +72,61 @@ int alt_clock_gettime (int clock_id, timespec *ts) #endif #ifdef ZMQ_HAVE_WINDOWS -typedef ULONGLONG (*f_compatible_get_tick_count64)(); +typedef ULONGLONG (*f_compatible_get_tick_count64) (); static zmq::mutex_t compatible_get_tick_count64_mutex; -ULONGLONG compatible_get_tick_count64() +ULONGLONG compatible_get_tick_count64 () { #ifdef ZMQ_HAVE_WINDOWS_UWP - const ULONGLONG result = ::GetTickCount64(); - return result; + const ULONGLONG result = ::GetTickCount64 (); + return result; #else - zmq::scoped_lock_t locker(compatible_get_tick_count64_mutex); + zmq::scoped_lock_t locker (compatible_get_tick_count64_mutex); - static DWORD s_wrap = 0; - static DWORD s_last_tick = 0; - const DWORD current_tick = ::GetTickCount(); + static DWORD s_wrap = 0; + static DWORD s_last_tick = 0; + const DWORD current_tick = ::GetTickCount (); - if (current_tick < s_last_tick) - ++s_wrap; + if (current_tick < s_last_tick) + ++s_wrap; - s_last_tick = current_tick; - const ULONGLONG result = (static_cast(s_wrap) << 32) + static_cast(current_tick); + s_last_tick = current_tick; + const ULONGLONG result = (static_cast (s_wrap) << 32) + + static_cast (current_tick); - return result; + return result; #endif } -f_compatible_get_tick_count64 init_compatible_get_tick_count64() +f_compatible_get_tick_count64 init_compatible_get_tick_count64 () { - f_compatible_get_tick_count64 func = NULL; + f_compatible_get_tick_count64 func = NULL; #if !defined ZMQ_HAVE_WINDOWS_UWP - HMODULE module = ::LoadLibraryA("Kernel32.dll"); - if (module != NULL) - func = reinterpret_cast(::GetProcAddress(module, "GetTickCount64")); + HMODULE module = ::LoadLibraryA ("Kernel32.dll"); + if (module != NULL) + func = reinterpret_cast ( + ::GetProcAddress (module, "GetTickCount64")); #endif - if (func == NULL) - func = compatible_get_tick_count64; + if (func == NULL) + func = compatible_get_tick_count64; #if !defined ZMQ_HAVE_WINDOWS_UWP - ::FreeLibrary(module); + ::FreeLibrary (module); #endif - return func; + return func; } -static f_compatible_get_tick_count64 my_get_tick_count64 = init_compatible_get_tick_count64(); +static f_compatible_get_tick_count64 my_get_tick_count64 = + init_compatible_get_tick_count64 (); #endif zmq::clock_t::clock_t () : last_tsc (rdtsc ()), #ifdef ZMQ_HAVE_WINDOWS - last_time (static_cast((*my_get_tick_count64)())) + last_time (static_cast ((*my_get_tick_count64) ())) #else last_time (now_us () / 1000) #endif @@ -156,7 +159,8 @@ uint64_t zmq::clock_t::now_us () // Use POSIX clock_gettime function to get precise monotonic time. struct timespec tv; -#if defined ZMQ_HAVE_OSX && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12 +#if defined ZMQ_HAVE_OSX \ + && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12 int rc = alt_clock_gettime (SYSTEM_CLOCK, &tv); #else int rc = clock_gettime (CLOCK_MONOTONIC, &tv); @@ -164,7 +168,7 @@ uint64_t zmq::clock_t::now_us () // Fix case where system has clock_gettime but CLOCK_MONOTONIC is not supported. // This should be a configuration check, but I looked into it and writing an // AC_FUNC_CLOCK_MONOTONIC seems beyond my powers. - if( rc != 0) { + if (rc != 0) { // Use POSIX gettimeofday function to get precise time. struct timeval tv; int rc = gettimeofday (&tv, NULL); @@ -193,14 +197,13 @@ uint64_t zmq::clock_t::now_ms () uint64_t tsc = rdtsc (); // If TSC is not supported, get precise time and chop off the microseconds. - if (!tsc) - { + if (!tsc) { #ifdef ZMQ_HAVE_WINDOWS // Under Windows, now_us is not so reliable since QueryPerformanceCounter // does not guarantee that it will use a hardware that offers a monotonic timer. // So, lets use GetTickCount when GetTickCount64 is not available with an workaround // to its 32 bit limitation. - return static_cast((*my_get_tick_count64)()); + return static_cast ((*my_get_tick_count64) ()); #else return now_us () / 1000; #endif @@ -214,7 +217,7 @@ uint64_t zmq::clock_t::now_ms () last_tsc = tsc; #ifdef ZMQ_HAVE_WINDOWS - last_time = static_cast((*my_get_tick_count64)()); + last_time = static_cast ((*my_get_tick_count64) ()); #else last_time = now_us () / 1000; #endif @@ -227,27 +230,29 @@ uint64_t zmq::clock_t::rdtsc () return __rdtsc (); #elif (defined __GNUC__ && (defined __i386__ || defined __x86_64__)) uint32_t low, high; - __asm__ volatile ("rdtsc" : "=a" (low), "=d" (high)); + __asm__ volatile("rdtsc" : "=a"(low), "=d"(high)); return (uint64_t) high << 32 | low; -#elif (defined __SUNPRO_CC && (__SUNPRO_CC >= 0x5100) && (defined __i386 || \ - defined __amd64 || defined __x86_64)) - union { +#elif (defined __SUNPRO_CC && (__SUNPRO_CC >= 0x5100) \ + && (defined __i386 || defined __amd64 || defined __x86_64)) + union + { uint64_t u64val; - uint32_t u32val [2]; + uint32_t u32val[2]; } tsc; - asm("rdtsc" : "=a" (tsc.u32val [0]), "=d" (tsc.u32val [1])); + asm("rdtsc" : "=a"(tsc.u32val[0]), "=d"(tsc.u32val[1])); return tsc.u64val; #elif defined(__s390__) uint64_t tsc; - asm("\tstck\t%0\n" : "=Q" (tsc) : : "cc"); - return(tsc); + asm("\tstck\t%0\n" : "=Q"(tsc) : : "cc"); + return (tsc); #else struct timespec ts; - #if defined ZMQ_HAVE_OSX && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12 - alt_clock_gettime (SYSTEM_CLOCK, &ts); - #else - clock_gettime (CLOCK_MONOTONIC, &ts); - #endif - return (uint64_t)(ts.tv_sec) * 1000000000 + ts.tv_nsec; +#if defined ZMQ_HAVE_OSX \ + && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12 + alt_clock_gettime (SYSTEM_CLOCK, &ts); +#else + clock_gettime (CLOCK_MONOTONIC, &ts); +#endif + return (uint64_t) (ts.tv_sec) * 1000000000 + ts.tv_nsec; #endif } diff --git a/src/clock.hpp b/src/clock.hpp index ee80a9da1d..3cef6538db 100644 --- a/src/clock.hpp +++ b/src/clock.hpp @@ -48,36 +48,32 @@ int alt_clock_gettime (int clock_id, timespec *ts); namespace zmq { +class clock_t +{ + public: + clock_t (); + ~clock_t (); - class clock_t - { - public: - - clock_t (); - ~clock_t (); - - // CPU's timestamp counter. Returns 0 if it's not available. - static uint64_t rdtsc (); - - // High precision timestamp. - static uint64_t now_us (); - - // Low precision timestamp. In tight loops generating it can be - // 10 to 100 times faster than the high precision timestamp. - uint64_t now_ms (); + // CPU's timestamp counter. Returns 0 if it's not available. + static uint64_t rdtsc (); - private: + // High precision timestamp. + static uint64_t now_us (); - // TSC timestamp of when last time measurement was made. - uint64_t last_tsc; + // Low precision timestamp. In tight loops generating it can be + // 10 to 100 times faster than the high precision timestamp. + uint64_t now_ms (); - // Physical time corresponding to the TSC above (in milliseconds). - uint64_t last_time; + private: + // TSC timestamp of when last time measurement was made. + uint64_t last_tsc; - clock_t (const clock_t&); - const clock_t &operator = (const clock_t&); - }; + // Physical time corresponding to the TSC above (in milliseconds). + uint64_t last_time; + clock_t (const clock_t &); + const clock_t &operator= (const clock_t &); +}; } #endif diff --git a/src/command.hpp b/src/command.hpp index ddb46d4675..ed095e1cd9 100644 --- a/src/command.hpp +++ b/src/command.hpp @@ -35,153 +35,169 @@ namespace zmq { +class object_t; +class own_t; +struct i_engine; +class pipe_t; +class socket_base_t; - class object_t; - class own_t; - struct i_engine; - class pipe_t; - class socket_base_t; - - // This structure defines the commands that can be sent between threads. +// This structure defines the commands that can be sent between threads. #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4324) // C4324: alignment padding warnings - __declspec(align(64)) +#pragma warning(disable : 4324) // C4324: alignment padding warnings +__declspec(align (64)) #endif - struct command_t + struct command_t +{ + // Object to process the command. + zmq::object_t *destination; + + enum type_t { - // Object to process the command. - zmq::object_t *destination; - - enum type_t - { - stop, - plug, - own, - attach, - bind, - activate_read, - activate_write, - hiccup, - pipe_term, - pipe_term_ack, - pipe_hwm, - term_req, - term, - term_ack, - term_endpoint, - reap, - reaped, - inproc_connected, - done - } type; - - union args_t - { - - // Sent to I/O thread to let it know that it should - // terminate itself. - struct { - } stop; - - // Sent to I/O object to make it register with its I/O thread. - struct { - } plug; - - // Sent to socket to let it know about the newly created object. - struct { - zmq::own_t *object; - } own; - - // Attach the engine to the session. If engine is NULL, it informs - // session that the connection have failed. - struct { - struct i_engine *engine; - } attach; - - // Sent from session to socket to establish pipe(s) between them. - // Caller have used inc_seqnum beforehand sending the command. - struct { - zmq::pipe_t *pipe; - } bind; - - // Sent by pipe writer to inform dormant pipe reader that there - // are messages in the pipe. - struct { - } activate_read; - - // Sent by pipe reader to inform pipe writer about how many - // messages it has read so far. - struct { - uint64_t msgs_read; - } activate_write; - - // Sent by pipe reader to writer after creating a new inpipe. - // The parameter is actually of type pipe_t::upipe_t, however, - // its definition is private so we'll have to do with void*. - struct { - void *pipe; - } hiccup; - - // Sent by pipe reader to pipe writer to ask it to terminate - // its end of the pipe. - struct { - } pipe_term; - - // Pipe writer acknowledges pipe_term command. - struct { - } pipe_term_ack; - - // Sent by one of pipe to another part for modify hwm - struct { - int inhwm; - int outhwm; - } pipe_hwm; - - // Sent by I/O object ot the socket to request the shutdown of - // the I/O object. - struct { - zmq::own_t *object; - } term_req; - - // Sent by socket to I/O object to start its shutdown. - struct { - int linger; - } term; - - // Sent by I/O object to the socket to acknowledge it has - // shut down. - struct { - } term_ack; - - // Sent by session_base (I/O thread) to socket (application thread) - // to ask to disconnect the endpoint. - struct { - std::string *endpoint; - } term_endpoint; - - // Transfers the ownership of the closed socket - // to the reaper thread. - struct { - zmq::socket_base_t *socket; - } reap; - - // Closed socket notifies the reaper that it's already deallocated. - struct { - } reaped; - - // Sent by reaper thread to the term thread when all the sockets - // are successfully deallocated. - struct { - } done; - - } args; + stop, + plug, + own, + attach, + bind, + activate_read, + activate_write, + hiccup, + pipe_term, + pipe_term_ack, + pipe_hwm, + term_req, + term, + term_ack, + term_endpoint, + reap, + reaped, + inproc_connected, + done + } type; + + union args_t + { + // Sent to I/O thread to let it know that it should + // terminate itself. + struct + { + } stop; + + // Sent to I/O object to make it register with its I/O thread. + struct + { + } plug; + + // Sent to socket to let it know about the newly created object. + struct + { + zmq::own_t *object; + } own; + + // Attach the engine to the session. If engine is NULL, it informs + // session that the connection have failed. + struct + { + struct i_engine *engine; + } attach; + + // Sent from session to socket to establish pipe(s) between them. + // Caller have used inc_seqnum beforehand sending the command. + struct + { + zmq::pipe_t *pipe; + } bind; + + // Sent by pipe writer to inform dormant pipe reader that there + // are messages in the pipe. + struct + { + } activate_read; + + // Sent by pipe reader to inform pipe writer about how many + // messages it has read so far. + struct + { + uint64_t msgs_read; + } activate_write; + + // Sent by pipe reader to writer after creating a new inpipe. + // The parameter is actually of type pipe_t::upipe_t, however, + // its definition is private so we'll have to do with void*. + struct + { + void *pipe; + } hiccup; + + // Sent by pipe reader to pipe writer to ask it to terminate + // its end of the pipe. + struct + { + } pipe_term; + + // Pipe writer acknowledges pipe_term command. + struct + { + } pipe_term_ack; + + // Sent by one of pipe to another part for modify hwm + struct + { + int inhwm; + int outhwm; + } pipe_hwm; + + // Sent by I/O object ot the socket to request the shutdown of + // the I/O object. + struct + { + zmq::own_t *object; + } term_req; + + // Sent by socket to I/O object to start its shutdown. + struct + { + int linger; + } term; + + // Sent by I/O object to the socket to acknowledge it has + // shut down. + struct + { + } term_ack; + + // Sent by session_base (I/O thread) to socket (application thread) + // to ask to disconnect the endpoint. + struct + { + std::string *endpoint; + } term_endpoint; + + // Transfers the ownership of the closed socket + // to the reaper thread. + struct + { + zmq::socket_base_t *socket; + } reap; + + // Closed socket notifies the reaper that it's already deallocated. + struct + { + } reaped; + + // Sent by reaper thread to the term thread when all the sockets + // are successfully deallocated. + struct + { + } done; + + } args; #ifdef _MSC_VER - }; +}; #pragma warning(pop) #else - } __attribute__((aligned(64))); +} __attribute__ ((aligned (64))); #endif } diff --git a/src/condition_variable.hpp b/src/condition_variable.hpp index 6452b7814f..73ad6a201e 100644 --- a/src/condition_variable.hpp +++ b/src/condition_variable.hpp @@ -58,38 +58,26 @@ namespace zmq { +class condition_variable_t +{ + public: + inline condition_variable_t () { zmq_assert (false); } - class condition_variable_t - { - public: - inline condition_variable_t () - { - zmq_assert(false); - } - - inline ~condition_variable_t () - { - - } - - inline int wait (mutex_t* mutex_, int timeout_ ) - { - zmq_assert(false); - return -1; - } + inline ~condition_variable_t () {} - inline void broadcast () - { - zmq_assert(false); - } - - private: + inline int wait (mutex_t *mutex_, int timeout_) + { + zmq_assert (false); + return -1; + } - // Disable copy construction and assignment. - condition_variable_t (const condition_variable_t&); - void operator = (const condition_variable_t&); - }; + inline void broadcast () { zmq_assert (false); } + private: + // Disable copy construction and assignment. + condition_variable_t (const condition_variable_t &); + void operator= (const condition_variable_t &); +}; } #else @@ -103,94 +91,79 @@ namespace zmq { #if !defined(ZMQ_HAVE_WINDOWS_TARGET_XP) && _WIN32_WINNT >= 0x0600 - class condition_variable_t +class condition_variable_t +{ + public: + inline condition_variable_t () { InitializeConditionVariable (&cv); } + + inline ~condition_variable_t () {} + + inline int wait (mutex_t *mutex_, int timeout_) { - public: - inline condition_variable_t () - { - InitializeConditionVariable (&cv); - } + int rc = SleepConditionVariableCS (&cv, mutex_->get_cs (), timeout_); - inline ~condition_variable_t () - { + if (rc != 0) + return 0; - } + rc = GetLastError (); - inline int wait (mutex_t* mutex_, int timeout_ ) - { - int rc = SleepConditionVariableCS(&cv, mutex_->get_cs (), timeout_); + if (rc != ERROR_TIMEOUT) + win_assert (rc); - if (rc != 0) - return 0; + errno = EAGAIN; + return -1; + } - rc = GetLastError(); + inline void broadcast () { WakeAllConditionVariable (&cv); } - if (rc != ERROR_TIMEOUT) - win_assert(rc); + private: + CONDITION_VARIABLE cv; - errno = EAGAIN; - return -1; - } + // Disable copy construction and assignment. + condition_variable_t (const condition_variable_t &); + void operator= (const condition_variable_t &); +}; +#else +class condition_variable_t +{ + public: + inline condition_variable_t () {} - inline void broadcast () - { - WakeAllConditionVariable(&cv); + inline ~condition_variable_t () {} + + inline int wait (mutex_t *mutex_, int timeout_) + { + std::unique_lock lck (mtx); // lock mtx + mutex_->unlock (); // unlock mutex_ + int res = 0; + if (timeout_ == -1) { + cv.wait ( + lck); // unlock mtx and wait cv.notify_all(), lock mtx after cv.notify_all() + } else if (cv.wait_for (lck, std::chrono::milliseconds (timeout_)) + == std::cv_status::timeout) { + // time expired + errno = EAGAIN; + res = -1; } + lck.unlock (); // unlock mtx + mutex_->lock (); // lock mutex_ + return res; + } - private: + inline void broadcast () + { + std::unique_lock lck (mtx); // lock mtx + cv.notify_all (); + } - CONDITION_VARIABLE cv; + private: + std::condition_variable cv; + std::mutex mtx; - // Disable copy construction and assignment. - condition_variable_t (const condition_variable_t&); - void operator = (const condition_variable_t&); - }; -#else - class condition_variable_t - { - public: - inline condition_variable_t() - { - - } - - inline ~condition_variable_t() - { - - } - - inline int wait(mutex_t* mutex_, int timeout_) - { - std::unique_lock lck(mtx); // lock mtx - mutex_->unlock(); // unlock mutex_ - int res = 0; - if(timeout_ == -1) { - cv.wait(lck); // unlock mtx and wait cv.notify_all(), lock mtx after cv.notify_all() - } else if (cv.wait_for(lck, std::chrono::milliseconds(timeout_)) == std::cv_status::timeout) { - // time expired - errno = EAGAIN; - res = -1; - } - lck.unlock(); // unlock mtx - mutex_->lock(); // lock mutex_ - return res; - } - - inline void broadcast() - { - std::unique_lock lck(mtx); // lock mtx - cv.notify_all(); - } - - private: - - std::condition_variable cv; - std::mutex mtx; - - // Disable copy construction and assignment. - condition_variable_t(const condition_variable_t&); - void operator = (const condition_variable_t&); - }; + // Disable copy construction and assignment. + condition_variable_t (const condition_variable_t &); + void operator= (const condition_variable_t &); +}; #endif } @@ -203,74 +176,72 @@ namespace zmq namespace zmq { - - class condition_variable_t +class condition_variable_t +{ + public: + inline condition_variable_t () { - public: - inline condition_variable_t () - { - int rc = pthread_cond_init (&cond, NULL); - posix_assert (rc); - } + int rc = pthread_cond_init (&cond, NULL); + posix_assert (rc); + } - inline ~condition_variable_t () - { - int rc = pthread_cond_destroy (&cond); - posix_assert (rc); - } + inline ~condition_variable_t () + { + int rc = pthread_cond_destroy (&cond); + posix_assert (rc); + } - inline int wait (mutex_t* mutex_, int timeout_) - { - int rc; + inline int wait (mutex_t *mutex_, int timeout_) + { + int rc; - if (timeout_ != -1) { - struct timespec timeout; + if (timeout_ != -1) { + struct timespec timeout; -#if defined ZMQ_HAVE_OSX && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12 - alt_clock_gettime(SYSTEM_CLOCK, &timeout); +#if defined ZMQ_HAVE_OSX \ + && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12 + alt_clock_gettime (SYSTEM_CLOCK, &timeout); #else - clock_gettime(CLOCK_MONOTONIC, &timeout); + clock_gettime (CLOCK_MONOTONIC, &timeout); #endif - timeout.tv_sec += timeout_ / 1000; - timeout.tv_nsec += (timeout_ % 1000) * 1000000; - - if (timeout.tv_nsec > 1000000000) { - timeout.tv_sec++; - timeout.tv_nsec -= 1000000000; - } + timeout.tv_sec += timeout_ / 1000; + timeout.tv_nsec += (timeout_ % 1000) * 1000000; - rc = pthread_cond_timedwait (&cond, mutex_->get_mutex (), &timeout); + if (timeout.tv_nsec > 1000000000) { + timeout.tv_sec++; + timeout.tv_nsec -= 1000000000; } - else - rc = pthread_cond_wait(&cond, mutex_->get_mutex()); - if (rc == 0) - return 0; + rc = pthread_cond_timedwait (&cond, mutex_->get_mutex (), &timeout); + } else + rc = pthread_cond_wait (&cond, mutex_->get_mutex ()); - if (rc == ETIMEDOUT){ - errno= EAGAIN; - return -1; - } + if (rc == 0) + return 0; - posix_assert (rc); + if (rc == ETIMEDOUT) { + errno = EAGAIN; return -1; } - inline void broadcast () - { - int rc = pthread_cond_broadcast (&cond); - posix_assert (rc); - } + posix_assert (rc); + return -1; + } - private: + inline void broadcast () + { + int rc = pthread_cond_broadcast (&cond); + posix_assert (rc); + } - pthread_cond_t cond; + private: + pthread_cond_t cond; - // Disable copy construction and assignment. - condition_variable_t (const condition_variable_t&); - const condition_variable_t &operator = (const condition_variable_t&); - }; + // Disable copy construction and assignment. + condition_variable_t (const condition_variable_t &); + const condition_variable_t &operator= (const condition_variable_t &); +}; } #endif diff --git a/src/config.hpp b/src/config.hpp index 0a7433a812..af228a0f9a 100644 --- a/src/config.hpp +++ b/src/config.hpp @@ -32,67 +32,65 @@ namespace zmq { +// Compile-time settings. - // Compile-time settings. - - enum - { - // Number of new messages in message pipe needed to trigger new memory - // allocation. Setting this parameter to 256 decreases the impact of - // memory allocation by approximately 99.6% - message_pipe_granularity = 256, - - // Commands in pipe per allocation event. - command_pipe_granularity = 16, - - // Determines how often does socket poll for new commands when it - // still has unprocessed messages to handle. Thus, if it is set to 100, - // socket will process 100 inbound messages before doing the poll. - // If there are no unprocessed messages available, poll is done - // immediately. Decreasing the value trades overall latency for more - // real-time behaviour (less latency peaks). - inbound_poll_rate = 100, - - // Maximal batching size for engines with receiving functionality. - // So, if there are 10 messages that fit into the batch size, all of - // them may be read by a single 'recv' system call, thus avoiding - // unnecessary network stack traversals. - in_batch_size = 8192, - - // Maximal batching size for engines with sending functionality. - // So, if there are 10 messages that fit into the batch size, all of - // them may be written by a single 'send' system call, thus avoiding - // unnecessary network stack traversals. - out_batch_size = 8192, - - // Maximal delta between high and low watermark. - max_wm_delta = 1024, - - // Maximum number of events the I/O thread can process in one go. - max_io_events = 256, - - // Maximal delay to process command in API thread (in CPU ticks). - // 3,000,000 ticks equals to 1 - 2 milliseconds on current CPUs. - // Note that delay is only applied when there is continuous stream of - // messages to process. If not so, commands are processed immediately. - max_command_delay = 3000000, - - // Low-precision clock precision in CPU ticks. 1ms. Value of 1000000 - // should be OK for CPU frequencies above 1GHz. If should work - // reasonably well for CPU frequencies above 500MHz. For lower CPU - // frequencies you may consider lowering this value to get best - // possible latencies. - clock_precision = 1000000, - - // On some OSes the signaler has to be emulated using a TCP - // connection. In such cases following port is used. - // If 0, it lets the OS choose a free port without requiring use of a - // global mutex. The original implementation of a Windows signaler - // socket used port 5905 instead of letting the OS choose a free port. - // https://github.com/zeromq/libzmq/issues/1542 - signaler_port = 0 - }; - +enum +{ + // Number of new messages in message pipe needed to trigger new memory + // allocation. Setting this parameter to 256 decreases the impact of + // memory allocation by approximately 99.6% + message_pipe_granularity = 256, + + // Commands in pipe per allocation event. + command_pipe_granularity = 16, + + // Determines how often does socket poll for new commands when it + // still has unprocessed messages to handle. Thus, if it is set to 100, + // socket will process 100 inbound messages before doing the poll. + // If there are no unprocessed messages available, poll is done + // immediately. Decreasing the value trades overall latency for more + // real-time behaviour (less latency peaks). + inbound_poll_rate = 100, + + // Maximal batching size for engines with receiving functionality. + // So, if there are 10 messages that fit into the batch size, all of + // them may be read by a single 'recv' system call, thus avoiding + // unnecessary network stack traversals. + in_batch_size = 8192, + + // Maximal batching size for engines with sending functionality. + // So, if there are 10 messages that fit into the batch size, all of + // them may be written by a single 'send' system call, thus avoiding + // unnecessary network stack traversals. + out_batch_size = 8192, + + // Maximal delta between high and low watermark. + max_wm_delta = 1024, + + // Maximum number of events the I/O thread can process in one go. + max_io_events = 256, + + // Maximal delay to process command in API thread (in CPU ticks). + // 3,000,000 ticks equals to 1 - 2 milliseconds on current CPUs. + // Note that delay is only applied when there is continuous stream of + // messages to process. If not so, commands are processed immediately. + max_command_delay = 3000000, + + // Low-precision clock precision in CPU ticks. 1ms. Value of 1000000 + // should be OK for CPU frequencies above 1GHz. If should work + // reasonably well for CPU frequencies above 500MHz. For lower CPU + // frequencies you may consider lowering this value to get best + // possible latencies. + clock_precision = 1000000, + + // On some OSes the signaler has to be emulated using a TCP + // connection. In such cases following port is used. + // If 0, it lets the OS choose a free port without requiring use of a + // global mutex. The original implementation of a Windows signaler + // socket used port 5905 instead of letting the OS choose a free port. + // https://github.com/zeromq/libzmq/issues/1542 + signaler_port = 0 +}; } #endif diff --git a/src/ctx.cpp b/src/ctx.cpp index 11e72f2a2f..5e6bc64035 100644 --- a/src/ctx.cpp +++ b/src/ctx.cpp @@ -53,11 +53,12 @@ #endif #define ZMQ_CTX_TAG_VALUE_GOOD 0xabadcafe -#define ZMQ_CTX_TAG_VALUE_BAD 0xdeadbeef +#define ZMQ_CTX_TAG_VALUE_BAD 0xdeadbeef int clipped_maxsocket (int max_requested) { - if (max_requested >= zmq::poller_t::max_fds () && zmq::poller_t::max_fds () != -1) + if (max_requested >= zmq::poller_t::max_fds () + && zmq::poller_t::max_fds () != -1) // -1 because we need room for the reaper mailbox. max_requested = zmq::poller_t::max_fds () - 1; @@ -80,7 +81,7 @@ zmq::ctx_t::ctx_t () : thread_sched_policy (ZMQ_THREAD_SCHED_POLICY_DFLT) { #ifdef HAVE_FORK - pid = getpid(); + pid = getpid (); #endif #ifdef ZMQ_HAVE_VMCI vmci_fd = -1; @@ -104,16 +105,16 @@ zmq::ctx_t::~ctx_t () // Ask I/O threads to terminate. If stop signal wasn't sent to I/O // thread subsequent invocation of destructor would hang-up. for (io_threads_t::size_type i = 0; i != io_threads.size (); i++) { - io_threads [i]->stop (); + io_threads[i]->stop (); } // Wait till I/O threads actually terminate. for (io_threads_t::size_type i = 0; i != io_threads.size (); i++) { - LIBZMQ_DELETE(io_threads [i]); + LIBZMQ_DELETE (io_threads[i]); } // Deallocate the reaper thread object. - LIBZMQ_DELETE(reaper); + LIBZMQ_DELETE (reaper); // Deallocate the array of mailboxes. No special work is // needed as mailboxes themselves were deallocated with their @@ -134,14 +135,15 @@ bool zmq::ctx_t::valid () const int zmq::ctx_t::terminate () { - slot_sync.lock(); + slot_sync.lock (); bool saveTerminating = terminating; terminating = false; // Connect up any pending inproc connections, otherwise we will hang pending_connections_t copy = pending_connections; - for (pending_connections_t::iterator p = copy.begin (); p != copy.end (); ++p) { + for (pending_connections_t::iterator p = copy.begin (); p != copy.end (); + ++p) { zmq::socket_base_t *s = create_socket (ZMQ_PAIR); // create_socket might fail eg: out of memory/sockets limit reached zmq_assert (s); @@ -156,7 +158,7 @@ int zmq::ctx_t::terminate () // we are a forked child process. Close all file descriptors // inherited from the parent. for (sockets_t::size_type i = 0; i != sockets.size (); i++) - sockets [i]->get_mailbox ()->forked (); + sockets[i]->get_mailbox ()->forked (); term_mailbox.forked (); } @@ -173,11 +175,11 @@ int zmq::ctx_t::terminate () // can be interrupted. If there are no sockets we can ask reaper // thread to stop. for (sockets_t::size_type i = 0; i != sockets.size (); i++) - sockets [i]->stop (); + sockets[i]->stop (); if (sockets.empty ()) reaper->stop (); } - slot_sync.unlock(); + slot_sync.unlock (); // Wait till reaper thread closes all the sockets. command_t cmd; @@ -209,7 +211,7 @@ int zmq::ctx_t::terminate () int zmq::ctx_t::shutdown () { - scoped_lock_t locker(slot_sync); + scoped_lock_t locker (slot_sync); if (!starting && !terminating) { terminating = true; @@ -218,7 +220,7 @@ int zmq::ctx_t::shutdown () // can be interrupted. If there are no sockets we can ask reaper // thread to stop. for (sockets_t::size_type i = 0; i != sockets.size (); i++) - sockets [i]->stop (); + sockets[i]->stop (); if (sockets.empty ()) reaper->stop (); } @@ -229,65 +231,46 @@ int zmq::ctx_t::shutdown () int zmq::ctx_t::set (int option_, int optval_) { int rc = 0; - if (option_ == ZMQ_MAX_SOCKETS - && optval_ >= 1 && optval_ == clipped_maxsocket (optval_)) { - scoped_lock_t locker(opt_sync); + if (option_ == ZMQ_MAX_SOCKETS && optval_ >= 1 + && optval_ == clipped_maxsocket (optval_)) { + scoped_lock_t locker (opt_sync); max_sockets = optval_; - } - else - if (option_ == ZMQ_IO_THREADS && optval_ >= 0) { - scoped_lock_t locker(opt_sync); + } else if (option_ == ZMQ_IO_THREADS && optval_ >= 0) { + scoped_lock_t locker (opt_sync); io_thread_count = optval_; - } - else - if (option_ == ZMQ_IPV6 && optval_ >= 0) { - scoped_lock_t locker(opt_sync); + } else if (option_ == ZMQ_IPV6 && optval_ >= 0) { + scoped_lock_t locker (opt_sync); ipv6 = (optval_ != 0); - } - else - if (option_ == ZMQ_THREAD_PRIORITY && optval_ >= 0) { - scoped_lock_t locker(opt_sync); + } else if (option_ == ZMQ_THREAD_PRIORITY && optval_ >= 0) { + scoped_lock_t locker (opt_sync); thread_priority = optval_; - } - else - if (option_ == ZMQ_THREAD_SCHED_POLICY && optval_ >= 0) { - scoped_lock_t locker(opt_sync); + } else if (option_ == ZMQ_THREAD_SCHED_POLICY && optval_ >= 0) { + scoped_lock_t locker (opt_sync); thread_sched_policy = optval_; - } - else - if (option_ == ZMQ_THREAD_AFFINITY_CPU_ADD && optval_ >= 0) { - scoped_lock_t locker(opt_sync); - thread_affinity_cpus.insert( optval_ ); - } - else - if (option_ == ZMQ_THREAD_AFFINITY_CPU_REMOVE && optval_ >= 0) { - scoped_lock_t locker(opt_sync); - std::set::iterator it = thread_affinity_cpus.find( optval_ ); - if (it != thread_affinity_cpus.end()) { - thread_affinity_cpus.erase( it ); + } else if (option_ == ZMQ_THREAD_AFFINITY_CPU_ADD && optval_ >= 0) { + scoped_lock_t locker (opt_sync); + thread_affinity_cpus.insert (optval_); + } else if (option_ == ZMQ_THREAD_AFFINITY_CPU_REMOVE && optval_ >= 0) { + scoped_lock_t locker (opt_sync); + std::set::iterator it = thread_affinity_cpus.find (optval_); + if (it != thread_affinity_cpus.end ()) { + thread_affinity_cpus.erase (it); } else { errno = EINVAL; rc = -1; } - } - else - if (option_ == ZMQ_THREAD_NAME_PREFIX && optval_ >= 0) { + } else if (option_ == ZMQ_THREAD_NAME_PREFIX && optval_ >= 0) { std::ostringstream s; s << optval_; - scoped_lock_t locker(opt_sync); - thread_name_prefix = s.str(); - } - else - if (option_ == ZMQ_BLOCKY && optval_ >= 0) { - scoped_lock_t locker(opt_sync); + scoped_lock_t locker (opt_sync); + thread_name_prefix = s.str (); + } else if (option_ == ZMQ_BLOCKY && optval_ >= 0) { + scoped_lock_t locker (opt_sync); blocky = (optval_ != 0); - } - else - if (option_ == ZMQ_MAX_MSGSZ && optval_ >= 0) { - scoped_lock_t locker(opt_sync); - max_msgsz = optval_ < INT_MAX? optval_: INT_MAX; - } - else { + } else if (option_ == ZMQ_MAX_MSGSZ && optval_ >= 0) { + scoped_lock_t locker (opt_sync); + max_msgsz = optval_ < INT_MAX ? optval_ : INT_MAX; + } else { errno = EINVAL; rc = -1; } @@ -299,23 +282,17 @@ int zmq::ctx_t::get (int option_) int rc = 0; if (option_ == ZMQ_MAX_SOCKETS) rc = max_sockets; - else - if (option_ == ZMQ_SOCKET_LIMIT) + else if (option_ == ZMQ_SOCKET_LIMIT) rc = clipped_maxsocket (65535); - else - if (option_ == ZMQ_IO_THREADS) + else if (option_ == ZMQ_IO_THREADS) rc = io_thread_count; - else - if (option_ == ZMQ_IPV6) + else if (option_ == ZMQ_IPV6) rc = ipv6; - else - if (option_ == ZMQ_BLOCKY) + else if (option_ == ZMQ_BLOCKY) rc = blocky; - else - if (option_ == ZMQ_MAX_MSGSZ) + else if (option_ == ZMQ_MAX_MSGSZ) rc = max_msgsz; - else - if (option_ == ZMQ_MSG_T_SIZE) + else if (option_ == ZMQ_MSG_T_SIZE) rc = sizeof (zmq_msg_t); else { errno = EINVAL; @@ -369,7 +346,7 @@ bool zmq::ctx_t::start () goto fail_cleanup_reaper; } io_threads.push_back (io_thread); - slots [i] = io_thread->get_mailbox (); + slots[i] = io_thread->get_mailbox (); io_thread->start (); } @@ -429,19 +406,19 @@ zmq::socket_base_t *zmq::ctx_t::create_socket (int type_) return NULL; } sockets.push_back (s); - slots [slot] = s->get_mailbox (); + slots[slot] = s->get_mailbox (); return s; } void zmq::ctx_t::destroy_socket (class socket_base_t *socket_) { - scoped_lock_t locker(slot_sync); + scoped_lock_t locker (slot_sync); // Free the associated thread slot. uint32_t tid = socket_->get_tid (); empty_slots.push_back (tid); - slots [tid] = NULL; + slots[tid] = NULL; // Remove the socket from the list of sockets. sockets.erase (socket_); @@ -457,25 +434,28 @@ zmq::object_t *zmq::ctx_t::get_reaper () return reaper; } -void zmq::ctx_t::start_thread (thread_t &thread_, thread_fn *tfn_, void *arg_) const +void zmq::ctx_t::start_thread (thread_t &thread_, + thread_fn *tfn_, + void *arg_) const { static unsigned int nthreads_started = 0; - thread_.setSchedulingParameters(thread_priority, thread_sched_policy, thread_affinity_cpus); - thread_.start(tfn_, arg_); + thread_.setSchedulingParameters (thread_priority, thread_sched_policy, + thread_affinity_cpus); + thread_.start (tfn_, arg_); #ifndef ZMQ_HAVE_ANDROID std::ostringstream s; - if (!thread_name_prefix.empty()) + if (!thread_name_prefix.empty ()) s << thread_name_prefix << "/"; s << "ZMQbg/" << nthreads_started; - thread_.setThreadName (s.str().c_str()); + thread_.setThreadName (s.str ().c_str ()); #endif nthreads_started++; } void zmq::ctx_t::send_command (uint32_t tid_, const command_t &command_) { - slots [tid_]->send (command_); + slots[tid_]->send (command_); } zmq::io_thread_t *zmq::ctx_t::choose_io_thread (uint64_t affinity_) @@ -488,10 +468,10 @@ zmq::io_thread_t *zmq::ctx_t::choose_io_thread (uint64_t affinity_) io_thread_t *selected_io_thread = NULL; for (io_threads_t::size_type i = 0; i != io_threads.size (); i++) { if (!affinity_ || (affinity_ & (uint64_t (1) << i))) { - int load = io_threads [i]->get_load (); + int load = io_threads[i]->get_load (); if (selected_io_thread == NULL || load < min_load) { min_load = load; - selected_io_thread = io_threads [i]; + selected_io_thread = io_threads[i]; } } } @@ -499,12 +479,12 @@ zmq::io_thread_t *zmq::ctx_t::choose_io_thread (uint64_t affinity_) } int zmq::ctx_t::register_endpoint (const char *addr_, - const endpoint_t &endpoint_) + const endpoint_t &endpoint_) { - scoped_lock_t locker(endpoints_sync); + scoped_lock_t locker (endpoints_sync); - const bool inserted = endpoints.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, - endpoint_).second; + const bool inserted = + endpoints.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, endpoint_).second; if (!inserted) { errno = EADDRINUSE; return -1; @@ -512,10 +492,10 @@ int zmq::ctx_t::register_endpoint (const char *addr_, return 0; } -int zmq::ctx_t::unregister_endpoint ( - const std::string &addr_, socket_base_t *socket_) +int zmq::ctx_t::unregister_endpoint (const std::string &addr_, + socket_base_t *socket_) { - scoped_lock_t locker(endpoints_sync); + scoped_lock_t locker (endpoints_sync); const endpoints_t::iterator it = endpoints.find (addr_); if (it == endpoints.end () || it->second.socket != socket_) { @@ -531,7 +511,7 @@ int zmq::ctx_t::unregister_endpoint ( void zmq::ctx_t::unregister_endpoints (socket_base_t *socket_) { - scoped_lock_t locker(endpoints_sync); + scoped_lock_t locker (endpoints_sync); endpoints_t::iterator it = endpoints.begin (); while (it != endpoints.end ()) { @@ -547,58 +527,69 @@ void zmq::ctx_t::unregister_endpoints (socket_base_t *socket_) zmq::endpoint_t zmq::ctx_t::find_endpoint (const char *addr_) { - scoped_lock_t locker(endpoints_sync); + scoped_lock_t locker (endpoints_sync); endpoints_t::iterator it = endpoints.find (addr_); if (it == endpoints.end ()) { errno = ECONNREFUSED; - endpoint_t empty = {NULL, options_t()}; + endpoint_t empty = {NULL, options_t ()}; return empty; - } - endpoint_t endpoint = it->second; + } + endpoint_t endpoint = it->second; - // Increment the command sequence number of the peer so that it won't - // get deallocated until "bind" command is issued by the caller. - // The subsequent 'bind' has to be called with inc_seqnum parameter - // set to false, so that the seqnum isn't incremented twice. - endpoint.socket->inc_seqnum (); + // Increment the command sequence number of the peer so that it won't + // get deallocated until "bind" command is issued by the caller. + // The subsequent 'bind' has to be called with inc_seqnum parameter + // set to false, so that the seqnum isn't incremented twice. + endpoint.socket->inc_seqnum (); - return endpoint; + return endpoint; } void zmq::ctx_t::pend_connection (const std::string &addr_, - const endpoint_t &endpoint_, pipe_t **pipes_) + const endpoint_t &endpoint_, + pipe_t **pipes_) { - scoped_lock_t locker(endpoints_sync); + scoped_lock_t locker (endpoints_sync); - const pending_connection_t pending_connection = {endpoint_, pipes_ [0], pipes_ [1]}; + const pending_connection_t pending_connection = {endpoint_, pipes_[0], + pipes_[1]}; endpoints_t::iterator it = endpoints.find (addr_); if (it == endpoints.end ()) { // Still no bind. endpoint_.socket->inc_seqnum (); - pending_connections.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, pending_connection); + pending_connections.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, + pending_connection); } else { // Bind has happened in the mean time, connect directly - connect_inproc_sockets(it->second.socket, it->second.options, pending_connection, connect_side); + connect_inproc_sockets (it->second.socket, it->second.options, + pending_connection, connect_side); } } -void zmq::ctx_t::connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_) +void zmq::ctx_t::connect_pending (const char *addr_, + zmq::socket_base_t *bind_socket_) { - scoped_lock_t locker(endpoints_sync); + scoped_lock_t locker (endpoints_sync); - std::pair pending = pending_connections.equal_range(addr_); - for (pending_connections_t::iterator p = pending.first; p != pending.second; ++p) - connect_inproc_sockets(bind_socket_, endpoints[addr_].options, p->second, bind_side); + std::pair + pending = pending_connections.equal_range (addr_); + for (pending_connections_t::iterator p = pending.first; p != pending.second; + ++p) + connect_inproc_sockets (bind_socket_, endpoints[addr_].options, + p->second, bind_side); - pending_connections.erase(pending.first, pending.second); + pending_connections.erase (pending.first, pending.second); } -void zmq::ctx_t::connect_inproc_sockets (zmq::socket_base_t *bind_socket_, - options_t& bind_options, const pending_connection_t &pending_connection_, side side_) +void zmq::ctx_t::connect_inproc_sockets ( + zmq::socket_base_t *bind_socket_, + options_t &bind_options, + const pending_connection_t &pending_connection_, + side side_) { - bind_socket_->inc_seqnum(); + bind_socket_->inc_seqnum (); pending_connection_.bind_pipe->set_tid (bind_socket_->get_tid ()); if (!bind_options.recv_routing_id) { @@ -609,23 +600,29 @@ void zmq::ctx_t::connect_inproc_sockets (zmq::socket_base_t *bind_socket_, errno_assert (rc == 0); } - bool conflate = pending_connection_.endpoint.options.conflate && - (pending_connection_.endpoint.options.type == ZMQ_DEALER || - pending_connection_.endpoint.options.type == ZMQ_PULL || - pending_connection_.endpoint.options.type == ZMQ_PUSH || - pending_connection_.endpoint.options.type == ZMQ_PUB || - pending_connection_.endpoint.options.type == ZMQ_SUB); + bool conflate = + pending_connection_.endpoint.options.conflate + && (pending_connection_.endpoint.options.type == ZMQ_DEALER + || pending_connection_.endpoint.options.type == ZMQ_PULL + || pending_connection_.endpoint.options.type == ZMQ_PUSH + || pending_connection_.endpoint.options.type == ZMQ_PUB + || pending_connection_.endpoint.options.type == ZMQ_SUB); if (!conflate) { - pending_connection_.connect_pipe->set_hwms_boost(bind_options.sndhwm, bind_options.rcvhwm); - pending_connection_.bind_pipe->set_hwms_boost(pending_connection_.endpoint.options.sndhwm, pending_connection_.endpoint.options.rcvhwm); - - pending_connection_.connect_pipe->set_hwms(pending_connection_.endpoint.options.rcvhwm, pending_connection_.endpoint.options.sndhwm); - pending_connection_.bind_pipe->set_hwms(bind_options.rcvhwm, bind_options.sndhwm); - } - else { - pending_connection_.connect_pipe->set_hwms(-1, -1); - pending_connection_.bind_pipe->set_hwms(-1, -1); + pending_connection_.connect_pipe->set_hwms_boost (bind_options.sndhwm, + bind_options.rcvhwm); + pending_connection_.bind_pipe->set_hwms_boost ( + pending_connection_.endpoint.options.sndhwm, + pending_connection_.endpoint.options.rcvhwm); + + pending_connection_.connect_pipe->set_hwms ( + pending_connection_.endpoint.options.rcvhwm, + pending_connection_.endpoint.options.sndhwm); + pending_connection_.bind_pipe->set_hwms (bind_options.rcvhwm, + bind_options.sndhwm); + } else { + pending_connection_.connect_pipe->set_hwms (-1, -1); + pending_connection_.bind_pipe->set_hwms (-1, -1); } if (side_ == bind_side) { @@ -633,22 +630,24 @@ void zmq::ctx_t::connect_inproc_sockets (zmq::socket_base_t *bind_socket_, cmd.type = command_t::bind; cmd.args.bind.pipe = pending_connection_.bind_pipe; bind_socket_->process_command (cmd); - bind_socket_->send_inproc_connected (pending_connection_.endpoint.socket); - } - else - pending_connection_.connect_pipe->send_bind (bind_socket_, pending_connection_.bind_pipe, false); + bind_socket_->send_inproc_connected ( + pending_connection_.endpoint.socket); + } else + pending_connection_.connect_pipe->send_bind ( + bind_socket_, pending_connection_.bind_pipe, false); // When a ctx is terminated all pending inproc connection will be // connected, but the socket will already be closed and the pipe will be // in waiting_for_delimiter state, which means no more writes can be done // and the routing id write fails and causes an assert. Check if the socket // is open before sending. - if (pending_connection_.endpoint.options.recv_routing_id && - pending_connection_.endpoint.socket->check_tag ()) { + if (pending_connection_.endpoint.options.recv_routing_id + && pending_connection_.endpoint.socket->check_tag ()) { msg_t routing_id; const int rc = routing_id.init_size (bind_options.routing_id_size); errno_assert (rc == 0); - memcpy (routing_id.data (), bind_options.routing_id, bind_options.routing_id_size); + memcpy (routing_id.data (), bind_options.routing_id, + bind_options.routing_id_size); routing_id.set_flags (msg_t::routing_id); const bool written = pending_connection_.bind_pipe->write (&routing_id); zmq_assert (written); @@ -660,9 +659,9 @@ void zmq::ctx_t::connect_inproc_sockets (zmq::socket_base_t *bind_socket_, int zmq::ctx_t::get_vmci_socket_family () { - zmq::scoped_lock_t locker(vmci_sync); + zmq::scoped_lock_t locker (vmci_sync); - if (vmci_fd == -1) { + if (vmci_fd == -1) { vmci_family = VMCISock_GetAFValueFd (&vmci_fd); if (vmci_fd != -1) { diff --git a/src/ctx.hpp b/src/ctx.hpp index 10a4d0768b..24c7b55756 100644 --- a/src/ctx.hpp +++ b/src/ctx.hpp @@ -46,200 +46,208 @@ namespace zmq { +class object_t; +class io_thread_t; +class socket_base_t; +class reaper_t; +class pipe_t; + +// Information associated with inproc endpoint. Note that endpoint options +// are registered as well so that the peer can access them without a need +// for synchronisation, handshaking or similar. +struct endpoint_t +{ + socket_base_t *socket; + options_t options; +}; - class object_t; - class io_thread_t; - class socket_base_t; - class reaper_t; - class pipe_t; - - // Information associated with inproc endpoint. Note that endpoint options - // are registered as well so that the peer can access them without a need - // for synchronisation, handshaking or similar. - struct endpoint_t - { - socket_base_t *socket; - options_t options; - }; - - // Context object encapsulates all the global state associated with - // the library. +// Context object encapsulates all the global state associated with +// the library. - class ctx_t - { - public: - - // Create the context object. - ctx_t (); - - // Returns false if object is not a context. - bool check_tag (); - - // This function is called when user invokes zmq_ctx_term. If there are - // no more sockets open it'll cause all the infrastructure to be shut - // down. If there are open sockets still, the deallocation happens - // after the last one is closed. - int terminate (); - - // This function starts the terminate process by unblocking any blocking - // operations currently in progress and stopping any more socket activity - // (except zmq_close). - // This function is non-blocking. - // terminate must still be called afterwards. - // This function is optional, terminate will unblock any current - // operations as well. - int shutdown(); - - // Set and get context properties. - int set (int option_, int optval_); - int get (int option_); - - // Create and destroy a socket. - zmq::socket_base_t *create_socket (int type_); - void destroy_socket (zmq::socket_base_t *socket_); - - // Start a new thread with proper scheduling parameters. - void start_thread (thread_t &thread_, thread_fn *tfn_, void *arg_) const; - - // Send command to the destination thread. - void send_command (uint32_t tid_, const command_t &command_); - - // Returns the I/O thread that is the least busy at the moment. - // Affinity specifies which I/O threads are eligible (0 = all). - // Returns NULL if no I/O thread is available. - zmq::io_thread_t *choose_io_thread (uint64_t affinity_); - - // Returns reaper thread object. - zmq::object_t *get_reaper (); - - // Management of inproc endpoints. - int register_endpoint (const char *addr_, const endpoint_t &endpoint_); - int unregister_endpoint (const std::string &addr_, socket_base_t *socket_); - void unregister_endpoints (zmq::socket_base_t *socket_); - endpoint_t find_endpoint (const char *addr_); - void pend_connection (const std::string &addr_, - const endpoint_t &endpoint_, pipe_t **pipes_); - void connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_); +class ctx_t +{ + public: + // Create the context object. + ctx_t (); + + // Returns false if object is not a context. + bool check_tag (); + + // This function is called when user invokes zmq_ctx_term. If there are + // no more sockets open it'll cause all the infrastructure to be shut + // down. If there are open sockets still, the deallocation happens + // after the last one is closed. + int terminate (); + + // This function starts the terminate process by unblocking any blocking + // operations currently in progress and stopping any more socket activity + // (except zmq_close). + // This function is non-blocking. + // terminate must still be called afterwards. + // This function is optional, terminate will unblock any current + // operations as well. + int shutdown (); + + // Set and get context properties. + int set (int option_, int optval_); + int get (int option_); + + // Create and destroy a socket. + zmq::socket_base_t *create_socket (int type_); + void destroy_socket (zmq::socket_base_t *socket_); + + // Start a new thread with proper scheduling parameters. + void start_thread (thread_t &thread_, thread_fn *tfn_, void *arg_) const; + + // Send command to the destination thread. + void send_command (uint32_t tid_, const command_t &command_); + + // Returns the I/O thread that is the least busy at the moment. + // Affinity specifies which I/O threads are eligible (0 = all). + // Returns NULL if no I/O thread is available. + zmq::io_thread_t *choose_io_thread (uint64_t affinity_); + + // Returns reaper thread object. + zmq::object_t *get_reaper (); + + // Management of inproc endpoints. + int register_endpoint (const char *addr_, const endpoint_t &endpoint_); + int unregister_endpoint (const std::string &addr_, socket_base_t *socket_); + void unregister_endpoints (zmq::socket_base_t *socket_); + endpoint_t find_endpoint (const char *addr_); + void pend_connection (const std::string &addr_, + const endpoint_t &endpoint_, + pipe_t **pipes_); + void connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_); #ifdef ZMQ_HAVE_VMCI - // Return family for the VMCI socket or -1 if it's not available. - int get_vmci_socket_family (); + // Return family for the VMCI socket or -1 if it's not available. + int get_vmci_socket_family (); #endif - enum { - term_tid = 0, - reaper_tid = 1 - }; + enum + { + term_tid = 0, + reaper_tid = 1 + }; - ~ctx_t (); + ~ctx_t (); - bool valid() const; + bool valid () const; - private: - bool start(); + private: + bool start (); - struct pending_connection_t - { - endpoint_t endpoint; - pipe_t* connect_pipe; - pipe_t* bind_pipe; - }; + struct pending_connection_t + { + endpoint_t endpoint; + pipe_t *connect_pipe; + pipe_t *bind_pipe; + }; - // Used to check whether the object is a context. - uint32_t tag; + // Used to check whether the object is a context. + uint32_t tag; - // Sockets belonging to this context. We need the list so that - // we can notify the sockets when zmq_ctx_term() is called. - // The sockets will return ETERM then. - typedef array_t sockets_t; - sockets_t sockets; + // Sockets belonging to this context. We need the list so that + // we can notify the sockets when zmq_ctx_term() is called. + // The sockets will return ETERM then. + typedef array_t sockets_t; + sockets_t sockets; - // List of unused thread slots. - typedef std::vector empty_slots_t; - empty_slots_t empty_slots; + // List of unused thread slots. + typedef std::vector empty_slots_t; + empty_slots_t empty_slots; - // If true, zmq_init has been called but no socket has been created - // yet. Launching of I/O threads is delayed. - bool starting; + // If true, zmq_init has been called but no socket has been created + // yet. Launching of I/O threads is delayed. + bool starting; - // If true, zmq_ctx_term was already called. - bool terminating; + // If true, zmq_ctx_term was already called. + bool terminating; - // Synchronisation of accesses to global slot-related data: - // sockets, empty_slots, terminating. It also synchronises - // access to zombie sockets as such (as opposed to slots) and provides - // a memory barrier to ensure that all CPU cores see the same data. - mutex_t slot_sync; + // Synchronisation of accesses to global slot-related data: + // sockets, empty_slots, terminating. It also synchronises + // access to zombie sockets as such (as opposed to slots) and provides + // a memory barrier to ensure that all CPU cores see the same data. + mutex_t slot_sync; - // The reaper thread. - zmq::reaper_t *reaper; + // The reaper thread. + zmq::reaper_t *reaper; - // I/O threads. - typedef std::vector io_threads_t; - io_threads_t io_threads; + // I/O threads. + typedef std::vector io_threads_t; + io_threads_t io_threads; - // Array of pointers to mailboxes for both application and I/O threads. - uint32_t slot_count; - i_mailbox **slots; + // Array of pointers to mailboxes for both application and I/O threads. + uint32_t slot_count; + i_mailbox **slots; - // Mailbox for zmq_ctx_term thread. - mailbox_t term_mailbox; + // Mailbox for zmq_ctx_term thread. + mailbox_t term_mailbox; - // List of inproc endpoints within this context. - typedef std::map endpoints_t; - endpoints_t endpoints; + // List of inproc endpoints within this context. + typedef std::map endpoints_t; + endpoints_t endpoints; - // List of inproc connection endpoints pending a bind - typedef std::multimap pending_connections_t; - pending_connections_t pending_connections; + // List of inproc connection endpoints pending a bind + typedef std::multimap + pending_connections_t; + pending_connections_t pending_connections; - // Synchronisation of access to the list of inproc endpoints. - mutex_t endpoints_sync; + // Synchronisation of access to the list of inproc endpoints. + mutex_t endpoints_sync; - // Maximum socket ID. - static atomic_counter_t max_socket_id; + // Maximum socket ID. + static atomic_counter_t max_socket_id; - // Maximum number of sockets that can be opened at the same time. - int max_sockets; + // Maximum number of sockets that can be opened at the same time. + int max_sockets; - // Maximum allowed message size - int max_msgsz; + // Maximum allowed message size + int max_msgsz; - // Number of I/O threads to launch. - int io_thread_count; + // Number of I/O threads to launch. + int io_thread_count; - // Does context wait (possibly forever) on termination? - bool blocky; + // Does context wait (possibly forever) on termination? + bool blocky; - // Is IPv6 enabled on this context? - bool ipv6; + // Is IPv6 enabled on this context? + bool ipv6; - // Thread parameters. - int thread_priority; - int thread_sched_policy; - std::set thread_affinity_cpus; - std::string thread_name_prefix; + // Thread parameters. + int thread_priority; + int thread_sched_policy; + std::set thread_affinity_cpus; + std::string thread_name_prefix; - // Synchronisation of access to context options. - mutex_t opt_sync; + // Synchronisation of access to context options. + mutex_t opt_sync; - ctx_t (const ctx_t&); - const ctx_t &operator = (const ctx_t&); + ctx_t (const ctx_t &); + const ctx_t &operator= (const ctx_t &); #ifdef HAVE_FORK - // the process that created this context. Used to detect forking. - pid_t pid; + // the process that created this context. Used to detect forking. + pid_t pid; #endif - enum side { connect_side, bind_side }; - void connect_inproc_sockets(zmq::socket_base_t *bind_socket_, options_t& bind_options, const pending_connection_t &pending_connection_, side side_); + enum side + { + connect_side, + bind_side + }; + void + connect_inproc_sockets (zmq::socket_base_t *bind_socket_, + options_t &bind_options, + const pending_connection_t &pending_connection_, + side side_); #ifdef ZMQ_HAVE_VMCI - int vmci_fd; - int vmci_family; - mutex_t vmci_sync; + int vmci_fd; + int vmci_family; + mutex_t vmci_sync; #endif - }; - +}; } #endif diff --git a/src/curve_client.cpp b/src/curve_client.cpp index 8c85d168e6..dd9102fb72 100644 --- a/src/curve_client.cpp +++ b/src/curve_client.cpp @@ -80,7 +80,7 @@ int zmq::curve_client_t::next_handshake_command (msg_t *msg_) int zmq::curve_client_t::process_handshake_command (msg_t *msg_) { const unsigned char *msg_data = - static_cast (msg_->data ()); + static_cast (msg_->data ()); const size_t msg_size = msg_->size (); int rc = 0; @@ -94,8 +94,7 @@ int zmq::curve_client_t::process_handshake_command (msg_t *msg_) rc = process_error (msg_data, msg_size); else { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; rc = -1; } @@ -126,8 +125,7 @@ zmq::mechanism_t::status_t zmq::curve_client_t::status () const { if (state == connected) return mechanism_t::ready; - else - if (state == error_received) + else if (state == error_received) return mechanism_t::error; else return mechanism_t::handshaking; @@ -141,11 +139,10 @@ int zmq::curve_client_t::produce_hello (msg_t *msg_) rc = tools.produce_hello (msg_->data (), cn_nonce); if (rc == -1) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); - - // TODO this is somewhat inconsistent: we call init_size, but we may - // not close msg_; i.e. we assume that msg_ is initialized but empty + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); + + // TODO this is somewhat inconsistent: we call init_size, but we may + // not close msg_; i.e. we assume that msg_ is initialized but empty // (if it were non-empty, calling init_size might cause a leak!) // msg_->close (); @@ -164,8 +161,7 @@ int zmq::curve_client_t::process_welcome (const uint8_t *msg_data, if (rc == -1) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); errno = EPROTO; return -1; @@ -196,8 +192,7 @@ int zmq::curve_client_t::produce_initiate (msg_t *msg_) if (-1 == rc) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); // TODO see comment in produce_hello return -1; @@ -208,8 +203,8 @@ int zmq::curve_client_t::produce_initiate (msg_t *msg_) return 0; } -int zmq::curve_client_t::process_ready ( - const uint8_t *msg_data, size_t msg_size) +int zmq::curve_client_t::process_ready (const uint8_t *msg_data, + size_t msg_size) { if (msg_size < 30) { session->get_socket ()->event_handshake_failed_protocol ( @@ -221,7 +216,7 @@ int zmq::curve_client_t::process_ready ( const size_t clen = (msg_size - 14) + crypto_box_BOXZEROBYTES; - uint8_t ready_nonce [crypto_box_NONCEBYTES]; + uint8_t ready_nonce[crypto_box_NONCEBYTES]; uint8_t *ready_plaintext = (uint8_t *) malloc (crypto_box_ZEROBYTES + clen); alloc_assert (ready_plaintext); uint8_t *ready_box = @@ -229,21 +224,20 @@ int zmq::curve_client_t::process_ready ( alloc_assert (ready_box); memset (ready_box, 0, crypto_box_BOXZEROBYTES); - memcpy (ready_box + crypto_box_BOXZEROBYTES, - msg_data + 14, clen - crypto_box_BOXZEROBYTES); + memcpy (ready_box + crypto_box_BOXZEROBYTES, msg_data + 14, + clen - crypto_box_BOXZEROBYTES); memcpy (ready_nonce, "CurveZMQREADY---", 16); memcpy (ready_nonce + 16, msg_data + 6, 8); - cn_peer_nonce = get_uint64(msg_data + 6); + cn_peer_nonce = get_uint64 (msg_data + 6); - int rc = crypto_box_open_afternm (ready_plaintext, ready_box, - clen, ready_nonce, cn_precom); + int rc = crypto_box_open_afternm (ready_plaintext, ready_box, clen, + ready_nonce, cn_precom); free (ready_box); if (rc != 0) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); errno = EPROTO; return -1; } @@ -254,8 +248,7 @@ int zmq::curve_client_t::process_ready ( if (rc == 0) state = connected; - else - { + else { session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_METADATA); errno = EPROTO; @@ -264,8 +257,8 @@ int zmq::curve_client_t::process_ready ( return rc; } -int zmq::curve_client_t::process_error ( - const uint8_t *msg_data, size_t msg_size) +int zmq::curve_client_t::process_error (const uint8_t *msg_data, + size_t msg_size) { if (state != expect_welcome && state != expect_ready) { session->get_socket ()->event_handshake_failed_protocol ( @@ -280,7 +273,7 @@ int zmq::curve_client_t::process_error ( errno = EPROTO; return -1; } - const size_t error_reason_len = static_cast (msg_data [6]); + const size_t error_reason_len = static_cast (msg_data[6]); if (error_reason_len > msg_size - 7) { session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), diff --git a/src/curve_client.hpp b/src/curve_client.hpp index 7693ac6485..07c3daf23f 100644 --- a/src/curve_client.hpp +++ b/src/curve_client.hpp @@ -38,48 +38,45 @@ namespace zmq { +class msg_t; +class session_base_t; - class msg_t; - class session_base_t; - - class curve_client_t : public curve_mechanism_base_t +class curve_client_t : public curve_mechanism_base_t +{ + public: + curve_client_t (session_base_t *session_, const options_t &options_); + virtual ~curve_client_t (); + + // mechanism implementation + virtual int next_handshake_command (msg_t *msg_); + virtual int process_handshake_command (msg_t *msg_); + virtual int encode (msg_t *msg_); + virtual int decode (msg_t *msg_); + virtual status_t status () const; + + private: + enum state_t { - public: - - curve_client_t (session_base_t *session_, const options_t &options_); - virtual ~curve_client_t (); - - // mechanism implementation - virtual int next_handshake_command (msg_t *msg_); - virtual int process_handshake_command (msg_t *msg_); - virtual int encode (msg_t *msg_); - virtual int decode (msg_t *msg_); - virtual status_t status () const; - - private: - - enum state_t { - send_hello, - expect_welcome, - send_initiate, - expect_ready, - error_received, - connected - }; - - // Current FSM state - state_t state; - - // CURVE protocol tools - curve_client_tools_t tools; - - int produce_hello (msg_t *msg_); - int process_welcome (const uint8_t *cmd_data, size_t data_size); - int produce_initiate (msg_t *msg_); - int process_ready (const uint8_t *cmd_data, size_t data_size); - int process_error (const uint8_t *cmd_data, size_t data_size); + send_hello, + expect_welcome, + send_initiate, + expect_ready, + error_received, + connected }; + // Current FSM state + state_t state; + + // CURVE protocol tools + curve_client_tools_t tools; + + int produce_hello (msg_t *msg_); + int process_welcome (const uint8_t *cmd_data, size_t data_size); + int produce_initiate (msg_t *msg_); + int process_ready (const uint8_t *cmd_data, size_t data_size); + int process_error (const uint8_t *cmd_data, size_t data_size); +}; } #endif diff --git a/src/curve_client_tools.hpp b/src/curve_client_tools.hpp index cb162115e6..5ca2450118 100644 --- a/src/curve_client_tools.hpp +++ b/src/curve_client_tools.hpp @@ -153,8 +153,7 @@ struct curve_client_tools_t // Create vouch = Box [C',S](C->S') memset (vouch_plaintext, 0, crypto_box_ZEROBYTES); memcpy (vouch_plaintext + crypto_box_ZEROBYTES, cn_public, 32); - memcpy (vouch_plaintext + crypto_box_ZEROBYTES + 32, server_key, - 32); + memcpy (vouch_plaintext + crypto_box_ZEROBYTES + 32, server_key, 32); memcpy (vouch_nonce, "VOUCH---", 8); randombytes (vouch_nonce + 8, 16); @@ -165,8 +164,8 @@ struct curve_client_tools_t return -1; uint8_t initiate_nonce[crypto_box_NONCEBYTES]; - uint8_t *initiate_box = (uint8_t *) malloc ( - crypto_box_BOXZEROBYTES + 144 + metadata_length); + uint8_t *initiate_box = + (uint8_t *) malloc (crypto_box_BOXZEROBYTES + 144 + metadata_length); alloc_assert (initiate_box); uint8_t *initiate_plaintext = (uint8_t *) malloc (crypto_box_ZEROBYTES + 128 + metadata_length); @@ -174,8 +173,7 @@ struct curve_client_tools_t // Create Box [C + vouch + metadata](C'->S') memset (initiate_plaintext, 0, crypto_box_ZEROBYTES); - memcpy (initiate_plaintext + crypto_box_ZEROBYTES, public_key, - 32); + memcpy (initiate_plaintext + crypto_box_ZEROBYTES, public_key, 32); memcpy (initiate_plaintext + crypto_box_ZEROBYTES + 32, vouch_nonce + 8, 16); memcpy (initiate_plaintext + crypto_box_ZEROBYTES + 48, diff --git a/src/curve_mechanism_base.cpp b/src/curve_mechanism_base.cpp index b61edd2e0b..338e0e539e 100644 --- a/src/curve_mechanism_base.cpp +++ b/src/curve_mechanism_base.cpp @@ -53,7 +53,7 @@ int zmq::curve_mechanism_base_t::encode (msg_t *msg_) { const size_t mlen = crypto_box_ZEROBYTES + 1 + msg_->size (); - uint8_t message_nonce [crypto_box_NONCEBYTES]; + uint8_t message_nonce[crypto_box_NONCEBYTES]; memcpy (message_nonce, encode_nonce_prefix, 16); put_uint64 (message_nonce + 16, cn_nonce); @@ -63,19 +63,19 @@ int zmq::curve_mechanism_base_t::encode (msg_t *msg_) if (msg_->flags () & msg_t::command) flags |= 0x02; - uint8_t *message_plaintext = static_cast (malloc (mlen)); + uint8_t *message_plaintext = static_cast (malloc (mlen)); alloc_assert (message_plaintext); memset (message_plaintext, 0, crypto_box_ZEROBYTES); - message_plaintext [crypto_box_ZEROBYTES] = flags; - memcpy (message_plaintext + crypto_box_ZEROBYTES + 1, - msg_->data (), msg_->size ()); + message_plaintext[crypto_box_ZEROBYTES] = flags; + memcpy (message_plaintext + crypto_box_ZEROBYTES + 1, msg_->data (), + msg_->size ()); - uint8_t *message_box = static_cast (malloc (mlen)); + uint8_t *message_box = static_cast (malloc (mlen)); alloc_assert (message_box); - int rc = crypto_box_afternm (message_box, message_plaintext, - mlen, message_nonce, cn_precom); + int rc = crypto_box_afternm (message_box, message_plaintext, mlen, + message_nonce, cn_precom); zmq_assert (rc == 0); rc = msg_->close (); @@ -84,7 +84,7 @@ int zmq::curve_mechanism_base_t::encode (msg_t *msg_) rc = msg_->init_size (16 + mlen - crypto_box_BOXZEROBYTES); zmq_assert (rc == 0); - uint8_t *message = static_cast (msg_->data ()); + uint8_t *message = static_cast (msg_->data ()); memcpy (message, "\x07MESSAGE", 8); memcpy (message + 8, message_nonce + 16, 8); @@ -103,11 +103,11 @@ int zmq::curve_mechanism_base_t::decode (msg_t *msg_) { int rc = check_basic_command_structure (msg_); if (rc == -1) - return -1; + return -1; const size_t size = msg_->size (); - const uint8_t *message = static_cast (msg_->data ()); - + const uint8_t *message = static_cast (msg_->data ()); + if (size < 8 || memcmp (message, "\x07MESSAGE", 8)) { session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); @@ -123,10 +123,10 @@ int zmq::curve_mechanism_base_t::decode (msg_t *msg_) return -1; } - uint8_t message_nonce [crypto_box_NONCEBYTES]; + uint8_t message_nonce[crypto_box_NONCEBYTES]; memcpy (message_nonce, decode_nonce_prefix, 16); memcpy (message_nonce + 16, message + 8, 8); - uint64_t nonce = get_uint64(message + 8); + uint64_t nonce = get_uint64 (message + 8); if (nonce <= cn_peer_nonce) { session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_SEQUENCE); @@ -137,15 +137,15 @@ int zmq::curve_mechanism_base_t::decode (msg_t *msg_) const size_t clen = crypto_box_BOXZEROBYTES + msg_->size () - 16; - uint8_t *message_plaintext = static_cast (malloc (clen)); + uint8_t *message_plaintext = static_cast (malloc (clen)); alloc_assert (message_plaintext); - uint8_t *message_box = static_cast (malloc (clen)); + uint8_t *message_box = static_cast (malloc (clen)); alloc_assert (message_box); memset (message_box, 0, crypto_box_BOXZEROBYTES); - memcpy (message_box + crypto_box_BOXZEROBYTES, - message + 16, msg_->size () - 16); + memcpy (message_box + crypto_box_BOXZEROBYTES, message + 16, + msg_->size () - 16); rc = crypto_box_open_afternm (message_plaintext, message_box, clen, message_nonce, cn_precom); @@ -156,17 +156,15 @@ int zmq::curve_mechanism_base_t::decode (msg_t *msg_) rc = msg_->init_size (clen - 1 - crypto_box_ZEROBYTES); zmq_assert (rc == 0); - const uint8_t flags = message_plaintext [crypto_box_ZEROBYTES]; + const uint8_t flags = message_plaintext[crypto_box_ZEROBYTES]; if (flags & 0x01) msg_->set_flags (msg_t::more); if (flags & 0x02) msg_->set_flags (msg_t::command); - memcpy (msg_->data (), - message_plaintext + crypto_box_ZEROBYTES + 1, + memcpy (msg_->data (), message_plaintext + crypto_box_ZEROBYTES + 1, msg_->size ()); - } - else { + } else { // CURVE I : connection key used for MESSAGE is wrong session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); diff --git a/src/curve_mechanism_base.hpp b/src/curve_mechanism_base.hpp index 98cfd03d91..6128df1cad 100644 --- a/src/curve_mechanism_base.hpp +++ b/src/curve_mechanism_base.hpp @@ -70,7 +70,7 @@ class curve_mechanism_base_t : public virtual mechanism_base_t uint64_t cn_peer_nonce; // Intermediary buffer used to speed up boxing and unboxing. - uint8_t cn_precom [crypto_box_BEFORENMBYTES]; + uint8_t cn_precom[crypto_box_BEFORENMBYTES]; }; } diff --git a/src/curve_server.cpp b/src/curve_server.cpp index 643e887bb2..6938a637a1 100644 --- a/src/curve_server.cpp +++ b/src/curve_server.cpp @@ -100,10 +100,10 @@ int zmq::curve_server_t::process_handshake_command (msg_t *msg_) rc = process_initiate (msg_); break; default: - // TODO I think this is not a case reachable with a misbehaving - // client. It is not an "invalid handshake command", but would be - // trying to process a handshake command in an invalid state, - // which is purely under control of this peer. + // TODO I think this is not a case reachable with a misbehaving + // client. It is not an "invalid handshake command", but would be + // trying to process a handshake command in an invalid state, + // which is purely under control of this peer. // Therefore, it should be changed to zmq_assert (false); // CURVE I: invalid handshake command @@ -138,10 +138,10 @@ int zmq::curve_server_t::process_hello (msg_t *msg_) { int rc = check_basic_command_structure (msg_); if (rc == -1) - return -1; + return -1; const size_t size = msg_->size (); - const uint8_t * const hello = static_cast (msg_->data ()); + const uint8_t *const hello = static_cast (msg_->data ()); if (size < 6 || memcmp (hello, "\x05HELLO", 6)) { session->get_socket ()->event_handshake_failed_protocol ( @@ -152,18 +152,20 @@ int zmq::curve_server_t::process_hello (msg_t *msg_) if (size != 200) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); + session->get_endpoint (), + ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } - const uint8_t major = hello [6]; - const uint8_t minor = hello [7]; + const uint8_t major = hello[6]; + const uint8_t minor = hello[7]; if (major != 1 || minor != 0) { // CURVE I: client HELLO has unknown version number session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); + session->get_endpoint (), + ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } @@ -171,13 +173,13 @@ int zmq::curve_server_t::process_hello (msg_t *msg_) // Save client's short-term public key (C') memcpy (cn_client, hello + 80, 32); - uint8_t hello_nonce [crypto_box_NONCEBYTES]; - uint8_t hello_plaintext [crypto_box_ZEROBYTES + 64]; - uint8_t hello_box [crypto_box_BOXZEROBYTES + 80]; + uint8_t hello_nonce[crypto_box_NONCEBYTES]; + uint8_t hello_plaintext[crypto_box_ZEROBYTES + 64]; + uint8_t hello_box[crypto_box_BOXZEROBYTES + 80]; memcpy (hello_nonce, "CurveZMQHELLO---", 16); memcpy (hello_nonce + 16, hello + 112, 8); - cn_peer_nonce = get_uint64(hello + 112); + cn_peer_nonce = get_uint64 (hello + 112); memset (hello_box, 0, crypto_box_BOXZEROBYTES); memcpy (hello_box + crypto_box_BOXZEROBYTES, hello + 120, 80); @@ -199,9 +201,9 @@ int zmq::curve_server_t::process_hello (msg_t *msg_) int zmq::curve_server_t::produce_welcome (msg_t *msg_) { - uint8_t cookie_nonce [crypto_secretbox_NONCEBYTES]; - uint8_t cookie_plaintext [crypto_secretbox_ZEROBYTES + 64]; - uint8_t cookie_ciphertext [crypto_secretbox_BOXZEROBYTES + 80]; + uint8_t cookie_nonce[crypto_secretbox_NONCEBYTES]; + uint8_t cookie_plaintext[crypto_secretbox_ZEROBYTES + 64]; + uint8_t cookie_ciphertext[crypto_secretbox_BOXZEROBYTES + 80]; // Create full nonce for encryption // 8-byte prefix plus 16-byte random nonce @@ -210,23 +212,21 @@ int zmq::curve_server_t::produce_welcome (msg_t *msg_) // Generate cookie = Box [C' + s'](t) memset (cookie_plaintext, 0, crypto_secretbox_ZEROBYTES); - memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES, - cn_client, 32); - memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES + 32, - cn_secret, 32); + memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES, cn_client, 32); + memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES + 32, cn_secret, 32); // Generate fresh cookie key randombytes (cookie_key, crypto_secretbox_KEYBYTES); // Encrypt using symmetric cookie key - int rc = crypto_secretbox (cookie_ciphertext, cookie_plaintext, - sizeof cookie_plaintext, - cookie_nonce, cookie_key); + int rc = + crypto_secretbox (cookie_ciphertext, cookie_plaintext, + sizeof cookie_plaintext, cookie_nonce, cookie_key); zmq_assert (rc == 0); - uint8_t welcome_nonce [crypto_box_NONCEBYTES]; - uint8_t welcome_plaintext [crypto_box_ZEROBYTES + 128]; - uint8_t welcome_ciphertext [crypto_box_BOXZEROBYTES + 144]; + uint8_t welcome_nonce[crypto_box_NONCEBYTES]; + uint8_t welcome_plaintext[crypto_box_ZEROBYTES + 128]; + uint8_t welcome_ciphertext[crypto_box_BOXZEROBYTES + 144]; // Create full nonce for encryption // 8-byte prefix plus 16-byte random nonce @@ -236,8 +236,8 @@ int zmq::curve_server_t::produce_welcome (msg_t *msg_) // Create 144-byte Box [S' + cookie](S->C') memset (welcome_plaintext, 0, crypto_box_ZEROBYTES); memcpy (welcome_plaintext + crypto_box_ZEROBYTES, cn_public, 32); - memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 32, - cookie_nonce + 8, 16); + memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 32, cookie_nonce + 8, + 16); memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 48, cookie_ciphertext + crypto_secretbox_BOXZEROBYTES, 80); @@ -257,7 +257,7 @@ int zmq::curve_server_t::produce_welcome (msg_t *msg_) rc = msg_->init_size (168); errno_assert (rc == 0); - uint8_t * const welcome = static_cast (msg_->data ()); + uint8_t *const welcome = static_cast (msg_->data ()); memcpy (welcome, "\x07WELCOME", 8); memcpy (welcome + 8, welcome_nonce + 8, 16); memcpy (welcome + 24, welcome_ciphertext + crypto_box_BOXZEROBYTES, 144); @@ -269,10 +269,10 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_) { int rc = check_basic_command_structure (msg_); if (rc == -1) - return -1; + return -1; const size_t size = msg_->size (); - const uint8_t *initiate = static_cast (msg_->data ()); + const uint8_t *initiate = static_cast (msg_->data ()); if (size < 9 || memcmp (initiate, "\x08INITIATE", 9)) { session->get_socket ()->event_handshake_failed_protocol ( @@ -289,9 +289,9 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_) return -1; } - uint8_t cookie_nonce [crypto_secretbox_NONCEBYTES]; - uint8_t cookie_plaintext [crypto_secretbox_ZEROBYTES + 64]; - uint8_t cookie_box [crypto_secretbox_BOXZEROBYTES + 80]; + uint8_t cookie_nonce[crypto_secretbox_NONCEBYTES]; + uint8_t cookie_plaintext[crypto_secretbox_ZEROBYTES + 64]; + uint8_t cookie_box[crypto_secretbox_BOXZEROBYTES + 80]; // Open Box [C' + s'](t) memset (cookie_box, 0, crypto_secretbox_BOXZEROBYTES); @@ -312,7 +312,8 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_) // Check cookie plain text is as expected [C' + s'] if (memcmp (cookie_plaintext + crypto_secretbox_ZEROBYTES, cn_client, 32) - || memcmp (cookie_plaintext + crypto_secretbox_ZEROBYTES + 32, cn_secret, 32)) { + || memcmp (cookie_plaintext + crypto_secretbox_ZEROBYTES + 32, + cn_secret, 32)) { // TODO this case is very hard to test, as it would require a modified // client that knows the server's secret temporary cookie key @@ -325,21 +326,21 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_) const size_t clen = (size - 113) + crypto_box_BOXZEROBYTES; - uint8_t initiate_nonce [crypto_box_NONCEBYTES]; - uint8_t initiate_plaintext [crypto_box_ZEROBYTES + 128 + 256]; - uint8_t initiate_box [crypto_box_BOXZEROBYTES + 144 + 256]; + uint8_t initiate_nonce[crypto_box_NONCEBYTES]; + uint8_t initiate_plaintext[crypto_box_ZEROBYTES + 128 + 256]; + uint8_t initiate_box[crypto_box_BOXZEROBYTES + 144 + 256]; // Open Box [C + vouch + metadata](C'->S') memset (initiate_box, 0, crypto_box_BOXZEROBYTES); - memcpy (initiate_box + crypto_box_BOXZEROBYTES, - initiate + 113, clen - crypto_box_BOXZEROBYTES); + memcpy (initiate_box + crypto_box_BOXZEROBYTES, initiate + 113, + clen - crypto_box_BOXZEROBYTES); memcpy (initiate_nonce, "CurveZMQINITIATE", 16); memcpy (initiate_nonce + 16, initiate + 105, 8); - cn_peer_nonce = get_uint64(initiate + 105); + cn_peer_nonce = get_uint64 (initiate + 105); - rc = crypto_box_open (initiate_plaintext, initiate_box, - clen, initiate_nonce, cn_client, cn_secret); + rc = crypto_box_open (initiate_plaintext, initiate_box, clen, + initiate_nonce, cn_client, cn_secret); if (rc != 0) { // CURVE I: cannot open client INITIATE session->get_socket ()->event_handshake_failed_protocol ( @@ -350,9 +351,9 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_) const uint8_t *client_key = initiate_plaintext + crypto_box_ZEROBYTES; - uint8_t vouch_nonce [crypto_box_NONCEBYTES]; - uint8_t vouch_plaintext [crypto_box_ZEROBYTES + 64]; - uint8_t vouch_box [crypto_box_BOXZEROBYTES + 80]; + uint8_t vouch_nonce[crypto_box_NONCEBYTES]; + uint8_t vouch_plaintext[crypto_box_ZEROBYTES + 64]; + uint8_t vouch_box[crypto_box_BOXZEROBYTES + 80]; // Open Box Box [C',S](C->S') and check contents memset (vouch_box, 0, crypto_box_BOXZEROBYTES); @@ -360,11 +361,10 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_) initiate_plaintext + crypto_box_ZEROBYTES + 48, 80); memcpy (vouch_nonce, "VOUCH---", 8); - memcpy (vouch_nonce + 8, - initiate_plaintext + crypto_box_ZEROBYTES + 32, 16); + memcpy (vouch_nonce + 8, initiate_plaintext + crypto_box_ZEROBYTES + 32, + 16); - rc = crypto_box_open (vouch_plaintext, vouch_box, - sizeof vouch_box, + rc = crypto_box_open (vouch_plaintext, vouch_box, sizeof vouch_box, vouch_nonce, client_key, cn_secret); if (rc != 0) { // CURVE I: cannot open client INITIATE vouch @@ -399,9 +399,9 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_) send_zap_request (client_key); state = waiting_for_zap_reply; - // TODO actually, it is quite unlikely that we can read the ZAP + // TODO actually, it is quite unlikely that we can read the ZAP // reply already, but removing this has some strange side-effect - // (probably because the pipe's in_active flag is true until a read + // (probably because the pipe's in_active flag is true until a read // is attempted) rc = receive_and_process_zap_reply (); if (rc == -1) @@ -427,7 +427,7 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_) int zmq::curve_server_t::produce_ready (msg_t *msg_) { const size_t metadata_length = basic_properties_len (); - uint8_t ready_nonce [crypto_box_NONCEBYTES]; + uint8_t ready_nonce[crypto_box_NONCEBYTES]; uint8_t *ready_plaintext = (uint8_t *) malloc (crypto_box_ZEROBYTES + metadata_length); @@ -456,7 +456,7 @@ int zmq::curve_server_t::produce_ready (msg_t *msg_) rc = msg_->init_size (14 + mlen - crypto_box_BOXZEROBYTES); errno_assert (rc == 0); - uint8_t *ready = static_cast (msg_->data ()); + uint8_t *ready = static_cast (msg_->data ()); memcpy (ready, "\x05READY", 6); // Short nonce, prefixed by "CurveZMQREADY---" @@ -477,9 +477,9 @@ int zmq::curve_server_t::produce_error (msg_t *msg_) const zmq_assert (status_code.length () == 3); const int rc = msg_->init_size (6 + 1 + expected_status_code_length); zmq_assert (rc == 0); - char *msg_data = static_cast (msg_->data ()); + char *msg_data = static_cast (msg_->data ()); memcpy (msg_data, "\5ERROR", 6); - msg_data [6] = expected_status_code_length; + msg_data[6] = expected_status_code_length; memcpy (msg_data + 7, status_code.c_str (), expected_status_code_length); return 0; } diff --git a/src/curve_server.hpp b/src/curve_server.hpp index 30efda5dcb..ce023152ff 100644 --- a/src/curve_server.hpp +++ b/src/curve_server.hpp @@ -39,54 +39,51 @@ namespace zmq { #ifdef _MSC_VER -#pragma warning (push) -#pragma warning (disable: 4250) +#pragma warning(push) +#pragma warning(disable : 4250) #endif - class curve_server_t : public zap_client_common_handshake_t, - public curve_mechanism_base_t - { - public: - - curve_server_t (session_base_t *session_, - const std::string &peer_address_, - const options_t &options_); - virtual ~curve_server_t (); - - // mechanism implementation - virtual int next_handshake_command (msg_t *msg_); - virtual int process_handshake_command (msg_t *msg_); - virtual int encode (msg_t *msg_); - virtual int decode (msg_t *msg_); - - private: - - // Our secret key (s) - uint8_t secret_key [crypto_box_SECRETKEYBYTES]; - - // Our short-term public key (S') - uint8_t cn_public [crypto_box_PUBLICKEYBYTES]; - - // Our short-term secret key (s') - uint8_t cn_secret [crypto_box_SECRETKEYBYTES]; - - // Client's short-term public key (C') - uint8_t cn_client [crypto_box_PUBLICKEYBYTES]; - - // Key used to produce cookie - uint8_t cookie_key [crypto_secretbox_KEYBYTES]; - - int process_hello (msg_t *msg_); - int produce_welcome (msg_t *msg_); - int process_initiate (msg_t *msg_); - int produce_ready (msg_t *msg_); - int produce_error (msg_t *msg_) const; - - void send_zap_request (const uint8_t *key); - }; +class curve_server_t : public zap_client_common_handshake_t, + public curve_mechanism_base_t +{ + public: + curve_server_t (session_base_t *session_, + const std::string &peer_address_, + const options_t &options_); + virtual ~curve_server_t (); + + // mechanism implementation + virtual int next_handshake_command (msg_t *msg_); + virtual int process_handshake_command (msg_t *msg_); + virtual int encode (msg_t *msg_); + virtual int decode (msg_t *msg_); + + private: + // Our secret key (s) + uint8_t secret_key[crypto_box_SECRETKEYBYTES]; + + // Our short-term public key (S') + uint8_t cn_public[crypto_box_PUBLICKEYBYTES]; + + // Our short-term secret key (s') + uint8_t cn_secret[crypto_box_SECRETKEYBYTES]; + + // Client's short-term public key (C') + uint8_t cn_client[crypto_box_PUBLICKEYBYTES]; + + // Key used to produce cookie + uint8_t cookie_key[crypto_secretbox_KEYBYTES]; + + int process_hello (msg_t *msg_); + int produce_welcome (msg_t *msg_); + int process_initiate (msg_t *msg_); + int produce_ready (msg_t *msg_); + int produce_error (msg_t *msg_) const; + + void send_zap_request (const uint8_t *key); +}; #ifdef _MSC_VER -#pragma warning (pop) +#pragma warning(pop) #endif - } #endif diff --git a/src/dbuffer.hpp b/src/dbuffer.hpp index 0e0186e524..7014ea1c7a 100644 --- a/src/dbuffer.hpp +++ b/src/dbuffer.hpp @@ -39,106 +39,103 @@ namespace zmq { - - // dbuffer is a single-producer single-consumer double-buffer - // implementation. - // - // The producer writes to a back buffer and then tries to swap - // pointers between the back and front buffers. If it fails, - // due to the consumer reading from the front buffer, it just - // gives up, which is ok since writes are many and redundant. - // - // The reader simply reads from the front buffer. - // - // has_msg keeps track of whether there has been a not yet read - // value written, it is used by ypipe_conflate to mimic ypipe - // functionality regarding a reader being asleep - - template class dbuffer_t; - - template <> class dbuffer_t +// dbuffer is a single-producer single-consumer double-buffer +// implementation. +// +// The producer writes to a back buffer and then tries to swap +// pointers between the back and front buffers. If it fails, +// due to the consumer reading from the front buffer, it just +// gives up, which is ok since writes are many and redundant. +// +// The reader simply reads from the front buffer. +// +// has_msg keeps track of whether there has been a not yet read +// value written, it is used by ypipe_conflate to mimic ypipe +// functionality regarding a reader being asleep + +template class dbuffer_t; + +template <> class dbuffer_t +{ + public: + inline dbuffer_t () : + back (&storage[0]), + front (&storage[1]), + has_msg (false) { - public: - - inline dbuffer_t () - : back (&storage[0]) - , front (&storage[1]) - , has_msg (false) - { - back->init (); - front->init (); - } + back->init (); + front->init (); + } - inline ~dbuffer_t() - { - back->close (); - front->close (); - } + inline ~dbuffer_t () + { + back->close (); + front->close (); + } - inline void write (const msg_t &value_) - { - msg_t& xvalue = const_cast(value_); + inline void write (const msg_t &value_) + { + msg_t &xvalue = const_cast (value_); - zmq_assert (xvalue.check ()); - back->move (xvalue); // cannot just overwrite, might leak + zmq_assert (xvalue.check ()); + back->move (xvalue); // cannot just overwrite, might leak - zmq_assert (back->check ()); + zmq_assert (back->check ()); - if (sync.try_lock ()) - { - std::swap (back, front); - has_msg = true; + if (sync.try_lock ()) { + std::swap (back, front); + has_msg = true; - sync.unlock (); - } + sync.unlock (); } + } + + inline bool read (msg_t *value_) + { + if (!value_) + return false; - inline bool read (msg_t *value_) { - if (!value_) + scoped_lock_t lock (sync); + if (!has_msg) return false; - { - scoped_lock_t lock (sync); - if (!has_msg) - return false; - - zmq_assert (front->check ()); + zmq_assert (front->check ()); - *value_ = *front; - front->init (); // avoid double free + *value_ = *front; + front->init (); // avoid double free - has_msg = false; - return true; - } + has_msg = false; + return true; } + } - inline bool check_read () - { - scoped_lock_t lock (sync); + inline bool check_read () + { + scoped_lock_t lock (sync); - return has_msg; - } + return has_msg; + } - inline bool probe (bool (*fn)(const msg_t &)) - { - scoped_lock_t lock (sync); - return (*fn) (*front); - } + inline bool probe (bool (*fn) (const msg_t &)) + { + scoped_lock_t lock (sync); + return (*fn) (*front); + } - private: - msg_t storage[2]; - msg_t *back, *front; + private: + msg_t storage[2]; + msg_t *back, *front; - mutex_t sync; - bool has_msg; + mutex_t sync; + bool has_msg; - // Disable copying of dbuffer. - dbuffer_t (const dbuffer_t&); - const dbuffer_t &operator = (const dbuffer_t&); - }; + // Disable copying of dbuffer. + dbuffer_t (const dbuffer_t &); + const dbuffer_t &operator= (const dbuffer_t &); +}; } #endif diff --git a/src/dealer.cpp b/src/dealer.cpp index a0f67914ec..81da60fd99 100644 --- a/src/dealer.cpp +++ b/src/dealer.cpp @@ -67,12 +67,14 @@ void zmq::dealer_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_) lb.attach (pipe_); } -int zmq::dealer_t::xsetsockopt (int option_, const void *optval_, - size_t optvallen_) +int zmq::dealer_t::xsetsockopt (int option_, + const void *optval_, + size_t optvallen_) { bool is_int = (optvallen_ == sizeof (int)); int value = 0; - if (is_int) memcpy(&value, optval_, sizeof (int)); + if (is_int) + memcpy (&value, optval_, sizeof (int)); switch (option_) { case ZMQ_PROBE_ROUTER: diff --git a/src/dealer.hpp b/src/dealer.hpp index 826ca43ff2..f1d67ddcd3 100644 --- a/src/dealer.hpp +++ b/src/dealer.hpp @@ -37,53 +37,47 @@ namespace zmq { +class ctx_t; +class msg_t; +class pipe_t; +class io_thread_t; +class socket_base_t; - class ctx_t; - class msg_t; - class pipe_t; - class io_thread_t; - class socket_base_t; - - class dealer_t : - public socket_base_t - { - public: - - dealer_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); - ~dealer_t (); - - protected: - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsetsockopt (int option_, const void *optval_, size_t optvallen_); - int xsend (zmq::msg_t *msg_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - bool xhas_out (); - const blob_t &get_credential () const; - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - // Send and recv - knowing which pipe was used. - int sendpipe (zmq::msg_t *msg_, zmq::pipe_t **pipe_); - int recvpipe (zmq::msg_t *msg_, zmq::pipe_t **pipe_); - - private: - - // Messages are fair-queued from inbound pipes. And load-balanced to - // the outbound pipes. - fq_t fq; - lb_t lb; - - // if true, send an empty message to every connected router peer - bool probe_router; - - dealer_t (const dealer_t&); - const dealer_t &operator = (const dealer_t&); - }; - +class dealer_t : public socket_base_t +{ + public: + dealer_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); + ~dealer_t (); + + protected: + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsetsockopt (int option_, const void *optval_, size_t optvallen_); + int xsend (zmq::msg_t *msg_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + bool xhas_out (); + const blob_t &get_credential () const; + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + // Send and recv - knowing which pipe was used. + int sendpipe (zmq::msg_t *msg_, zmq::pipe_t **pipe_); + int recvpipe (zmq::msg_t *msg_, zmq::pipe_t **pipe_); + + private: + // Messages are fair-queued from inbound pipes. And load-balanced to + // the outbound pipes. + fq_t fq; + lb_t lb; + + // if true, send an empty message to every connected router peer + bool probe_router; + + dealer_t (const dealer_t &); + const dealer_t &operator= (const dealer_t &); +}; } #endif diff --git a/src/decoder.hpp b/src/decoder.hpp index c8fe5befd1..8cf663cd43 100644 --- a/src/decoder.hpp +++ b/src/decoder.hpp @@ -42,157 +42,152 @@ namespace zmq { - // Helper base class for decoders that know the amount of data to read - // in advance at any moment. Knowing the amount in advance is a property - // of the protocol used. 0MQ framing protocol is based size-prefixed - // paradigm, which qualifies it to be parsed by this class. - // On the other hand, XML-based transports (like XMPP or SOAP) don't allow - // for knowing the size of data to read in advance and should use different - // decoding algorithms. - // - // This class implements the state machine that parses the incoming buffer. - // Derived class should implement individual state machine actions. - // - // Buffer management is done by an allocator policy. - template - class decoder_base_t : public i_decoder +// Helper base class for decoders that know the amount of data to read +// in advance at any moment. Knowing the amount in advance is a property +// of the protocol used. 0MQ framing protocol is based size-prefixed +// paradigm, which qualifies it to be parsed by this class. +// On the other hand, XML-based transports (like XMPP or SOAP) don't allow +// for knowing the size of data to read in advance and should use different +// decoding algorithms. +// +// This class implements the state machine that parses the incoming buffer. +// Derived class should implement individual state machine actions. +// +// Buffer management is done by an allocator policy. +template +class decoder_base_t : public i_decoder +{ + public: + explicit decoder_base_t (A *allocator_) : + next (NULL), + read_pos (NULL), + to_read (0), + allocator (allocator_) { - public: - - explicit decoder_base_t (A *allocator_) : - next (NULL), - read_pos (NULL), - to_read (0), - allocator(allocator_) - { - buf = allocator->allocate (); - } + buf = allocator->allocate (); + } - // The destructor doesn't have to be virtual. It is made virtual - // just to keep ICC and code checking tools from complaining. - virtual ~decoder_base_t () - { - allocator->deallocate (); - } - - // Returns a buffer to be filled with binary data. - void get_buffer (unsigned char **data_, std::size_t *size_) - { - buf = allocator->allocate (); - - // If we are expected to read large message, we'll opt for zero- - // copy, i.e. we'll ask caller to fill the data directly to the - // message. Note that subsequent read(s) are non-blocking, thus - // each single read reads at most SO_RCVBUF bytes at once not - // depending on how large is the chunk returned from here. - // As a consequence, large messages being received won't block - // other engines running in the same I/O thread for excessive - // amounts of time. - if (to_read >= allocator->size ()) { - *data_ = read_pos; - *size_ = to_read; - return; - } + // The destructor doesn't have to be virtual. It is made virtual + // just to keep ICC and code checking tools from complaining. + virtual ~decoder_base_t () { allocator->deallocate (); } - *data_ = buf; - *size_ = allocator->size (); + // Returns a buffer to be filled with binary data. + void get_buffer (unsigned char **data_, std::size_t *size_) + { + buf = allocator->allocate (); + + // If we are expected to read large message, we'll opt for zero- + // copy, i.e. we'll ask caller to fill the data directly to the + // message. Note that subsequent read(s) are non-blocking, thus + // each single read reads at most SO_RCVBUF bytes at once not + // depending on how large is the chunk returned from here. + // As a consequence, large messages being received won't block + // other engines running in the same I/O thread for excessive + // amounts of time. + if (to_read >= allocator->size ()) { + *data_ = read_pos; + *size_ = to_read; + return; } - // Processes the data in the buffer previously allocated using - // get_buffer function. size_ argument specifies number of bytes - // actually filled into the buffer. Function returns 1 when the - // whole message was decoded or 0 when more data is required. - // On error, -1 is returned and errno set accordingly. - // Number of bytes processed is returned in bytes_used_. - int decode (const unsigned char *data_, std::size_t size_, - std::size_t &bytes_used_) - { - bytes_used_ = 0; - - // In case of zero-copy simply adjust the pointers, no copying - // is required. Also, run the state machine in case all the data - // were processed. - if (data_ == read_pos) { - zmq_assert (size_ <= to_read); - read_pos += size_; - to_read -= size_; - bytes_used_ = size_; - - while (!to_read) { - const int rc = - (static_cast (this)->*next) (data_ + bytes_used_); - if (rc != 0) - return rc; - } - return 0; - } - - while (bytes_used_ < size_) { - // Copy the data from buffer to the message. - const size_t to_copy = std::min (to_read, size_ - bytes_used_); - // Only copy when destination address is different from the - // current address in the buffer. - if (read_pos != data_ + bytes_used_) { - memcpy (read_pos, data_ + bytes_used_, to_copy); - } - - read_pos += to_copy; - to_read -= to_copy; - bytes_used_ += to_copy; - // Try to get more space in the message to fill in. - // If none is available, return. - while (to_read == 0) { - // pass current address in the buffer - const int rc = - (static_cast (this)->*next) (data_ + bytes_used_); - if (rc != 0) - return rc; - } + *data_ = buf; + *size_ = allocator->size (); + } + + // Processes the data in the buffer previously allocated using + // get_buffer function. size_ argument specifies number of bytes + // actually filled into the buffer. Function returns 1 when the + // whole message was decoded or 0 when more data is required. + // On error, -1 is returned and errno set accordingly. + // Number of bytes processed is returned in bytes_used_. + int decode (const unsigned char *data_, + std::size_t size_, + std::size_t &bytes_used_) + { + bytes_used_ = 0; + + // In case of zero-copy simply adjust the pointers, no copying + // is required. Also, run the state machine in case all the data + // were processed. + if (data_ == read_pos) { + zmq_assert (size_ <= to_read); + read_pos += size_; + to_read -= size_; + bytes_used_ = size_; + + while (!to_read) { + const int rc = + (static_cast (this)->*next) (data_ + bytes_used_); + if (rc != 0) + return rc; } - return 0; } - virtual void resize_buffer (std::size_t new_size) - { - allocator->resize (new_size); - } - - protected: - - // Prototype of state machine action. Action should return false if - // it is unable to push the data to the system. - typedef int (T:: *step_t) (unsigned char const *); + while (bytes_used_ < size_) { + // Copy the data from buffer to the message. + const size_t to_copy = std::min (to_read, size_ - bytes_used_); + // Only copy when destination address is different from the + // current address in the buffer. + if (read_pos != data_ + bytes_used_) { + memcpy (read_pos, data_ + bytes_used_, to_copy); + } - // This function should be called from derived class to read data - // from the buffer and schedule next state machine action. - void next_step (void *read_pos_, std::size_t to_read_, step_t next_) - { - read_pos = static_cast (read_pos_); - to_read = to_read_; - next = next_; + read_pos += to_copy; + to_read -= to_copy; + bytes_used_ += to_copy; + // Try to get more space in the message to fill in. + // If none is available, return. + while (to_read == 0) { + // pass current address in the buffer + const int rc = + (static_cast (this)->*next) (data_ + bytes_used_); + if (rc != 0) + return rc; + } } - private: + return 0; + } - // Next step. If set to NULL, it means that associated data stream - // is dead. Note that there can be still data in the process in such - // case. - step_t next; - - // Where to store the read data. - unsigned char *read_pos; - - // How much data to read before taking next step. - std::size_t to_read; + virtual void resize_buffer (std::size_t new_size) + { + allocator->resize (new_size); + } - // The duffer for data to decode. - A *allocator; - unsigned char *buf; + protected: + // Prototype of state machine action. Action should return false if + // it is unable to push the data to the system. + typedef int (T::*step_t) (unsigned char const *); - decoder_base_t (const decoder_base_t &); - const decoder_base_t &operator = (const decoder_base_t &); - }; + // This function should be called from derived class to read data + // from the buffer and schedule next state machine action. + void next_step (void *read_pos_, std::size_t to_read_, step_t next_) + { + read_pos = static_cast (read_pos_); + to_read = to_read_; + next = next_; + } + + private: + // Next step. If set to NULL, it means that associated data stream + // is dead. Note that there can be still data in the process in such + // case. + step_t next; + + // Where to store the read data. + unsigned char *read_pos; + + // How much data to read before taking next step. + std::size_t to_read; + + // The duffer for data to decode. + A *allocator; + unsigned char *buf; + + decoder_base_t (const decoder_base_t &); + const decoder_base_t &operator= (const decoder_base_t &); +}; } #endif diff --git a/src/decoder_allocators.cpp b/src/decoder_allocators.cpp index c49e2696e1..78eac47d85 100644 --- a/src/decoder_allocators.cpp +++ b/src/decoder_allocators.cpp @@ -34,34 +34,39 @@ #include "msg.hpp" -zmq::shared_message_memory_allocator::shared_message_memory_allocator (std::size_t bufsize_) : - buf(NULL), - bufsize(0), - max_size(bufsize_), - msg_content(NULL), - maxCounters (static_cast (std::ceil (static_cast (max_size) / static_cast (msg_t::max_vsm_size)))) +zmq::shared_message_memory_allocator::shared_message_memory_allocator ( + std::size_t bufsize_) : + buf (NULL), + bufsize (0), + max_size (bufsize_), + msg_content (NULL), + maxCounters (static_cast ( + std::ceil (static_cast (max_size) + / static_cast (msg_t::max_vsm_size)))) { } -zmq::shared_message_memory_allocator::shared_message_memory_allocator (std::size_t bufsize_, std::size_t maxMessages) : - buf(NULL), - bufsize(0), - max_size(bufsize_), - msg_content(NULL), - maxCounters(maxMessages) +zmq::shared_message_memory_allocator::shared_message_memory_allocator ( + std::size_t bufsize_, std::size_t maxMessages) : + buf (NULL), + bufsize (0), + max_size (bufsize_), + msg_content (NULL), + maxCounters (maxMessages) { } zmq::shared_message_memory_allocator::~shared_message_memory_allocator () { - deallocate(); + deallocate (); } -unsigned char* zmq::shared_message_memory_allocator::allocate () +unsigned char *zmq::shared_message_memory_allocator::allocate () { if (buf) { // release reference count to couple lifetime to messages - zmq::atomic_counter_t* c = reinterpret_cast(buf); + zmq::atomic_counter_t *c = + reinterpret_cast (buf); // if refcnt drops to 0, there are no message using the buffer // because either all messages have been closed or only vsm-messages @@ -77,36 +82,38 @@ unsigned char* zmq::shared_message_memory_allocator::allocate () if (!buf) { // allocate memory for reference counters together with reception buffer std::size_t const allocationsize = - max_size + sizeof (zmq::atomic_counter_t) + - maxCounters * sizeof (zmq::msg_t::content_t); + max_size + sizeof (zmq::atomic_counter_t) + + maxCounters * sizeof (zmq::msg_t::content_t); - buf = static_cast (std::malloc (allocationsize)); + buf = static_cast (std::malloc (allocationsize)); alloc_assert (buf); new (buf) atomic_counter_t (1); } else { // release reference count to couple lifetime to messages - zmq::atomic_counter_t *c = reinterpret_cast (buf); + zmq::atomic_counter_t *c = + reinterpret_cast (buf); c->set (1); } bufsize = max_size; - msg_content = reinterpret_cast (buf + sizeof (atomic_counter_t) + max_size); + msg_content = reinterpret_cast ( + buf + sizeof (atomic_counter_t) + max_size); return buf + sizeof (zmq::atomic_counter_t); } void zmq::shared_message_memory_allocator::deallocate () { - zmq::atomic_counter_t* c = reinterpret_cast(buf); - if (buf && !c->sub(1)) { - std::free(buf); + zmq::atomic_counter_t *c = reinterpret_cast (buf); + if (buf && !c->sub (1)) { + std::free (buf); } - release(); + release (); } -unsigned char* zmq::shared_message_memory_allocator::release () +unsigned char *zmq::shared_message_memory_allocator::release () { - unsigned char* b = buf; + unsigned char *b = buf; buf = NULL; bufsize = 0; msg_content = NULL; @@ -116,14 +123,14 @@ unsigned char* zmq::shared_message_memory_allocator::release () void zmq::shared_message_memory_allocator::inc_ref () { - (reinterpret_cast (buf))->add (1); + (reinterpret_cast (buf))->add (1); } -void zmq::shared_message_memory_allocator::call_dec_ref(void*, void* hint) +void zmq::shared_message_memory_allocator::call_dec_ref (void *, void *hint) { zmq_assert (hint); - unsigned char* buf = static_cast (hint); - zmq::atomic_counter_t* c = reinterpret_cast (buf); + unsigned char *buf = static_cast (hint); + zmq::atomic_counter_t *c = reinterpret_cast (buf); if (!c->sub (1)) { c->~atomic_counter_t (); @@ -138,7 +145,7 @@ std::size_t zmq::shared_message_memory_allocator::size () const return bufsize; } -unsigned char* zmq::shared_message_memory_allocator::data () +unsigned char *zmq::shared_message_memory_allocator::data () { return buf + sizeof (zmq::atomic_counter_t); } diff --git a/src/decoder_allocators.hpp b/src/decoder_allocators.hpp index 30cfaf1aa5..e760cba6ce 100644 --- a/src/decoder_allocators.hpp +++ b/src/decoder_allocators.hpp @@ -39,117 +39,93 @@ namespace zmq { - // Static buffer policy. - class c_single_allocator - { - public: - explicit c_single_allocator (std::size_t bufsize_) : - bufsize(bufsize_), - buf(static_cast (std::malloc (bufsize))) - { - alloc_assert (buf); - } - - ~c_single_allocator () - { - std::free (buf); - } - - unsigned char* allocate () - { - return buf; - } - - void deallocate () - { - } - - std::size_t size () const - { - return bufsize; - } - - void resize (std::size_t new_size) - { - bufsize = new_size; - } - private: - std::size_t bufsize; - unsigned char* buf; - - c_single_allocator (c_single_allocator const&); - c_single_allocator& operator = (c_single_allocator const&); - }; - - // This allocator allocates a reference counted buffer which is used by v2_decoder_t - // to use zero-copy msg::init_data to create messages with memory from this buffer as - // data storage. - // - // The buffer is allocated with a reference count of 1 to make sure that is is alive while - // decoding messages. Otherwise, it is possible that e.g. the first message increases the count - // from zero to one, gets passed to the user application, processed in the user thread and deleted - // which would then deallocate the buffer. The drawback is that the buffer may be allocated longer - // than necessary because it is only deleted when allocate is called the next time. - class shared_message_memory_allocator +// Static buffer policy. +class c_single_allocator +{ + public: + explicit c_single_allocator (std::size_t bufsize_) : + bufsize (bufsize_), + buf (static_cast (std::malloc (bufsize))) { - public: - explicit shared_message_memory_allocator (std::size_t bufsize_); + alloc_assert (buf); + } + + ~c_single_allocator () { std::free (buf); } + + unsigned char *allocate () { return buf; } + + void deallocate () {} + + std::size_t size () const { return bufsize; } - // Create an allocator for a maximum number of messages - shared_message_memory_allocator (std::size_t bufsize_, std::size_t maxMessages); + void resize (std::size_t new_size) { bufsize = new_size; } - ~shared_message_memory_allocator (); + private: + std::size_t bufsize; + unsigned char *buf; - // Allocate a new buffer - // - // This releases the current buffer to be bound to the lifetime of the messages - // created on this buffer. - unsigned char* allocate (); + c_single_allocator (c_single_allocator const &); + c_single_allocator &operator= (c_single_allocator const &); +}; + +// This allocator allocates a reference counted buffer which is used by v2_decoder_t +// to use zero-copy msg::init_data to create messages with memory from this buffer as +// data storage. +// +// The buffer is allocated with a reference count of 1 to make sure that is is alive while +// decoding messages. Otherwise, it is possible that e.g. the first message increases the count +// from zero to one, gets passed to the user application, processed in the user thread and deleted +// which would then deallocate the buffer. The drawback is that the buffer may be allocated longer +// than necessary because it is only deleted when allocate is called the next time. +class shared_message_memory_allocator +{ + public: + explicit shared_message_memory_allocator (std::size_t bufsize_); + + // Create an allocator for a maximum number of messages + shared_message_memory_allocator (std::size_t bufsize_, + std::size_t maxMessages); + + ~shared_message_memory_allocator (); + + // Allocate a new buffer + // + // This releases the current buffer to be bound to the lifetime of the messages + // created on this buffer. + unsigned char *allocate (); - // force deallocation of buffer. - void deallocate (); + // force deallocation of buffer. + void deallocate (); - // Give up ownership of the buffer. The buffer's lifetime is now coupled to - // the messages constructed on top of it. - unsigned char* release (); + // Give up ownership of the buffer. The buffer's lifetime is now coupled to + // the messages constructed on top of it. + unsigned char *release (); - void inc_ref (); + void inc_ref (); - static void call_dec_ref (void*, void* buffer); + static void call_dec_ref (void *, void *buffer); - std::size_t size () const; + std::size_t size () const; - // Return pointer to the first message data byte. - unsigned char* data (); + // Return pointer to the first message data byte. + unsigned char *data (); - // Return pointer to the first byte of the buffer. - unsigned char* buffer () - { - return buf; - } + // Return pointer to the first byte of the buffer. + unsigned char *buffer () { return buf; } - void resize (std::size_t new_size) - { - bufsize = new_size; - } + void resize (std::size_t new_size) { bufsize = new_size; } - zmq::msg_t::content_t* provide_content () - { - return msg_content; - } + zmq::msg_t::content_t *provide_content () { return msg_content; } - void advance_content () - { - msg_content++; - } + void advance_content () { msg_content++; } - private: - unsigned char* buf; - std::size_t bufsize; - std::size_t max_size; - zmq::msg_t::content_t* msg_content; - std::size_t maxCounters; - }; + private: + unsigned char *buf; + std::size_t bufsize; + std::size_t max_size; + zmq::msg_t::content_t *msg_content; + std::size_t maxCounters; +}; } #endif diff --git a/src/devpoll.cpp b/src/devpoll.cpp index 99c8277708..bbe7ebb6e2 100644 --- a/src/devpoll.cpp +++ b/src/devpoll.cpp @@ -47,7 +47,7 @@ #include "i_poll_events.hpp" zmq::devpoll_t::devpoll_t (const zmq::ctx_t &ctx_) : - ctx(ctx_), + ctx (ctx_), stopping (false) { devpoll_fd = open ("/dev/poll", O_RDWR); @@ -68,24 +68,24 @@ void zmq::devpoll_t::devpoll_ctl (fd_t fd_, short events_) } zmq::devpoll_t::handle_t zmq::devpoll_t::add_fd (fd_t fd_, - i_poll_events *reactor_) + i_poll_events *reactor_) { // If the file descriptor table is too small expand it. fd_table_t::size_type sz = fd_table.size (); if (sz <= (fd_table_t::size_type) fd_) { fd_table.resize (fd_ + 1); while (sz != (fd_table_t::size_type) (fd_ + 1)) { - fd_table [sz].valid = false; + fd_table[sz].valid = false; ++sz; } } - zmq_assert (!fd_table [fd_].valid); + zmq_assert (!fd_table[fd_].valid); - fd_table [fd_].events = 0; - fd_table [fd_].reactor = reactor_; - fd_table [fd_].valid = true; - fd_table [fd_].accepted = false; + fd_table[fd_].events = 0; + fd_table[fd_].reactor = reactor_; + fd_table[fd_].valid = true; + fd_table[fd_].accepted = false; devpoll_ctl (fd_, 0); pending_list.push_back (fd_); @@ -98,10 +98,10 @@ zmq::devpoll_t::handle_t zmq::devpoll_t::add_fd (fd_t fd_, void zmq::devpoll_t::rm_fd (handle_t handle_) { - zmq_assert (fd_table [handle_].valid); + zmq_assert (fd_table[handle_].valid); devpoll_ctl (handle_, POLLREMOVE); - fd_table [handle_].valid = false; + fd_table[handle_].valid = false; // Decrease the load metric of the thread. adjust_load (-1); @@ -110,29 +110,29 @@ void zmq::devpoll_t::rm_fd (handle_t handle_) void zmq::devpoll_t::set_pollin (handle_t handle_) { devpoll_ctl (handle_, POLLREMOVE); - fd_table [handle_].events |= POLLIN; - devpoll_ctl (handle_, fd_table [handle_].events); + fd_table[handle_].events |= POLLIN; + devpoll_ctl (handle_, fd_table[handle_].events); } void zmq::devpoll_t::reset_pollin (handle_t handle_) { devpoll_ctl (handle_, POLLREMOVE); - fd_table [handle_].events &= ~((short) POLLIN); - devpoll_ctl (handle_, fd_table [handle_].events); + fd_table[handle_].events &= ~((short) POLLIN); + devpoll_ctl (handle_, fd_table[handle_].events); } void zmq::devpoll_t::set_pollout (handle_t handle_) { devpoll_ctl (handle_, POLLREMOVE); - fd_table [handle_].events |= POLLOUT; - devpoll_ctl (handle_, fd_table [handle_].events); + fd_table[handle_].events |= POLLOUT; + devpoll_ctl (handle_, fd_table[handle_].events); } void zmq::devpoll_t::reset_pollout (handle_t handle_) { devpoll_ctl (handle_, POLLREMOVE); - fd_table [handle_].events &= ~((short) POLLOUT); - devpoll_ctl (handle_, fd_table [handle_].events); + fd_table[handle_].events &= ~((short) POLLOUT); + devpoll_ctl (handle_, fd_table[handle_].events); } void zmq::devpoll_t::start () @@ -153,12 +153,11 @@ int zmq::devpoll_t::max_fds () void zmq::devpoll_t::loop () { while (!stopping) { - - struct pollfd ev_buf [max_io_events]; + struct pollfd ev_buf[max_io_events]; struct dvpoll poll_req; - for (pending_list_t::size_type i = 0; i < pending_list.size (); i ++) - fd_table [pending_list [i]].accepted = true; + for (pending_list_t::size_type i = 0; i < pending_list.size (); i++) + fd_table[pending_list[i]].accepted = true; pending_list.clear (); // Execute any due timers. @@ -166,7 +165,7 @@ void zmq::devpoll_t::loop () // Wait for events. // On Solaris, we can retrieve no more then (OPEN_MAX - 1) events. - poll_req.dp_fds = &ev_buf [0]; + poll_req.dp_fds = &ev_buf[0]; #if defined ZMQ_HAVE_SOLARIS poll_req.dp_nfds = std::min ((int) max_io_events, OPEN_MAX - 1); #else @@ -178,20 +177,19 @@ void zmq::devpoll_t::loop () continue; errno_assert (n != -1); - for (int i = 0; i < n; i ++) { - - fd_entry_t *fd_ptr = &fd_table [ev_buf [i].fd]; + for (int i = 0; i < n; i++) { + fd_entry_t *fd_ptr = &fd_table[ev_buf[i].fd]; if (!fd_ptr->valid || !fd_ptr->accepted) continue; - if (ev_buf [i].revents & (POLLERR | POLLHUP)) + if (ev_buf[i].revents & (POLLERR | POLLHUP)) fd_ptr->reactor->in_event (); if (!fd_ptr->valid || !fd_ptr->accepted) continue; - if (ev_buf [i].revents & POLLOUT) + if (ev_buf[i].revents & POLLOUT) fd_ptr->reactor->out_event (); if (!fd_ptr->valid || !fd_ptr->accepted) continue; - if (ev_buf [i].revents & POLLIN) + if (ev_buf[i].revents & POLLIN) fd_ptr->reactor->in_event (); } } @@ -199,7 +197,7 @@ void zmq::devpoll_t::loop () void zmq::devpoll_t::worker_routine (void *arg_) { - ((devpoll_t*) arg_)->loop (); + ((devpoll_t *) arg_)->loop (); } #endif diff --git a/src/devpoll.hpp b/src/devpoll.hpp index 3d939b5549..17bd6eeac9 100644 --- a/src/devpoll.hpp +++ b/src/devpoll.hpp @@ -43,75 +43,71 @@ namespace zmq { +struct i_poll_events; - struct i_poll_events; +// Implements socket polling mechanism using the "/dev/poll" interface. - // Implements socket polling mechanism using the "/dev/poll" interface. - - class devpoll_t : public poller_base_t - { - public: - - typedef fd_t handle_t; - - devpoll_t (const ctx_t &ctx_); - ~devpoll_t (); - - // "poller" concept. - handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); - void rm_fd (handle_t handle_); - void set_pollin (handle_t handle_); - void reset_pollin (handle_t handle_); - void set_pollout (handle_t handle_); - void reset_pollout (handle_t handle_); - void start (); - void stop (); +class devpoll_t : public poller_base_t +{ + public: + typedef fd_t handle_t; - static int max_fds (); + devpoll_t (const ctx_t &ctx_); + ~devpoll_t (); - private: + // "poller" concept. + handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); + void rm_fd (handle_t handle_); + void set_pollin (handle_t handle_); + void reset_pollin (handle_t handle_); + void set_pollout (handle_t handle_); + void reset_pollout (handle_t handle_); + void start (); + void stop (); - // Main worker thread routine. - static void worker_routine (void *arg_); + static int max_fds (); - // Main event loop. - void loop (); + private: + // Main worker thread routine. + static void worker_routine (void *arg_); - // Reference to ZMQ context. - const ctx_t &ctx; + // Main event loop. + void loop (); - // File descriptor referring to "/dev/poll" pseudo-device. - fd_t devpoll_fd; + // Reference to ZMQ context. + const ctx_t &ctx; - struct fd_entry_t - { - short events; - zmq::i_poll_events *reactor; - bool valid; - bool accepted; - }; + // File descriptor referring to "/dev/poll" pseudo-device. + fd_t devpoll_fd; - typedef std::vector fd_table_t; - fd_table_t fd_table; + struct fd_entry_t + { + short events; + zmq::i_poll_events *reactor; + bool valid; + bool accepted; + }; - typedef std::vector pending_list_t; - pending_list_t pending_list; + typedef std::vector fd_table_t; + fd_table_t fd_table; - // Pollset manipulation function. - void devpoll_ctl (fd_t fd_, short events_); + typedef std::vector pending_list_t; + pending_list_t pending_list; - // If true, thread is in the process of shutting down. - bool stopping; + // Pollset manipulation function. + void devpoll_ctl (fd_t fd_, short events_); - // Handle of the physical thread doing the I/O work. - thread_t worker; + // If true, thread is in the process of shutting down. + bool stopping; - devpoll_t (const devpoll_t&); - const devpoll_t &operator = (const devpoll_t&); - }; + // Handle of the physical thread doing the I/O work. + thread_t worker; - typedef devpoll_t poller_t; + devpoll_t (const devpoll_t &); + const devpoll_t &operator= (const devpoll_t &); +}; +typedef devpoll_t poller_t; } #endif diff --git a/src/dgram.cpp b/src/dgram.cpp index 2c1d20f779..c63bbe2c24 100644 --- a/src/dgram.cpp +++ b/src/dgram.cpp @@ -53,7 +53,7 @@ zmq::dgram_t::~dgram_t () void zmq::dgram_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_) { - LIBZMQ_UNUSED(subscribe_to_all_); + LIBZMQ_UNUSED (subscribe_to_all_); zmq_assert (pipe_); @@ -107,9 +107,7 @@ int zmq::dgram_t::xsend (msg_t *msg_) // Expect one more message frame. more_out = true; - } - else { - + } else { // dgram messages are two part only, reject part if more is set if (msg_->flags () & msg_t::more) { errno = EINVAL; @@ -173,5 +171,5 @@ bool zmq::dgram_t::xhas_out () const zmq::blob_t &zmq::dgram_t::get_credential () const { - return last_in? last_in->get_credential (): saved_credential; + return last_in ? last_in->get_credential () : saved_credential; } diff --git a/src/dgram.hpp b/src/dgram.hpp index 82980776bf..439c876bd5 100644 --- a/src/dgram.hpp +++ b/src/dgram.hpp @@ -36,46 +36,41 @@ namespace zmq { +class ctx_t; +class msg_t; +class pipe_t; +class io_thread_t; - class ctx_t; - class msg_t; - class pipe_t; - class io_thread_t; - - class dgram_t : - public socket_base_t - { - public: - - dgram_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); - ~dgram_t (); - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsend (zmq::msg_t *msg_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - bool xhas_out (); - const blob_t &get_credential () const; - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - - zmq::pipe_t *pipe; - - zmq::pipe_t *last_in; - - blob_t saved_credential; - - // If true, more outgoing message parts are expected. - bool more_out; - - dgram_t (const dgram_t&); - const dgram_t &operator = (const dgram_t&); - }; - +class dgram_t : public socket_base_t +{ + public: + dgram_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); + ~dgram_t (); + + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsend (zmq::msg_t *msg_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + bool xhas_out (); + const blob_t &get_credential () const; + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + zmq::pipe_t *pipe; + + zmq::pipe_t *last_in; + + blob_t saved_credential; + + // If true, more outgoing message parts are expected. + bool more_out; + + dgram_t (const dgram_t &); + const dgram_t &operator= (const dgram_t &); +}; } #endif diff --git a/src/dish.cpp b/src/dish.cpp index df67ba82ba..c4e51a5854 100644 --- a/src/dish.cpp +++ b/src/dish.cpp @@ -88,7 +88,7 @@ void zmq::dish_t::xhiccuped (pipe_t *pipe_) send_subscriptions (pipe_); } -int zmq::dish_t::xjoin (const char* group_) +int zmq::dish_t::xjoin (const char *group_) { std::string group = std::string (group_); @@ -125,7 +125,7 @@ int zmq::dish_t::xjoin (const char* group_) return rc; } -int zmq::dish_t::xleave (const char* group_) +int zmq::dish_t::xleave (const char *group_) { std::string group = std::string (group_); @@ -134,7 +134,8 @@ int zmq::dish_t::xleave (const char* group_) return -1; } - subscriptions_t::iterator it = std::find (subscriptions.begin (), subscriptions.end (), group); + subscriptions_t::iterator it = + std::find (subscriptions.begin (), subscriptions.end (), group); if (it == subscriptions.end ()) { errno = EINVAL; @@ -186,7 +187,6 @@ int zmq::dish_t::xrecv (msg_t *msg_) } while (true) { - // Get a message using fair queueing algorithm. int rc = fq.recv (msg_); @@ -196,7 +196,8 @@ int zmq::dish_t::xrecv (msg_t *msg_) return -1; // Filtering non matching messages - subscriptions_t::iterator it = subscriptions.find (std::string(msg_->group ())); + subscriptions_t::iterator it = + subscriptions.find (std::string (msg_->group ())); if (it != subscriptions.end ()) return 0; } @@ -221,7 +222,8 @@ bool zmq::dish_t::xhas_in () } // Filtering non matching messages - subscriptions_t::iterator it = subscriptions.find (std::string(message.group ())); + subscriptions_t::iterator it = + subscriptions.find (std::string (message.group ())); if (it != subscriptions.end ()) { has_message = true; return true; @@ -236,12 +238,13 @@ const zmq::blob_t &zmq::dish_t::get_credential () const void zmq::dish_t::send_subscriptions (pipe_t *pipe_) { - for (subscriptions_t::iterator it = subscriptions.begin (); it != subscriptions.end (); ++it) { + for (subscriptions_t::iterator it = subscriptions.begin (); + it != subscriptions.end (); ++it) { msg_t msg; int rc = msg.init_join (); errno_assert (rc == 0); - rc = msg.set_group (it->c_str()); + rc = msg.set_group (it->c_str ()); errno_assert (rc == 0); // Send it to the pipe. @@ -252,9 +255,11 @@ void zmq::dish_t::send_subscriptions (pipe_t *pipe_) pipe_->flush (); } -zmq::dish_session_t::dish_session_t (io_thread_t *io_thread_, bool connect_, - socket_base_t *socket_, const options_t &options_, - address_t *addr_) : +zmq::dish_session_t::dish_session_t (io_thread_t *io_thread_, + bool connect_, + socket_base_t *socket_, + const options_t &options_, + address_t *addr_) : session_base_t (io_thread_, connect_, socket_, options_, addr_), state (group) { @@ -267,12 +272,12 @@ zmq::dish_session_t::~dish_session_t () int zmq::dish_session_t::push_msg (msg_t *msg_) { if (state == group) { - if ((msg_->flags() & msg_t::more) != msg_t::more) { + if ((msg_->flags () & msg_t::more) != msg_t::more) { errno = EFAULT; return -1; } - if (msg_->size() > ZMQ_GROUP_MAX_LENGTH) { + if (msg_->size () > ZMQ_GROUP_MAX_LENGTH) { errno = EFAULT; return -1; } @@ -283,23 +288,22 @@ int zmq::dish_session_t::push_msg (msg_t *msg_) int rc = msg_->init (); errno_assert (rc == 0); return 0; - } - else { - const char *group_setting = msg_->group(); + } else { + const char *group_setting = msg_->group (); int rc; - if(group_setting[0] != 0) - goto has_group; + if (group_setting[0] != 0) + goto has_group; // Set the message group - rc = msg_->set_group ((char*)group_msg.data (), group_msg. size()); + rc = msg_->set_group ((char *) group_msg.data (), group_msg.size ()); errno_assert (rc == 0); // We set the group, so we don't need the group_msg anymore rc = group_msg.close (); errno_assert (rc == 0); -has_group: + has_group: // Thread safe socket doesn't support multipart messages - if ((msg_->flags() & msg_t::more) == msg_t::more) { + if ((msg_->flags () & msg_t::more) == msg_t::more) { errno = EFAULT; return -1; } @@ -331,19 +335,18 @@ int zmq::dish_session_t::pull_msg (msg_t *msg_) if (msg_->is_join ()) { rc = command.init_size (group_length + 5); - errno_assert(rc == 0); + errno_assert (rc == 0); offset = 5; memcpy (command.data (), "\4JOIN", 5); - } - else { + } else { rc = command.init_size (group_length + 6); - errno_assert(rc == 0); + errno_assert (rc == 0); offset = 6; memcpy (command.data (), "\5LEAVE", 6); } command.set_flags (msg_t::command); - char* command_data = (char*)command.data (); + char *command_data = (char *) command.data (); // Copy the group memcpy (command_data + offset, msg_->group (), group_length); diff --git a/src/dish.hpp b/src/dish.hpp index 2dd0d2f143..fc6444cff4 100644 --- a/src/dish.hpp +++ b/src/dish.hpp @@ -41,85 +41,81 @@ namespace zmq { +class ctx_t; +class pipe_t; +class io_thread_t; - class ctx_t; - class pipe_t; - class io_thread_t; - - class dish_t : - public socket_base_t - { - public: - - dish_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~dish_t (); - - protected: - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsend (zmq::msg_t *msg_); - bool xhas_out (); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - const blob_t &get_credential () const; - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xhiccuped (pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - int xjoin (const char *group_); - int xleave (const char *group_); - private: - - // Send subscriptions to a pipe - void send_subscriptions (pipe_t *pipe_); - - // Fair queueing object for inbound pipes. - fq_t fq; - - // Object for distributing the subscriptions upstream. - dist_t dist; - - // The repository of subscriptions. - typedef std::set subscriptions_t; - subscriptions_t subscriptions; - - // If true, 'message' contains a matching message to return on the - // next recv call. - bool has_message; - msg_t message; - - dish_t (const dish_t&); - const dish_t &operator = (const dish_t&); - }; - - class dish_session_t : public session_base_t +class dish_t : public socket_base_t +{ + public: + dish_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~dish_t (); + + protected: + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsend (zmq::msg_t *msg_); + bool xhas_out (); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + const blob_t &get_credential () const; + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xhiccuped (pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + int xjoin (const char *group_); + int xleave (const char *group_); + + private: + // Send subscriptions to a pipe + void send_subscriptions (pipe_t *pipe_); + + // Fair queueing object for inbound pipes. + fq_t fq; + + // Object for distributing the subscriptions upstream. + dist_t dist; + + // The repository of subscriptions. + typedef std::set subscriptions_t; + subscriptions_t subscriptions; + + // If true, 'message' contains a matching message to return on the + // next recv call. + bool has_message; + msg_t message; + + dish_t (const dish_t &); + const dish_t &operator= (const dish_t &); +}; + +class dish_session_t : public session_base_t +{ + public: + dish_session_t (zmq::io_thread_t *io_thread_, + bool connect_, + zmq::socket_base_t *socket_, + const options_t &options_, + address_t *addr_); + ~dish_session_t (); + + // Overrides of the functions from session_base_t. + int push_msg (msg_t *msg_); + int pull_msg (msg_t *msg_); + void reset (); + + private: + enum { - public: - - dish_session_t (zmq::io_thread_t *io_thread_, bool connect_, - zmq::socket_base_t *socket_, const options_t &options_, - address_t *addr_); - ~dish_session_t (); - - // Overrides of the functions from session_base_t. - int push_msg (msg_t *msg_); - int pull_msg (msg_t *msg_); - void reset (); - - private: - - enum { - group, - body - } state; - - msg_t group_msg; + group, + body + } state; - dish_session_t (const dish_session_t&); - const dish_session_t &operator = (const dish_session_t&); - }; + msg_t group_msg; + dish_session_t (const dish_session_t &); + const dish_session_t &operator= (const dish_session_t &); +}; } #endif diff --git a/src/dist.cpp b/src/dist.cpp index 8b306fa68c..a8daf2aad7 100644 --- a/src/dist.cpp +++ b/src/dist.cpp @@ -34,11 +34,7 @@ #include "msg.hpp" #include "likely.hpp" -zmq::dist_t::dist_t () : - matching (0), - active (0), - eligible (0), - more (false) +zmq::dist_t::dist_t () : matching (0), active (0), eligible (0), more (false) { } @@ -56,8 +52,7 @@ void zmq::dist_t::attach (pipe_t *pipe_) pipes.push_back (pipe_); pipes.swap (eligible, pipes.size () - 1); eligible++; - } - else { + } else { pipes.push_back (pipe_); pipes.swap (active, pipes.size () - 1); active++; @@ -85,14 +80,14 @@ void zmq::dist_t::reverse_match () pipes_t::size_type prev_matching = matching; // Reset matching to 0 - unmatch(); + unmatch (); // Mark all matching pipes as not matching and vice-versa. // To do this, push all pipes that are eligible but not // matched - i.e. between "matching" and "eligible" - // to the beginning of the queue. for (pipes_t::size_type i = prev_matching; i < eligible; ++i) { - pipes.swap(i, matching++); + pipes.swap (i, matching++); } } @@ -173,9 +168,9 @@ void zmq::dist_t::distribute (msg_t *msg_) if (msg_->is_vsm ()) { for (pipes_t::size_type i = 0; i < matching; ++i) - if(!write (pipes [i], msg_)) + if (!write (pipes[i], msg_)) --i; // Retry last write because index will have been swapped - int rc = msg_->close(); + int rc = msg_->close (); errno_assert (rc == 0); rc = msg_->init (); errno_assert (rc == 0); @@ -189,7 +184,7 @@ void zmq::dist_t::distribute (msg_t *msg_) // Push copy of the message to each matching pipe. int failed = 0; for (pipes_t::size_type i = 0; i < matching; ++i) - if (!write (pipes [i], msg_)) { + if (!write (pipes[i], msg_)) { ++failed; --i; // Retry last write because index will have been swapped } @@ -226,10 +221,8 @@ bool zmq::dist_t::write (pipe_t *pipe_, msg_t *msg_) bool zmq::dist_t::check_hwm () { for (pipes_t::size_type i = 0; i < matching; ++i) - if (!pipes [i]->check_hwm ()) + if (!pipes[i]->check_hwm ()) return false; return true; } - - diff --git a/src/dist.hpp b/src/dist.hpp index 9500d87717..4f171eccb7 100644 --- a/src/dist.hpp +++ b/src/dist.hpp @@ -37,84 +37,80 @@ namespace zmq { +class pipe_t; +class msg_t; - class pipe_t; - class msg_t; - - // Class manages a set of outbound pipes. It sends each messages to - // each of them. - class dist_t - { - public: - - dist_t (); - ~dist_t (); - - // Adds the pipe to the distributor object. - void attach (zmq::pipe_t *pipe_); - - // Activates pipe that have previously reached high watermark. - void activated (zmq::pipe_t *pipe_); +// Class manages a set of outbound pipes. It sends each messages to +// each of them. +class dist_t +{ + public: + dist_t (); + ~dist_t (); - // Mark the pipe as matching. Subsequent call to send_to_matching - // will send message also to this pipe. - void match (zmq::pipe_t *pipe_); + // Adds the pipe to the distributor object. + void attach (zmq::pipe_t *pipe_); - // Marks all pipes that are not matched as matched and vice-versa. - void reverse_match(); + // Activates pipe that have previously reached high watermark. + void activated (zmq::pipe_t *pipe_); - // Mark all pipes as non-matching. - void unmatch (); + // Mark the pipe as matching. Subsequent call to send_to_matching + // will send message also to this pipe. + void match (zmq::pipe_t *pipe_); - // Removes the pipe from the distributor object. - void pipe_terminated (zmq::pipe_t *pipe_); + // Marks all pipes that are not matched as matched and vice-versa. + void reverse_match (); - // Send the message to the matching outbound pipes. - int send_to_matching (zmq::msg_t *msg_); + // Mark all pipes as non-matching. + void unmatch (); - // Send the message to all the outbound pipes. - int send_to_all (zmq::msg_t *msg_); + // Removes the pipe from the distributor object. + void pipe_terminated (zmq::pipe_t *pipe_); - bool has_out (); + // Send the message to the matching outbound pipes. + int send_to_matching (zmq::msg_t *msg_); - // check HWM of all pipes matching - bool check_hwm (); + // Send the message to all the outbound pipes. + int send_to_all (zmq::msg_t *msg_); - private: + bool has_out (); - // Write the message to the pipe. Make the pipe inactive if writing - // fails. In such a case false is returned. - bool write (zmq::pipe_t *pipe_, zmq::msg_t *msg_); + // check HWM of all pipes matching + bool check_hwm (); - // Put the message to all active pipes. - void distribute (zmq::msg_t *msg_); + private: + // Write the message to the pipe. Make the pipe inactive if writing + // fails. In such a case false is returned. + bool write (zmq::pipe_t *pipe_, zmq::msg_t *msg_); - // List of outbound pipes. - typedef array_t pipes_t; - pipes_t pipes; + // Put the message to all active pipes. + void distribute (zmq::msg_t *msg_); - // Number of all the pipes to send the next message to. - pipes_t::size_type matching; + // List of outbound pipes. + typedef array_t pipes_t; + pipes_t pipes; - // Number of active pipes. All the active pipes are located at the - // beginning of the pipes array. These are the pipes the messages - // can be sent to at the moment. - pipes_t::size_type active; + // Number of all the pipes to send the next message to. + pipes_t::size_type matching; - // Number of pipes eligible for sending messages to. This includes all - // the active pipes plus all the pipes that we can in theory send - // messages to (the HWM is not yet reached), but sending a message - // to them would result in partial message being delivered, ie. message - // with initial parts missing. - pipes_t::size_type eligible; + // Number of active pipes. All the active pipes are located at the + // beginning of the pipes array. These are the pipes the messages + // can be sent to at the moment. + pipes_t::size_type active; - // True if last we are in the middle of a multipart message. - bool more; + // Number of pipes eligible for sending messages to. This includes all + // the active pipes plus all the pipes that we can in theory send + // messages to (the HWM is not yet reached), but sending a message + // to them would result in partial message being delivered, ie. message + // with initial parts missing. + pipes_t::size_type eligible; - dist_t (const dist_t&); - const dist_t &operator = (const dist_t&); - }; + // True if last we are in the middle of a multipart message. + bool more; + dist_t (const dist_t &); + const dist_t &operator= (const dist_t &); +}; } #endif diff --git a/src/encoder.hpp b/src/encoder.hpp index 66a7adaa1d..be7e29c445 100644 --- a/src/encoder.hpp +++ b/src/encoder.hpp @@ -47,143 +47,134 @@ namespace zmq { +// Helper base class for encoders. It implements the state machine that +// fills the outgoing buffer. Derived classes should implement individual +// state machine actions. - // Helper base class for encoders. It implements the state machine that - // fills the outgoing buffer. Derived classes should implement individual - // state machine actions. - - template class encoder_base_t : public i_encoder +template class encoder_base_t : public i_encoder +{ + public: + inline encoder_base_t (size_t bufsize_) : + write_pos (0), + to_write (0), + next (NULL), + new_msg_flag (false), + bufsize (bufsize_), + in_progress (NULL) { - public: - - inline encoder_base_t (size_t bufsize_) : - write_pos(0), - to_write(0), - next(NULL), - new_msg_flag(false), - bufsize (bufsize_), - in_progress (NULL) - { - buf = (unsigned char*) malloc (bufsize_); - alloc_assert (buf); - } - - // The destructor doesn't have to be virtual. It is made virtual - // just to keep ICC and code checking tools from complaining. - inline virtual ~encoder_base_t () - { - free (buf); - } - - // The function returns a batch of binary data. The data - // are filled to a supplied buffer. If no buffer is supplied (data_ - // points to NULL) decoder object will provide buffer of its own. - inline size_t encode (unsigned char **data_, size_t size_) - { - unsigned char *buffer = !*data_ ? buf : *data_; - size_t buffersize = !*data_ ? bufsize : size_; - - if (in_progress == NULL) - return 0; - - size_t pos = 0; - while (pos < buffersize) { - - // If there are no more data to return, run the state machine. - // If there are still no data, return what we already have - // in the buffer. - if (!to_write) { - if (new_msg_flag) { - int rc = in_progress->close (); - errno_assert (rc == 0); - rc = in_progress->init (); - errno_assert (rc == 0); - in_progress = NULL; - break; - } - (static_cast (this)->*next) (); - } - - // If there are no data in the buffer yet and we are able to - // fill whole buffer in a single go, let's use zero-copy. - // There's no disadvantage to it as we cannot stuck multiple - // messages into the buffer anyway. Note that subsequent - // write(s) are non-blocking, thus each single write writes - // at most SO_SNDBUF bytes at once not depending on how large - // is the chunk returned from here. - // As a consequence, large messages being sent won't block - // other engines running in the same I/O thread for excessive - // amounts of time. - if (!pos && !*data_ && to_write >= buffersize) { - *data_ = write_pos; - pos = to_write; - write_pos = NULL; - to_write = 0; - return pos; + buf = (unsigned char *) malloc (bufsize_); + alloc_assert (buf); + } + + // The destructor doesn't have to be virtual. It is made virtual + // just to keep ICC and code checking tools from complaining. + inline virtual ~encoder_base_t () { free (buf); } + + // The function returns a batch of binary data. The data + // are filled to a supplied buffer. If no buffer is supplied (data_ + // points to NULL) decoder object will provide buffer of its own. + inline size_t encode (unsigned char **data_, size_t size_) + { + unsigned char *buffer = !*data_ ? buf : *data_; + size_t buffersize = !*data_ ? bufsize : size_; + + if (in_progress == NULL) + return 0; + + size_t pos = 0; + while (pos < buffersize) { + // If there are no more data to return, run the state machine. + // If there are still no data, return what we already have + // in the buffer. + if (!to_write) { + if (new_msg_flag) { + int rc = in_progress->close (); + errno_assert (rc == 0); + rc = in_progress->init (); + errno_assert (rc == 0); + in_progress = NULL; + break; } - - // Copy data to the buffer. If the buffer is full, return. - size_t to_copy = std::min (to_write, buffersize - pos); - memcpy (buffer + pos, write_pos, to_copy); - pos += to_copy; - write_pos += to_copy; - to_write -= to_copy; + (static_cast (this)->*next) (); } - *data_ = buffer; - return pos; - } - - void load_msg (msg_t *msg_) - { - zmq_assert (in_progress == NULL); - in_progress = msg_; - (static_cast (this)->*next) (); - } - - protected: - - // Prototype of state machine action. - typedef void (T::*step_t) (); + // If there are no data in the buffer yet and we are able to + // fill whole buffer in a single go, let's use zero-copy. + // There's no disadvantage to it as we cannot stuck multiple + // messages into the buffer anyway. Note that subsequent + // write(s) are non-blocking, thus each single write writes + // at most SO_SNDBUF bytes at once not depending on how large + // is the chunk returned from here. + // As a consequence, large messages being sent won't block + // other engines running in the same I/O thread for excessive + // amounts of time. + if (!pos && !*data_ && to_write >= buffersize) { + *data_ = write_pos; + pos = to_write; + write_pos = NULL; + to_write = 0; + return pos; + } - // This function should be called from derived class to write the data - // to the buffer and schedule next state machine action. - inline void next_step (void *write_pos_, size_t to_write_, - step_t next_, bool new_msg_flag_) - { - write_pos = (unsigned char*) write_pos_; - to_write = to_write_; - next = next_; - new_msg_flag = new_msg_flag_; + // Copy data to the buffer. If the buffer is full, return. + size_t to_copy = std::min (to_write, buffersize - pos); + memcpy (buffer + pos, write_pos, to_copy); + pos += to_copy; + write_pos += to_copy; + to_write -= to_copy; } - private: - - // Where to get the data to write from. - unsigned char *write_pos; + *data_ = buffer; + return pos; + } - // How much data to write before next step should be executed. - size_t to_write; + void load_msg (msg_t *msg_) + { + zmq_assert (in_progress == NULL); + in_progress = msg_; + (static_cast (this)->*next) (); + } + + protected: + // Prototype of state machine action. + typedef void (T::*step_t) (); + + // This function should be called from derived class to write the data + // to the buffer and schedule next state machine action. + inline void next_step (void *write_pos_, + size_t to_write_, + step_t next_, + bool new_msg_flag_) + { + write_pos = (unsigned char *) write_pos_; + to_write = to_write_; + next = next_; + new_msg_flag = new_msg_flag_; + } - // Next step. If set to NULL, it means that associated data stream - // is dead. - step_t next; + private: + // Where to get the data to write from. + unsigned char *write_pos; - bool new_msg_flag; + // How much data to write before next step should be executed. + size_t to_write; - // The buffer for encoded data. - size_t bufsize; - unsigned char *buf; + // Next step. If set to NULL, it means that associated data stream + // is dead. + step_t next; - encoder_base_t (const encoder_base_t&); - void operator = (const encoder_base_t&); + bool new_msg_flag; - protected: + // The buffer for encoded data. + size_t bufsize; + unsigned char *buf; - msg_t *in_progress; + encoder_base_t (const encoder_base_t &); + void operator= (const encoder_base_t &); - }; + protected: + msg_t *in_progress; +}; } #endif - diff --git a/src/epoll.cpp b/src/epoll.cpp index be7ad61d83..235ab7802d 100644 --- a/src/epoll.cpp +++ b/src/epoll.cpp @@ -44,9 +44,7 @@ #include "config.hpp" #include "i_poll_events.hpp" -zmq::epoll_t::epoll_t (const zmq::ctx_t &ctx_) : - ctx(ctx_), - stopping (false) +zmq::epoll_t::epoll_t (const zmq::ctx_t &ctx_) : ctx (ctx_), stopping (false) { #ifdef ZMQ_USE_EPOLL_CLOEXEC // Setting this option result in sane behaviour when exec() functions @@ -65,8 +63,9 @@ zmq::epoll_t::~epoll_t () worker.stop (); close (epoll_fd); - for (retired_t::iterator it = retired.begin (); it != retired.end (); ++it) { - LIBZMQ_DELETE(*it); + for (retired_t::iterator it = retired.begin (); it != retired.end (); + ++it) { + LIBZMQ_DELETE (*it); } } @@ -95,7 +94,7 @@ zmq::epoll_t::handle_t zmq::epoll_t::add_fd (fd_t fd_, i_poll_events *events_) void zmq::epoll_t::rm_fd (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; int rc = epoll_ctl (epoll_fd, EPOLL_CTL_DEL, pe->fd, &pe->ev); errno_assert (rc != -1); pe->fd = retired_fd; @@ -109,7 +108,7 @@ void zmq::epoll_t::rm_fd (handle_t handle_) void zmq::epoll_t::set_pollin (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; pe->ev.events |= EPOLLIN; int rc = epoll_ctl (epoll_fd, EPOLL_CTL_MOD, pe->fd, &pe->ev); errno_assert (rc != -1); @@ -117,7 +116,7 @@ void zmq::epoll_t::set_pollin (handle_t handle_) void zmq::epoll_t::reset_pollin (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; pe->ev.events &= ~((short) EPOLLIN); int rc = epoll_ctl (epoll_fd, EPOLL_CTL_MOD, pe->fd, &pe->ev); errno_assert (rc != -1); @@ -125,7 +124,7 @@ void zmq::epoll_t::reset_pollin (handle_t handle_) void zmq::epoll_t::set_pollout (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; pe->ev.events |= EPOLLOUT; int rc = epoll_ctl (epoll_fd, EPOLL_CTL_MOD, pe->fd, &pe->ev); errno_assert (rc != -1); @@ -133,7 +132,7 @@ void zmq::epoll_t::set_pollout (handle_t handle_) void zmq::epoll_t::reset_pollout (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; pe->ev.events &= ~((short) EPOLLOUT); int rc = epoll_ctl (epoll_fd, EPOLL_CTL_MOD, pe->fd, &pe->ev); errno_assert (rc != -1); @@ -156,42 +155,42 @@ int zmq::epoll_t::max_fds () void zmq::epoll_t::loop () { - epoll_event ev_buf [max_io_events]; + epoll_event ev_buf[max_io_events]; while (!stopping) { - // Execute any due timers. int timeout = (int) execute_timers (); // Wait for events. - int n = epoll_wait (epoll_fd, &ev_buf [0], max_io_events, - timeout ? timeout : -1); + int n = epoll_wait (epoll_fd, &ev_buf[0], max_io_events, + timeout ? timeout : -1); if (n == -1) { errno_assert (errno == EINTR); continue; } - for (int i = 0; i < n; i ++) { - poll_entry_t *pe = ((poll_entry_t*) ev_buf [i].data.ptr); + for (int i = 0; i < n; i++) { + poll_entry_t *pe = ((poll_entry_t *) ev_buf[i].data.ptr); if (pe->fd == retired_fd) continue; - if (ev_buf [i].events & (EPOLLERR | EPOLLHUP)) + if (ev_buf[i].events & (EPOLLERR | EPOLLHUP)) pe->events->in_event (); if (pe->fd == retired_fd) - continue; - if (ev_buf [i].events & EPOLLOUT) + continue; + if (ev_buf[i].events & EPOLLOUT) pe->events->out_event (); if (pe->fd == retired_fd) continue; - if (ev_buf [i].events & EPOLLIN) + if (ev_buf[i].events & EPOLLIN) pe->events->in_event (); } // Destroy retired event sources. retired_sync.lock (); - for (retired_t::iterator it = retired.begin (); it != retired.end (); ++it) { - LIBZMQ_DELETE(*it); + for (retired_t::iterator it = retired.begin (); it != retired.end (); + ++it) { + LIBZMQ_DELETE (*it); } retired.clear (); retired_sync.unlock (); @@ -200,7 +199,7 @@ void zmq::epoll_t::loop () void zmq::epoll_t::worker_routine (void *arg_) { - ((epoll_t*) arg_)->loop (); + ((epoll_t *) arg_)->loop (); } #endif diff --git a/src/epoll.hpp b/src/epoll.hpp index e6c08c9283..f5c2936988 100644 --- a/src/epoll.hpp +++ b/src/epoll.hpp @@ -45,73 +45,69 @@ namespace zmq { +struct i_poll_events; - struct i_poll_events; +// This class implements socket polling mechanism using the Linux-specific +// epoll mechanism. - // This class implements socket polling mechanism using the Linux-specific - // epoll mechanism. - - class epoll_t : public poller_base_t - { - public: - - typedef void* handle_t; - - epoll_t (const ctx_t &ctx_); - ~epoll_t (); - - // "poller" concept. - handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); - void rm_fd (handle_t handle_); - void set_pollin (handle_t handle_); - void reset_pollin (handle_t handle_); - void set_pollout (handle_t handle_); - void reset_pollout (handle_t handle_); - void start (); - void stop (); +class epoll_t : public poller_base_t +{ + public: + typedef void *handle_t; - static int max_fds (); + epoll_t (const ctx_t &ctx_); + ~epoll_t (); - private: + // "poller" concept. + handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); + void rm_fd (handle_t handle_); + void set_pollin (handle_t handle_); + void reset_pollin (handle_t handle_); + void set_pollout (handle_t handle_); + void reset_pollout (handle_t handle_); + void start (); + void stop (); - // Main worker thread routine. - static void worker_routine (void *arg_); + static int max_fds (); - // Main event loop. - void loop (); + private: + // Main worker thread routine. + static void worker_routine (void *arg_); - // Reference to ZMQ context. - const ctx_t &ctx; + // Main event loop. + void loop (); - // Main epoll file descriptor - fd_t epoll_fd; + // Reference to ZMQ context. + const ctx_t &ctx; - struct poll_entry_t - { - fd_t fd; - epoll_event ev; - zmq::i_poll_events *events; - }; + // Main epoll file descriptor + fd_t epoll_fd; - // List of retired event sources. - typedef std::vector retired_t; - retired_t retired; + struct poll_entry_t + { + fd_t fd; + epoll_event ev; + zmq::i_poll_events *events; + }; - // If true, thread is in the process of shutting down. - bool stopping; + // List of retired event sources. + typedef std::vector retired_t; + retired_t retired; - // Handle of the physical thread doing the I/O work. - thread_t worker; + // If true, thread is in the process of shutting down. + bool stopping; - // Synchronisation of retired event sources - mutex_t retired_sync; + // Handle of the physical thread doing the I/O work. + thread_t worker; - epoll_t (const epoll_t&); - const epoll_t &operator = (const epoll_t&); - }; + // Synchronisation of retired event sources + mutex_t retired_sync; - typedef epoll_t poller_t; + epoll_t (const epoll_t &); + const epoll_t &operator= (const epoll_t &); +}; +typedef epoll_t poller_t; } #endif diff --git a/src/err.cpp b/src/err.cpp index 4eff87646b..6f545db927 100644 --- a/src/err.cpp +++ b/src/err.cpp @@ -34,189 +34,209 @@ const char *zmq::errno_to_string (int errno_) { switch (errno_) { #if defined ZMQ_HAVE_WINDOWS - case ENOTSUP: - return "Not supported"; - case EPROTONOSUPPORT: - return "Protocol not supported"; - case ENOBUFS: - return "No buffer space available"; - case ENETDOWN: - return "Network is down"; - case EADDRINUSE: - return "Address in use"; - case EADDRNOTAVAIL: - return "Address not available"; - case ECONNREFUSED: - return "Connection refused"; - case EINPROGRESS: - return "Operation in progress"; + case ENOTSUP: + return "Not supported"; + case EPROTONOSUPPORT: + return "Protocol not supported"; + case ENOBUFS: + return "No buffer space available"; + case ENETDOWN: + return "Network is down"; + case EADDRINUSE: + return "Address in use"; + case EADDRNOTAVAIL: + return "Address not available"; + case ECONNREFUSED: + return "Connection refused"; + case EINPROGRESS: + return "Operation in progress"; #endif - case EFSM: - return "Operation cannot be accomplished in current state"; - case ENOCOMPATPROTO: - return "The protocol is not compatible with the socket type"; - case ETERM: - return "Context was terminated"; - case EMTHREAD: - return "No thread available"; - case EHOSTUNREACH: - return "Host unreachable"; - default: + case EFSM: + return "Operation cannot be accomplished in current state"; + case ENOCOMPATPROTO: + return "The protocol is not compatible with the socket type"; + case ETERM: + return "Context was terminated"; + case EMTHREAD: + return "No thread available"; + case EHOSTUNREACH: + return "Host unreachable"; + default: #if defined _MSC_VER -#pragma warning (push) -#pragma warning (disable:4996) +#pragma warning(push) +#pragma warning(disable : 4996) #endif - return strerror (errno_); + return strerror (errno_); #if defined _MSC_VER -#pragma warning (pop) +#pragma warning(pop) #endif } } -void zmq::zmq_abort(const char *errmsg_) +void zmq::zmq_abort (const char *errmsg_) { #if defined ZMQ_HAVE_WINDOWS // Raise STATUS_FATAL_APP_EXIT. - ULONG_PTR extra_info [1]; - extra_info [0] = (ULONG_PTR) errmsg_; + ULONG_PTR extra_info[1]; + extra_info[0] = (ULONG_PTR) errmsg_; RaiseException (0x40000015, EXCEPTION_NONCONTINUABLE, 1, extra_info); #else - (void)errmsg_; - print_backtrace(); + (void) errmsg_; + print_backtrace (); abort (); #endif } #ifdef ZMQ_HAVE_WINDOWS -const char *zmq::wsa_error() +const char *zmq::wsa_error () { - return wsa_error_no (WSAGetLastError(), NULL); + return wsa_error_no (WSAGetLastError (), NULL); } -const char *zmq::wsa_error_no (int no_, const char * wsae_wouldblock_string) +const char *zmq::wsa_error_no (int no_, const char *wsae_wouldblock_string) { // TODO: It seems that list of Windows socket errors is longer than this. // Investigate whether there's a way to convert it into the string // automatically (wsaError->HRESULT->string?). - return - (no_ == WSABASEERR) ? - "No Error" : - (no_ == WSAEINTR) ? - "Interrupted system call" : - (no_ == WSAEBADF) ? - "Bad file number" : - (no_ == WSAEACCES) ? - "Permission denied" : - (no_ == WSAEFAULT) ? - "Bad address" : - (no_ == WSAEINVAL) ? - "Invalid argument" : - (no_ == WSAEMFILE) ? - "Too many open files" : - (no_ == WSAEWOULDBLOCK) ? - wsae_wouldblock_string : - (no_ == WSAEINPROGRESS) ? - "Operation now in progress" : - (no_ == WSAEALREADY) ? - "Operation already in progress" : - (no_ == WSAENOTSOCK) ? - "Socket operation on non-socket" : - (no_ == WSAEDESTADDRREQ) ? - "Destination address required" : - (no_ == WSAEMSGSIZE) ? - "Message too long" : - (no_ == WSAEPROTOTYPE) ? - "Protocol wrong type for socket" : - (no_ == WSAENOPROTOOPT) ? - "Bad protocol option" : - (no_ == WSAEPROTONOSUPPORT) ? - "Protocol not supported" : - (no_ == WSAESOCKTNOSUPPORT) ? - "Socket type not supported" : - (no_ == WSAEOPNOTSUPP) ? - "Operation not supported on socket" : - (no_ == WSAEPFNOSUPPORT) ? - "Protocol family not supported" : - (no_ == WSAEAFNOSUPPORT) ? - "Address family not supported by protocol family" : - (no_ == WSAEADDRINUSE) ? - "Address already in use" : - (no_ == WSAEADDRNOTAVAIL) ? - "Can't assign requested address" : - (no_ == WSAENETDOWN) ? - "Network is down" : - (no_ == WSAENETUNREACH) ? - "Network is unreachable" : - (no_ == WSAENETRESET) ? - "Net dropped connection or reset" : - (no_ == WSAECONNABORTED) ? - "Software caused connection abort" : - (no_ == WSAECONNRESET) ? - "Connection reset by peer" : - (no_ == WSAENOBUFS) ? - "No buffer space available" : - (no_ == WSAEISCONN) ? - "Socket is already connected" : - (no_ == WSAENOTCONN) ? - "Socket is not connected" : - (no_ == WSAESHUTDOWN) ? - "Can't send after socket shutdown" : - (no_ == WSAETOOMANYREFS) ? - "Too many references can't splice" : - (no_ == WSAETIMEDOUT) ? - "Connection timed out" : - (no_ == WSAECONNREFUSED) ? - "Connection refused" : - (no_ == WSAELOOP) ? - "Too many levels of symbolic links" : - (no_ == WSAENAMETOOLONG) ? - "File name too long" : - (no_ == WSAEHOSTDOWN) ? - "Host is down" : - (no_ == WSAEHOSTUNREACH) ? - "No Route to Host" : - (no_ == WSAENOTEMPTY) ? - "Directory not empty" : - (no_ == WSAEPROCLIM) ? - "Too many processes" : - (no_ == WSAEUSERS) ? - "Too many users" : - (no_ == WSAEDQUOT) ? - "Disc Quota Exceeded" : - (no_ == WSAESTALE) ? - "Stale NFS file handle" : - (no_ == WSAEREMOTE) ? - "Too many levels of remote in path" : - (no_ == WSASYSNOTREADY) ? - "Network SubSystem is unavailable" : - (no_ == WSAVERNOTSUPPORTED) ? - "WINSOCK DLL Version out of range" : - (no_ == WSANOTINITIALISED) ? - "Successful WSASTARTUP not yet performed" : - (no_ == WSAHOST_NOT_FOUND) ? - "Host not found" : - (no_ == WSATRY_AGAIN) ? - "Non-Authoritative Host not found" : - (no_ == WSANO_RECOVERY) ? - "Non-Recoverable errors: FORMERR REFUSED NOTIMP" : - (no_ == WSANO_DATA) ? - "Valid name no data record of requested" : - "error not defined"; + return (no_ == WSABASEERR) + ? "No Error" + : (no_ == WSAEINTR) + ? "Interrupted system call" + : (no_ == WSAEBADF) + ? "Bad file number" + : (no_ == WSAEACCES) + ? "Permission denied" + : (no_ == WSAEFAULT) + ? "Bad address" + : (no_ == WSAEINVAL) + ? "Invalid argument" + : (no_ == WSAEMFILE) + ? "Too many open files" + : (no_ == WSAEWOULDBLOCK) + ? wsae_wouldblock_string + : (no_ == WSAEINPROGRESS) + ? "Operation now in progress" + : (no_ == WSAEALREADY) + ? "Operation already in " + "progress" + : (no_ == WSAENOTSOCK) + ? "Socket operation on " + "non-socket" + : (no_ == WSAEDESTADDRREQ) + ? "Destination " + "address required" + : (no_ == WSAEMSGSIZE) + ? "Message too " + "long" + : (no_ + == WSAEPROTOTYPE) + ? "Protocol " + "wrong type " + "for socket" + : (no_ + == WSAENOPROTOOPT) + ? "Bad " + "protoco" + "l " + "option" + : (no_ + == WSAEPROTONOSUPPORT) + ? "Pro" + "toc" + "ol " + "not" + " su" + "ppo" + "rte" + "d" + : (no_ + == WSAESOCKTNOSUPPORT) + ? "Socket type not supported" + : (no_ + == WSAEOPNOTSUPP) + ? "Operation not supported on socket" + : (no_ + == WSAEPFNOSUPPORT) + ? "Protocol family not supported" + : (no_ + == WSAEAFNOSUPPORT) + ? "Address family not supported by protocol family" + : (no_ == WSAEADDRINUSE) ? "Address already in use" + : (no_ == WSAEADDRNOTAVAIL) ? "Can't assign requested address" + : (no_ == WSAENETDOWN) ? "Network is down" + : (no_ == WSAENETUNREACH) ? "Network is unreachable" + : (no_ == WSAENETRESET) ? "Net dropped connection or reset" + : (no_ == WSAECONNABORTED) ? "Software caused connection abort" + : (no_ == WSAECONNRESET) ? "Connection reset by peer" + : (no_ + == WSAENOBUFS) + ? "No buffer space available" + : (no_ == WSAEISCONN) ? "Socket is already connected" + : (no_ + == WSAENOTCONN) + ? "Socket is not connected" + : (no_ == WSAESHUTDOWN) ? "Can't send after socket shutdown" + : (no_ == WSAETOOMANYREFS) ? "Too many references can't splice" + : (no_ == WSAETIMEDOUT) ? "Connection timed out" + : (no_ + == WSAECONNREFUSED) + ? "Connection refused" + : (no_ + == WSAELOOP) + ? "Too many levels of symbolic links" + : (no_ + == WSAENAMETOOLONG) + ? "File name too long" + : (no_ == WSAEHOSTDOWN) ? "Host is down" + : (no_ + == WSAEHOSTUNREACH) + ? "No Route to Host" + : (no_ == WSAENOTEMPTY) ? "Directory not empty" + : (no_ == WSAEPROCLIM) ? "Too many processes" + : ( + no_ + == WSAEUSERS) + ? "Too many users" + : (no_ + == WSAEDQUOT) + ? "Disc Quota Exceeded" + : (no_ + == WSAESTALE) + ? "Stale NFS file handle" + : (no_ == WSAEREMOTE) ? "Too many levels of remote in path" + : (no_ + == WSASYSNOTREADY) + ? "Network SubSystem is unavailable" + : (no_ == WSAVERNOTSUPPORTED) ? "WINSOCK DLL Version out of range" + : (no_ + == WSANOTINITIALISED) + ? "Successful WSASTARTUP not yet performed" + : (no_ == WSAHOST_NOT_FOUND) ? "Host not found" + : (no_ + == WSATRY_AGAIN) + ? "Non-Authoritative Host not found" + : (no_ == WSANO_RECOVERY) ? "Non-Recoverable errors: FORMERR REFUSED NOTIMP" + : (no_ + == WSANO_DATA) + ? "Valid name no data record of requested" + : "error not defined"; } void zmq::win_error (char *buffer_, size_t buffer_size_) { DWORD errcode = GetLastError (); #if defined _WIN32_WCE - DWORD rc = FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), (LPWSTR)buffer_, buffer_size_ / sizeof(wchar_t), NULL); + DWORD rc = FormatMessageW ( + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, + MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR) buffer_, + buffer_size_ / sizeof (wchar_t), NULL); #else - DWORD rc = FormatMessageA (FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), buffer_, (DWORD) buffer_size_, NULL); + DWORD rc = FormatMessageA ( + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, + MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), buffer_, (DWORD) buffer_size_, + NULL); #endif zmq_assert (rc); } @@ -224,158 +244,158 @@ void zmq::win_error (char *buffer_, size_t buffer_size_) int zmq::wsa_error_to_errno (int errcode) { switch (errcode) { -// 10004 - Interrupted system call. - case WSAEINTR: - return EINTR; -// 10009 - File handle is not valid. - case WSAEBADF: - return EBADF; -// 10013 - Permission denied. - case WSAEACCES: - return EACCES; -// 10014 - Bad address. - case WSAEFAULT: - return EFAULT; -// 10022 - Invalid argument. - case WSAEINVAL: - return EINVAL; -// 10024 - Too many open files. - case WSAEMFILE: - return EMFILE; -// 10035 - Operation would block. - case WSAEWOULDBLOCK: - return EBUSY; -// 10036 - Operation now in progress. - case WSAEINPROGRESS: - return EAGAIN; -// 10037 - Operation already in progress. - case WSAEALREADY: - return EAGAIN; -// 10038 - Socket operation on non-socket. - case WSAENOTSOCK: - return ENOTSOCK; -// 10039 - Destination address required. - case WSAEDESTADDRREQ: - return EFAULT; -// 10040 - Message too long. - case WSAEMSGSIZE: - return EMSGSIZE; -// 10041 - Protocol wrong type for socket. - case WSAEPROTOTYPE: - return EFAULT; -// 10042 - Bad protocol option. - case WSAENOPROTOOPT: - return EINVAL; -// 10043 - Protocol not supported. - case WSAEPROTONOSUPPORT: - return EPROTONOSUPPORT; -// 10044 - Socket type not supported. - case WSAESOCKTNOSUPPORT: - return EFAULT; -// 10045 - Operation not supported on socket. - case WSAEOPNOTSUPP: - return EFAULT; -// 10046 - Protocol family not supported. - case WSAEPFNOSUPPORT: - return EPROTONOSUPPORT; -// 10047 - Address family not supported by protocol family. - case WSAEAFNOSUPPORT: - return EAFNOSUPPORT; -// 10048 - Address already in use. - case WSAEADDRINUSE: - return EADDRINUSE; -// 10049 - Cannot assign requested address. - case WSAEADDRNOTAVAIL: - return EADDRNOTAVAIL; -// 10050 - Network is down. - case WSAENETDOWN: - return ENETDOWN; -// 10051 - Network is unreachable. - case WSAENETUNREACH: - return ENETUNREACH; -// 10052 - Network dropped connection on reset. - case WSAENETRESET: - return ENETRESET; -// 10053 - Software caused connection abort. - case WSAECONNABORTED: - return ECONNABORTED; -// 10054 - Connection reset by peer. - case WSAECONNRESET: - return ECONNRESET; -// 10055 - No buffer space available. - case WSAENOBUFS: - return ENOBUFS; -// 10056 - Socket is already connected. - case WSAEISCONN: - return EFAULT; -// 10057 - Socket is not connected. - case WSAENOTCONN: - return ENOTCONN; -// 10058 - Can't send after socket shutdown. - case WSAESHUTDOWN: - return EFAULT; -// 10059 - Too many references can't splice. - case WSAETOOMANYREFS: - return EFAULT; -// 10060 - Connection timed out. - case WSAETIMEDOUT: - return ETIMEDOUT; -// 10061 - Connection refused. - case WSAECONNREFUSED: - return ECONNREFUSED; -// 10062 - Too many levels of symbolic links. - case WSAELOOP: - return EFAULT; -// 10063 - File name too long. - case WSAENAMETOOLONG: - return EFAULT; -// 10064 - Host is down. - case WSAEHOSTDOWN: - return EAGAIN; -// 10065 - No route to host. - case WSAEHOSTUNREACH: - return EHOSTUNREACH; -// 10066 - Directory not empty. - case WSAENOTEMPTY: - return EFAULT; -// 10067 - Too many processes. - case WSAEPROCLIM: - return EFAULT; -// 10068 - Too many users. - case WSAEUSERS: - return EFAULT; -// 10069 - Disc Quota Exceeded. - case WSAEDQUOT: - return EFAULT; -// 10070 - Stale NFS file handle. - case WSAESTALE: - return EFAULT; -// 10071 - Too many levels of remote in path. - case WSAEREMOTE: - return EFAULT; -// 10091 - Network SubSystem is unavailable. - case WSASYSNOTREADY: - return EFAULT; -// 10092 - WINSOCK DLL Version out of range. - case WSAVERNOTSUPPORTED: - return EFAULT; -// 10093 - Successful WSASTARTUP not yet performed. - case WSANOTINITIALISED: - return EFAULT; -// 11001 - Host not found. - case WSAHOST_NOT_FOUND: - return EFAULT; -// 11002 - Non-Authoritative Host not found. - case WSATRY_AGAIN: - return EFAULT; -// 11003 - Non-Recoverable errors: FORMERR REFUSED NOTIMP. - case WSANO_RECOVERY: - return EFAULT; -// 11004 - Valid name no data record of requested. - case WSANO_DATA: - return EFAULT; - default: - wsa_assert (false); + // 10004 - Interrupted system call. + case WSAEINTR: + return EINTR; + // 10009 - File handle is not valid. + case WSAEBADF: + return EBADF; + // 10013 - Permission denied. + case WSAEACCES: + return EACCES; + // 10014 - Bad address. + case WSAEFAULT: + return EFAULT; + // 10022 - Invalid argument. + case WSAEINVAL: + return EINVAL; + // 10024 - Too many open files. + case WSAEMFILE: + return EMFILE; + // 10035 - Operation would block. + case WSAEWOULDBLOCK: + return EBUSY; + // 10036 - Operation now in progress. + case WSAEINPROGRESS: + return EAGAIN; + // 10037 - Operation already in progress. + case WSAEALREADY: + return EAGAIN; + // 10038 - Socket operation on non-socket. + case WSAENOTSOCK: + return ENOTSOCK; + // 10039 - Destination address required. + case WSAEDESTADDRREQ: + return EFAULT; + // 10040 - Message too long. + case WSAEMSGSIZE: + return EMSGSIZE; + // 10041 - Protocol wrong type for socket. + case WSAEPROTOTYPE: + return EFAULT; + // 10042 - Bad protocol option. + case WSAENOPROTOOPT: + return EINVAL; + // 10043 - Protocol not supported. + case WSAEPROTONOSUPPORT: + return EPROTONOSUPPORT; + // 10044 - Socket type not supported. + case WSAESOCKTNOSUPPORT: + return EFAULT; + // 10045 - Operation not supported on socket. + case WSAEOPNOTSUPP: + return EFAULT; + // 10046 - Protocol family not supported. + case WSAEPFNOSUPPORT: + return EPROTONOSUPPORT; + // 10047 - Address family not supported by protocol family. + case WSAEAFNOSUPPORT: + return EAFNOSUPPORT; + // 10048 - Address already in use. + case WSAEADDRINUSE: + return EADDRINUSE; + // 10049 - Cannot assign requested address. + case WSAEADDRNOTAVAIL: + return EADDRNOTAVAIL; + // 10050 - Network is down. + case WSAENETDOWN: + return ENETDOWN; + // 10051 - Network is unreachable. + case WSAENETUNREACH: + return ENETUNREACH; + // 10052 - Network dropped connection on reset. + case WSAENETRESET: + return ENETRESET; + // 10053 - Software caused connection abort. + case WSAECONNABORTED: + return ECONNABORTED; + // 10054 - Connection reset by peer. + case WSAECONNRESET: + return ECONNRESET; + // 10055 - No buffer space available. + case WSAENOBUFS: + return ENOBUFS; + // 10056 - Socket is already connected. + case WSAEISCONN: + return EFAULT; + // 10057 - Socket is not connected. + case WSAENOTCONN: + return ENOTCONN; + // 10058 - Can't send after socket shutdown. + case WSAESHUTDOWN: + return EFAULT; + // 10059 - Too many references can't splice. + case WSAETOOMANYREFS: + return EFAULT; + // 10060 - Connection timed out. + case WSAETIMEDOUT: + return ETIMEDOUT; + // 10061 - Connection refused. + case WSAECONNREFUSED: + return ECONNREFUSED; + // 10062 - Too many levels of symbolic links. + case WSAELOOP: + return EFAULT; + // 10063 - File name too long. + case WSAENAMETOOLONG: + return EFAULT; + // 10064 - Host is down. + case WSAEHOSTDOWN: + return EAGAIN; + // 10065 - No route to host. + case WSAEHOSTUNREACH: + return EHOSTUNREACH; + // 10066 - Directory not empty. + case WSAENOTEMPTY: + return EFAULT; + // 10067 - Too many processes. + case WSAEPROCLIM: + return EFAULT; + // 10068 - Too many users. + case WSAEUSERS: + return EFAULT; + // 10069 - Disc Quota Exceeded. + case WSAEDQUOT: + return EFAULT; + // 10070 - Stale NFS file handle. + case WSAESTALE: + return EFAULT; + // 10071 - Too many levels of remote in path. + case WSAEREMOTE: + return EFAULT; + // 10091 - Network SubSystem is unavailable. + case WSASYSNOTREADY: + return EFAULT; + // 10092 - WINSOCK DLL Version out of range. + case WSAVERNOTSUPPORTED: + return EFAULT; + // 10093 - Successful WSASTARTUP not yet performed. + case WSANOTINITIALISED: + return EFAULT; + // 11001 - Host not found. + case WSAHOST_NOT_FOUND: + return EFAULT; + // 11002 - Non-Authoritative Host not found. + case WSATRY_AGAIN: + return EFAULT; + // 11003 - Non-Recoverable errors: FORMERR REFUSED NOTIMP. + case WSANO_RECOVERY: + return EFAULT; + // 11004 - Valid name no data record of requested. + case WSANO_DATA: + return EFAULT; + default: + wsa_assert (false); } // Not reachable return 0; @@ -417,9 +437,9 @@ void zmq::print_backtrace (void) rc = unw_get_proc_name (&cursor, func_name, 256, &offset); if (rc == -UNW_ENOINFO) - strcpy(func_name, "?"); + strcpy (func_name, "?"); - addr = (void *)(p_info.start_ip + offset); + addr = (void *) (p_info.start_ip + offset); if (dladdr (addr, &dl_info) && dl_info.dli_fname) file_name = dl_info.dli_fname; @@ -433,7 +453,7 @@ void zmq::print_backtrace (void) free (demangled_name); } puts (""); - + fflush (stdout); mtx.unlock (); } diff --git a/src/err.hpp b/src/err.hpp index c7869f801f..2381352b8a 100644 --- a/src/err.hpp +++ b/src/err.hpp @@ -55,58 +55,60 @@ namespace zmq { - const char *errno_to_string (int errno_); - void zmq_abort (const char *errmsg_); - void print_backtrace (void); +const char *errno_to_string (int errno_); +void zmq_abort (const char *errmsg_); +void print_backtrace (void); } #ifdef ZMQ_HAVE_WINDOWS namespace zmq { - const char *wsa_error (); - const char *wsa_error_no (int no_, const char * wsae_wouldblock_string = "Operation would block"); - void win_error (char *buffer_, size_t buffer_size_); - int wsa_error_to_errno (int errcode); +const char *wsa_error (); +const char * +wsa_error_no (int no_, + const char *wsae_wouldblock_string = "Operation would block"); +void win_error (char *buffer_, size_t buffer_size_); +int wsa_error_to_errno (int errcode); } // Provides convenient way to check WSA-style errors on Windows. -#define wsa_assert(x) \ - do {\ - if (unlikely (!(x))) {\ - const char *errstr = zmq::wsa_error ();\ - if (errstr != NULL) {\ - fprintf (stderr, "Assertion failed: %s (%s:%d)\n", errstr, \ - __FILE__, __LINE__);\ - fflush (stderr);\ - zmq::zmq_abort (errstr);\ - }\ - }\ +#define wsa_assert(x) \ + do { \ + if (unlikely (!(x))) { \ + const char *errstr = zmq::wsa_error (); \ + if (errstr != NULL) { \ + fprintf (stderr, "Assertion failed: %s (%s:%d)\n", errstr, \ + __FILE__, __LINE__); \ + fflush (stderr); \ + zmq::zmq_abort (errstr); \ + } \ + } \ } while (false) // Provides convenient way to assert on WSA-style errors on Windows. -#define wsa_assert_no(no) \ - do {\ - const char *errstr = zmq::wsa_error_no (no);\ - if (errstr != NULL) {\ - fprintf (stderr, "Assertion failed: %s (%s:%d)\n", errstr, \ - __FILE__, __LINE__);\ - fflush (stderr);\ - zmq::zmq_abort (errstr);\ - }\ +#define wsa_assert_no(no) \ + do { \ + const char *errstr = zmq::wsa_error_no (no); \ + if (errstr != NULL) { \ + fprintf (stderr, "Assertion failed: %s (%s:%d)\n", errstr, \ + __FILE__, __LINE__); \ + fflush (stderr); \ + zmq::zmq_abort (errstr); \ + } \ } while (false) // Provides convenient way to check GetLastError-style errors on Windows. -#define win_assert(x) \ - do {\ - if (unlikely (!(x))) {\ - char errstr [256];\ - zmq::win_error (errstr, 256);\ - fprintf (stderr, "Assertion failed: %s (%s:%d)\n", errstr, \ - __FILE__, __LINE__);\ - fflush (stderr);\ - zmq::zmq_abort (errstr);\ - }\ +#define win_assert(x) \ + do { \ + if (unlikely (!(x))) { \ + char errstr[256]; \ + zmq::win_error (errstr, 256); \ + fprintf (stderr, "Assertion failed: %s (%s:%d)\n", errstr, \ + __FILE__, __LINE__); \ + fflush (stderr); \ + zmq::zmq_abort (errstr); \ + } \ } while (false) #endif @@ -114,60 +116,58 @@ namespace zmq // This macro works in exactly the same way as the normal assert. It is used // in its stead because standard assert on Win32 in broken - it prints nothing // when used within the scope of JNI library. -#define zmq_assert(x) \ - do {\ - if (unlikely (!(x))) {\ - fprintf (stderr, "Assertion failed: %s (%s:%d)\n", #x, \ - __FILE__, __LINE__);\ - fflush (stderr);\ - zmq::zmq_abort (#x);\ - }\ +#define zmq_assert(x) \ + do { \ + if (unlikely (!(x))) { \ + fprintf (stderr, "Assertion failed: %s (%s:%d)\n", #x, __FILE__, \ + __LINE__); \ + fflush (stderr); \ + zmq::zmq_abort (#x); \ + } \ } while (false) // Provides convenient way to check for errno-style errors. -#define errno_assert(x) \ - do {\ - if (unlikely (!(x))) {\ - const char *errstr = strerror (errno);\ - fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__);\ - fflush (stderr);\ - zmq::zmq_abort (errstr);\ - }\ +#define errno_assert(x) \ + do { \ + if (unlikely (!(x))) { \ + const char *errstr = strerror (errno); \ + fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__); \ + fflush (stderr); \ + zmq::zmq_abort (errstr); \ + } \ } while (false) // Provides convenient way to check for POSIX errors. -#define posix_assert(x) \ - do {\ - if (unlikely (x)) {\ - const char *errstr = strerror (x);\ - fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__);\ - fflush (stderr);\ - zmq::zmq_abort (errstr);\ - }\ +#define posix_assert(x) \ + do { \ + if (unlikely (x)) { \ + const char *errstr = strerror (x); \ + fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__); \ + fflush (stderr); \ + zmq::zmq_abort (errstr); \ + } \ } while (false) // Provides convenient way to check for errors from getaddrinfo. -#define gai_assert(x) \ - do {\ - if (unlikely (x)) {\ - const char *errstr = gai_strerror (x);\ - fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__);\ - fflush (stderr);\ - zmq::zmq_abort (errstr);\ - }\ +#define gai_assert(x) \ + do { \ + if (unlikely (x)) { \ + const char *errstr = gai_strerror (x); \ + fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__); \ + fflush (stderr); \ + zmq::zmq_abort (errstr); \ + } \ } while (false) // Provides convenient way to check whether memory allocation have succeeded. -#define alloc_assert(x) \ - do {\ - if (unlikely (!x)) {\ - fprintf (stderr, "FATAL ERROR: OUT OF MEMORY (%s:%d)\n",\ - __FILE__, __LINE__);\ - fflush (stderr);\ - zmq::zmq_abort ("FATAL ERROR: OUT OF MEMORY");\ - }\ +#define alloc_assert(x) \ + do { \ + if (unlikely (!x)) { \ + fprintf (stderr, "FATAL ERROR: OUT OF MEMORY (%s:%d)\n", __FILE__, \ + __LINE__); \ + fflush (stderr); \ + zmq::zmq_abort ("FATAL ERROR: OUT OF MEMORY"); \ + } \ } while (false) #endif - - diff --git a/src/fd.hpp b/src/fd.hpp index 5b3afe8515..892e2a9df3 100644 --- a/src/fd.hpp +++ b/src/fd.hpp @@ -37,16 +37,25 @@ namespace zmq { #ifdef ZMQ_HAVE_WINDOWS -#if defined _MSC_VER &&_MSC_VER <= 1400 - typedef UINT_PTR fd_t; - enum {retired_fd = (fd_t)(~0)}; +#if defined _MSC_VER && _MSC_VER <= 1400 +typedef UINT_PTR fd_t; +enum +{ + retired_fd = (fd_t) (~0) +}; #else - typedef SOCKET fd_t; - enum {retired_fd = (fd_t)INVALID_SOCKET}; +typedef SOCKET fd_t; +enum +{ + retired_fd = (fd_t) INVALID_SOCKET +}; #endif #else - typedef int fd_t; - enum {retired_fd = -1}; +typedef int fd_t; +enum +{ + retired_fd = -1 +}; #endif } #endif diff --git a/src/fq.cpp b/src/fq.cpp index 0137b31301..1217c08876 100644 --- a/src/fq.cpp +++ b/src/fq.cpp @@ -33,11 +33,7 @@ #include "err.hpp" #include "msg.hpp" -zmq::fq_t::fq_t () : - active (0), - last_in (NULL), - current (0), - more (false) +zmq::fq_t::fq_t () : active (0), last_in (NULL), current (0), more (false) { } @@ -93,20 +89,19 @@ int zmq::fq_t::recvpipe (msg_t *msg_, pipe_t **pipe_) // Round-robin over the pipes to get the next message. while (active > 0) { - // Try to fetch new message. If we've already read part of the message // subsequent part should be immediately available. - bool fetched = pipes [current]->read (msg_); + bool fetched = pipes[current]->read (msg_); // Note that when message is not fetched, current pipe is deactivated // and replaced by another active pipe. Thus we don't have to increase // the 'current' pointer. if (fetched) { if (pipe_) - *pipe_ = pipes [current]; - more = msg_->flags () & msg_t::more? true: false; + *pipe_ = pipes[current]; + more = msg_->flags () & msg_t::more ? true : false; if (!more) { - last_in = pipes [current]; + last_in = pipes[current]; current = (current + 1) % active; } return 0; @@ -142,7 +137,7 @@ bool zmq::fq_t::has_in () // get back to its original value. Otherwise it'll point to the first // pipe holding messages, skipping only pipes with no messages available. while (active > 0) { - if (pipes [current]->check_read ()) + if (pipes[current]->check_read ()) return true; // Deactivate the pipe. @@ -157,7 +152,5 @@ bool zmq::fq_t::has_in () const zmq::blob_t &zmq::fq_t::get_credential () const { - return last_in? - last_in->get_credential (): saved_credential; + return last_in ? last_in->get_credential () : saved_credential; } - diff --git a/src/fq.hpp b/src/fq.hpp index 6be74a86bf..6dd2f2eadf 100644 --- a/src/fq.hpp +++ b/src/fq.hpp @@ -37,56 +37,52 @@ namespace zmq { +// Class manages a set of inbound pipes. On receive it performs fair +// queueing so that senders gone berserk won't cause denial of +// service for decent senders. - // Class manages a set of inbound pipes. On receive it performs fair - // queueing so that senders gone berserk won't cause denial of - // service for decent senders. - - class fq_t - { - public: - - fq_t (); - ~fq_t (); - - void attach (pipe_t *pipe_); - void activated (pipe_t *pipe_); - void pipe_terminated (pipe_t *pipe_); - - int recv (msg_t *msg_); - int recvpipe (msg_t *msg_, pipe_t **pipe_); - bool has_in (); - const blob_t &get_credential () const; - - private: - - // Inbound pipes. - typedef array_t pipes_t; - pipes_t pipes; - - // Number of active pipes. All the active pipes are located at the - // beginning of the pipes array. - pipes_t::size_type active; - - // Pointer to the last pipe we received message from. - // NULL when no message has been received or the pipe - // has terminated. - pipe_t *last_in; - - // Index of the next bound pipe to read a message from. - pipes_t::size_type current; - - // If true, part of a multipart message was already received, but - // there are following parts still waiting in the current pipe. - bool more; - - // Holds credential after the last_active_pipe has terminated. - blob_t saved_credential; - - fq_t (const fq_t&); - const fq_t &operator = (const fq_t&); - }; - +class fq_t +{ + public: + fq_t (); + ~fq_t (); + + void attach (pipe_t *pipe_); + void activated (pipe_t *pipe_); + void pipe_terminated (pipe_t *pipe_); + + int recv (msg_t *msg_); + int recvpipe (msg_t *msg_, pipe_t **pipe_); + bool has_in (); + const blob_t &get_credential () const; + + private: + // Inbound pipes. + typedef array_t pipes_t; + pipes_t pipes; + + // Number of active pipes. All the active pipes are located at the + // beginning of the pipes array. + pipes_t::size_type active; + + // Pointer to the last pipe we received message from. + // NULL when no message has been received or the pipe + // has terminated. + pipe_t *last_in; + + // Index of the next bound pipe to read a message from. + pipes_t::size_type current; + + // If true, part of a multipart message was already received, but + // there are following parts still waiting in the current pipe. + bool more; + + // Holds credential after the last_active_pipe has terminated. + blob_t saved_credential; + + fq_t (const fq_t &); + const fq_t &operator= (const fq_t &); +}; } #endif diff --git a/src/gather.cpp b/src/gather.cpp index 9c57675626..00d1935960 100644 --- a/src/gather.cpp +++ b/src/gather.cpp @@ -68,7 +68,6 @@ int zmq::gather_t::xrecv (msg_t *msg_) // Drop any messages with more flag while (rc == 0 && msg_->flags () & msg_t::more) { - // drop all frames of the current multi-frame message rc = fq.recvpipe (msg_, NULL); diff --git a/src/gather.hpp b/src/gather.hpp index 1b3096955f..0efed02c65 100644 --- a/src/gather.hpp +++ b/src/gather.hpp @@ -36,40 +36,33 @@ namespace zmq { +class ctx_t; +class pipe_t; +class msg_t; +class io_thread_t; - class ctx_t; - class pipe_t; - class msg_t; - class io_thread_t; - - class gather_t : - public socket_base_t - { - public: - - gather_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~gather_t (); - - protected: - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - const blob_t &get_credential () const; - void xread_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - - // Fair queueing object for inbound pipes. - fq_t fq; - - gather_t (const gather_t&); - const gather_t &operator = (const gather_t&); - - }; - +class gather_t : public socket_base_t +{ + public: + gather_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~gather_t (); + + protected: + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + const blob_t &get_credential () const; + void xread_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + // Fair queueing object for inbound pipes. + fq_t fq; + + gather_t (const gather_t &); + const gather_t &operator= (const gather_t &); +}; } #endif diff --git a/src/gssapi_client.cpp b/src/gssapi_client.cpp index 75ba5a2b32..291e9f09ba 100644 --- a/src/gssapi_client.cpp +++ b/src/gssapi_client.cpp @@ -49,19 +49,22 @@ zmq::gssapi_client_t::gssapi_client_t (session_base_t *session_, mechs (), security_context_established (false) { - const std::string::size_type service_size = options_.gss_service_principal.size(); - service_name = static_cast (malloc(service_size+1)); - assert(service_name); - memcpy(service_name, options_.gss_service_principal.c_str(), service_size+1 ); + const std::string::size_type service_size = + options_.gss_service_principal.size (); + service_name = static_cast (malloc (service_size + 1)); + assert (service_name); + memcpy (service_name, options_.gss_service_principal.c_str (), + service_size + 1); service_name_type = convert_nametype (options_.gss_service_principal_nt); maj_stat = GSS_S_COMPLETE; - if(!options_.gss_principal.empty()) - { - const std::string::size_type principal_size = options_.gss_principal.size(); - principal_name = static_cast (malloc(principal_size+1)); - assert(principal_name); - memcpy(principal_name, options_.gss_principal.c_str(), principal_size+1 ); + if (!options_.gss_principal.empty ()) { + const std::string::size_type principal_size = + options_.gss_principal.size (); + principal_name = static_cast (malloc (principal_size + 1)); + assert (principal_name); + memcpy (principal_name, options_.gss_principal.c_str (), + principal_size + 1); gss_OID name_type = convert_nametype (options_.gss_principal_nt); if (acquire_credentials (principal_name, &cred, name_type) != 0) @@ -74,16 +77,16 @@ zmq::gssapi_client_t::gssapi_client_t (session_base_t *session_, zmq::gssapi_client_t::~gssapi_client_t () { - if(service_name) + if (service_name) free (service_name); - if(cred) - gss_release_cred(&min_stat, &cred); + if (cred) + gss_release_cred (&min_stat, &cred); } int zmq::gssapi_client_t::next_handshake_command (msg_t *msg_) { if (state == send_ready) { - int rc = produce_ready(msg_); + int rc = produce_ready (msg_); if (rc == 0) state = connected; @@ -107,8 +110,7 @@ int zmq::gssapi_client_t::next_handshake_command (msg_t *msg_) if (maj_stat == GSS_S_COMPLETE) { security_context_established = true; state = recv_ready; - } - else + } else state = recv_next_token; return 0; @@ -117,7 +119,7 @@ int zmq::gssapi_client_t::next_handshake_command (msg_t *msg_) int zmq::gssapi_client_t::process_handshake_command (msg_t *msg_) { if (state == recv_ready) { - int rc = process_ready(msg_); + int rc = process_ready (msg_); if (rc == 0) state = send_ready; @@ -126,8 +128,7 @@ int zmq::gssapi_client_t::process_handshake_command (msg_t *msg_) if (state != recv_next_token) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; return -1; } @@ -151,7 +152,7 @@ int zmq::gssapi_client_t::encode (msg_t *msg_) zmq_assert (state == connected); if (do_encryption) - return encode_message (msg_); + return encode_message (msg_); return 0; } @@ -161,14 +162,14 @@ int zmq::gssapi_client_t::decode (msg_t *msg_) zmq_assert (state == connected); if (do_encryption) - return decode_message (msg_); + return decode_message (msg_); return 0; } zmq::mechanism_t::status_t zmq::gssapi_client_t::status () const { - return state == connected? mechanism_t::ready: mechanism_t::handshaking; + return state == connected ? mechanism_t::ready : mechanism_t::handshaking; } int zmq::gssapi_client_t::initialize_context () @@ -180,22 +181,20 @@ int zmq::gssapi_client_t::initialize_context () // First time through, import service_name into target_name if (target_name == GSS_C_NO_NAME) { send_tok.value = service_name; - send_tok.length = strlen(service_name) + 1; - OM_uint32 maj = gss_import_name(&min_stat, &send_tok, - service_name_type, - &target_name); + send_tok.length = strlen (service_name) + 1; + OM_uint32 maj = gss_import_name (&min_stat, &send_tok, + service_name_type, &target_name); if (maj != GSS_S_COMPLETE) return -1; } - maj_stat = gss_init_sec_context(&init_sec_min_stat, cred, &context, - target_name, mechs.elements, - gss_flags, 0, NULL, token_ptr, NULL, - &send_tok, &ret_flags, NULL); + maj_stat = gss_init_sec_context ( + &init_sec_min_stat, cred, &context, target_name, mechs.elements, + gss_flags, 0, NULL, token_ptr, NULL, &send_tok, &ret_flags, NULL); if (token_ptr != GSS_C_NO_BUFFER) - free(recv_tok.value); + free (recv_tok.value); return 0; } @@ -203,18 +202,18 @@ int zmq::gssapi_client_t::initialize_context () int zmq::gssapi_client_t::produce_next_token (msg_t *msg_) { if (send_tok.length != 0) { // Server expects another token - if (produce_initiate(msg_, send_tok.value, send_tok.length) < 0) { - gss_release_buffer(&min_stat, &send_tok); - gss_release_name(&min_stat, &target_name); + if (produce_initiate (msg_, send_tok.value, send_tok.length) < 0) { + gss_release_buffer (&min_stat, &send_tok); + gss_release_name (&min_stat, &target_name); return -1; } } - gss_release_buffer(&min_stat, &send_tok); + gss_release_buffer (&min_stat, &send_tok); if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED) { - gss_release_name(&min_stat, &target_name); + gss_release_name (&min_stat, &target_name); if (context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &context, GSS_C_NO_BUFFER); + gss_delete_sec_context (&min_stat, &context, GSS_C_NO_BUFFER); return -1; } @@ -224,8 +223,8 @@ int zmq::gssapi_client_t::produce_next_token (msg_t *msg_) int zmq::gssapi_client_t::process_next_token (msg_t *msg_) { if (maj_stat == GSS_S_CONTINUE_NEEDED) { - if (process_initiate(msg_, &recv_tok.value, recv_tok.length) < 0) { - gss_release_name(&min_stat, &target_name); + if (process_initiate (msg_, &recv_tok.value, recv_tok.length) < 0) { + gss_release_name (&min_stat, &target_name); return -1; } token_ptr = &recv_tok; diff --git a/src/gssapi_client.hpp b/src/gssapi_client.hpp index 6bfdf50cc1..02d72fc9af 100644 --- a/src/gssapi_client.hpp +++ b/src/gssapi_client.hpp @@ -36,57 +36,55 @@ namespace zmq { +class msg_t; +class session_base_t; - class msg_t; - class session_base_t; - - class gssapi_client_t : public gssapi_mechanism_base_t +class gssapi_client_t : public gssapi_mechanism_base_t +{ + public: + gssapi_client_t (session_base_t *session_, const options_t &options_); + virtual ~gssapi_client_t (); + + // mechanism implementation + virtual int next_handshake_command (msg_t *msg_); + virtual int process_handshake_command (msg_t *msg_); + virtual int encode (msg_t *msg_); + virtual int decode (msg_t *msg_); + virtual status_t status () const; + + private: + enum state_t { - public: - gssapi_client_t (session_base_t *session_, const options_t &options_); - virtual ~gssapi_client_t (); - - // mechanism implementation - virtual int next_handshake_command (msg_t *msg_); - virtual int process_handshake_command (msg_t *msg_); - virtual int encode (msg_t *msg_); - virtual int decode (msg_t *msg_); - virtual status_t status () const; - - private: - - enum state_t { - call_next_init, - send_next_token, - recv_next_token, - send_ready, - recv_ready, - connected - }; - - // Human-readable principal name of the service we are connecting to - char * service_name; + call_next_init, + send_next_token, + recv_next_token, + send_ready, + recv_ready, + connected + }; - gss_OID service_name_type; + // Human-readable principal name of the service we are connecting to + char *service_name; - // Current FSM state - state_t state; + gss_OID service_name_type; - // Points to either send_tok or recv_tok - // during context initialization - gss_buffer_desc *token_ptr; + // Current FSM state + state_t state; - // The desired underlying mechanism - gss_OID_set_desc mechs; + // Points to either send_tok or recv_tok + // during context initialization + gss_buffer_desc *token_ptr; - // True iff client considers the server authenticated - bool security_context_established; + // The desired underlying mechanism + gss_OID_set_desc mechs; - int initialize_context (); - int produce_next_token (msg_t *msg_); - int process_next_token (msg_t *msg_); - }; + // True iff client considers the server authenticated + bool security_context_established; + int initialize_context (); + int produce_next_token (msg_t *msg_); + int process_next_token (msg_t *msg_); +}; } #endif diff --git a/src/gssapi_mechanism_base.cpp b/src/gssapi_mechanism_base.cpp index 4c1dda9a25..b9ffeec52c 100644 --- a/src/gssapi_mechanism_base.cpp +++ b/src/gssapi_mechanism_base.cpp @@ -41,8 +41,7 @@ #include "wire.hpp" zmq::gssapi_mechanism_base_t::gssapi_mechanism_base_t ( - session_base_t *session_, - const options_t &options_) : + session_base_t *session_, const options_t &options_) : mechanism_base_t (session_, options_), send_tok (), recv_tok (), @@ -62,10 +61,10 @@ zmq::gssapi_mechanism_base_t::gssapi_mechanism_base_t ( zmq::gssapi_mechanism_base_t::~gssapi_mechanism_base_t () { - if(target_name) - gss_release_name(&min_stat, &target_name); - if(context) - gss_delete_sec_context(&min_stat, &context, GSS_C_NO_BUFFER); + if (target_name) + gss_release_name (&min_stat, &target_name); + if (context) + gss_delete_sec_context (&min_stat, &context, GSS_C_NO_BUFFER); } int zmq::gssapi_mechanism_base_t::encode_message (msg_t *msg_) @@ -81,17 +80,18 @@ int zmq::gssapi_mechanism_base_t::encode_message (msg_t *msg_) if (msg_->flags () & msg_t::command) flags |= 0x02; - uint8_t *plaintext_buffer = static_cast (malloc(msg_->size ()+1)); - alloc_assert(plaintext_buffer); + uint8_t *plaintext_buffer = + static_cast (malloc (msg_->size () + 1)); + alloc_assert (plaintext_buffer); plaintext_buffer[0] = flags; - memcpy (plaintext_buffer+1, msg_->data(), msg_->size()); + memcpy (plaintext_buffer + 1, msg_->data (), msg_->size ()); plaintext.value = plaintext_buffer; - plaintext.length = msg_->size ()+1; + plaintext.length = msg_->size () + 1; - maj_stat = gss_wrap(&min_stat, context, 1, GSS_C_QOP_DEFAULT, - &plaintext, &state, &wrapped); + maj_stat = gss_wrap (&min_stat, context, 1, GSS_C_QOP_DEFAULT, &plaintext, + &state, &wrapped); zmq_assert (maj_stat == GSS_S_COMPLETE); zmq_assert (state); @@ -103,14 +103,14 @@ int zmq::gssapi_mechanism_base_t::encode_message (msg_t *msg_) rc = msg_->init_size (8 + 4 + wrapped.length); zmq_assert (rc == 0); - uint8_t *ptr = static_cast (msg_->data ()); + uint8_t *ptr = static_cast (msg_->data ()); // Add command string memcpy (ptr, "\x07MESSAGE", 8); ptr += 8; // Add token length - put_uint32 (ptr, static_cast (wrapped.length)); + put_uint32 (ptr, static_cast (wrapped.length)); ptr += 4; // Add wrapped token value @@ -124,7 +124,7 @@ int zmq::gssapi_mechanism_base_t::encode_message (msg_t *msg_) int zmq::gssapi_mechanism_base_t::decode_message (msg_t *msg_) { - const uint8_t *ptr = static_cast (msg_->data ()); + const uint8_t *ptr = static_cast (msg_->data ()); size_t bytes_left = msg_->size (); int rc = check_basic_command_structure (msg_); @@ -134,8 +134,7 @@ int zmq::gssapi_mechanism_base_t::decode_message (msg_t *msg_) // Get command string if (bytes_left < 8 || memcmp (ptr, "\x07MESSAGE", 8)) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; return -1; } @@ -164,12 +163,12 @@ int zmq::gssapi_mechanism_base_t::decode_message (msg_t *msg_) return -1; } // TODO: instead of malloc/memcpy, can we just do: wrapped.value = ptr; - const size_t alloc_length = wrapped.length? wrapped.length: 1; - wrapped.value = static_cast (malloc (alloc_length)); + const size_t alloc_length = wrapped.length ? wrapped.length : 1; + wrapped.value = static_cast (malloc (alloc_length)); alloc_assert (wrapped.value); if (wrapped.length) { - memcpy(wrapped.value, ptr, wrapped.length); + memcpy (wrapped.value, ptr, wrapped.length); ptr += wrapped.length; bytes_left -= wrapped.length; } @@ -177,38 +176,37 @@ int zmq::gssapi_mechanism_base_t::decode_message (msg_t *msg_) // Unwrap the token value int state; gss_buffer_desc plaintext; - maj_stat = gss_unwrap(&min_stat, context, &wrapped, &plaintext, - &state, (gss_qop_t *) NULL); + maj_stat = gss_unwrap (&min_stat, context, &wrapped, &plaintext, &state, + (gss_qop_t *) NULL); - if (maj_stat != GSS_S_COMPLETE) - { + if (maj_stat != GSS_S_COMPLETE) { gss_release_buffer (&min_stat, &plaintext); free (wrapped.value); session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); errno = EPROTO; return -1; } - zmq_assert(state); + zmq_assert (state); // Re-initialize msg_ for plaintext rc = msg_->close (); zmq_assert (rc == 0); - rc = msg_->init_size (plaintext.length-1); + rc = msg_->init_size (plaintext.length - 1); zmq_assert (rc == 0); - const uint8_t flags = static_cast (plaintext.value)[0]; + const uint8_t flags = static_cast (plaintext.value)[0]; if (flags & 0x01) msg_->set_flags (msg_t::more); if (flags & 0x02) msg_->set_flags (msg_t::command); - memcpy (msg_->data (), static_cast (plaintext.value)+1, plaintext.length-1); + memcpy (msg_->data (), static_cast (plaintext.value) + 1, + plaintext.length - 1); gss_release_buffer (&min_stat, &plaintext); - free(wrapped.value); + free (wrapped.value); if (bytes_left > 0) { session->get_socket ()->event_handshake_failed_protocol ( @@ -221,7 +219,9 @@ int zmq::gssapi_mechanism_base_t::decode_message (msg_t *msg_) return 0; } -int zmq::gssapi_mechanism_base_t::produce_initiate (msg_t *msg_, void *token_value_, size_t token_length_) +int zmq::gssapi_mechanism_base_t::produce_initiate (msg_t *msg_, + void *token_value_, + size_t token_length_) { zmq_assert (token_value_); zmq_assert (token_length_ <= 0xFFFFFFFFUL); @@ -231,14 +231,14 @@ int zmq::gssapi_mechanism_base_t::produce_initiate (msg_t *msg_, void *token_val const int rc = msg_->init_size (command_size); errno_assert (rc == 0); - uint8_t *ptr = static_cast (msg_->data ()); + uint8_t *ptr = static_cast (msg_->data ()); // Add command string memcpy (ptr, "\x08INITIATE", 9); ptr += 9; // Add token length - put_uint32 (ptr, static_cast (token_length_)); + put_uint32 (ptr, static_cast (token_length_)); ptr += 4; // Add token value @@ -248,11 +248,13 @@ int zmq::gssapi_mechanism_base_t::produce_initiate (msg_t *msg_, void *token_val return 0; } -int zmq::gssapi_mechanism_base_t::process_initiate (msg_t *msg_, void **token_value_, size_t &token_length_) +int zmq::gssapi_mechanism_base_t::process_initiate (msg_t *msg_, + void **token_value_, + size_t &token_length_) { zmq_assert (token_value_); - const uint8_t *ptr = static_cast (msg_->data ()); + const uint8_t *ptr = static_cast (msg_->data ()); size_t bytes_left = msg_->size (); int rc = check_basic_command_structure (msg_); @@ -262,8 +264,7 @@ int zmq::gssapi_mechanism_base_t::process_initiate (msg_t *msg_, void **token_va // Get command string if (bytes_left < 9 || memcmp (ptr, "\x08INITIATE", 9)) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; return -1; } @@ -291,11 +292,12 @@ int zmq::gssapi_mechanism_base_t::process_initiate (msg_t *msg_, void **token_va return -1; } - *token_value_ = static_cast (malloc (token_length_ ? token_length_ : 1)); + *token_value_ = + static_cast (malloc (token_length_ ? token_length_ : 1)); alloc_assert (*token_value_); if (token_length_) { - memcpy(*token_value_, ptr, token_length_); + memcpy (*token_value_, ptr, token_length_); ptr += token_length_; bytes_left -= token_length_; } @@ -329,7 +331,7 @@ int zmq::gssapi_mechanism_base_t::process_ready (msg_t *msg_) return rc; } - const unsigned char *ptr = static_cast (msg_->data ()); + const unsigned char *ptr = static_cast (msg_->data ()); size_t bytes_left = msg_->size (); int rc = check_basic_command_structure (msg_); @@ -338,8 +340,7 @@ int zmq::gssapi_mechanism_base_t::process_ready (msg_t *msg_) if (bytes_left < 6 || memcmp (ptr, "\x05READY", 6)) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; return -1; } @@ -347,9 +348,8 @@ int zmq::gssapi_mechanism_base_t::process_ready (msg_t *msg_) bytes_left -= 6; rc = parse_metadata (ptr, bytes_left); if (rc == -1) - session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_METADATA); + session->get_socket ()->event_handshake_failed_protocol ( + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_METADATA); return rc; } @@ -363,7 +363,7 @@ const gss_OID zmq::gssapi_mechanism_base_t::convert_nametype (int zmq_nametype) return GSS_C_NT_USER_NAME; case ZMQ_GSSAPI_NT_KRB5_PRINCIPAL: #ifdef GSS_KRB5_NT_PRINCIPAL_NAME - return (gss_OID)GSS_KRB5_NT_PRINCIPAL_NAME; + return (gss_OID) GSS_KRB5_NT_PRINCIPAL_NAME; #else return GSS_C_NT_USER_NAME; #endif @@ -371,7 +371,9 @@ const gss_OID zmq::gssapi_mechanism_base_t::convert_nametype (int zmq_nametype) return NULL; } -int zmq::gssapi_mechanism_base_t::acquire_credentials (char * service_name_, gss_cred_id_t * cred_, gss_OID name_type_) +int zmq::gssapi_mechanism_base_t::acquire_credentials (char *service_name_, + gss_cred_id_t *cred_, + gss_OID name_type_) { OM_uint32 maj_stat; OM_uint32 min_stat; @@ -381,20 +383,18 @@ int zmq::gssapi_mechanism_base_t::acquire_credentials (char * service_name_, gss name_buf.value = service_name_; name_buf.length = strlen ((char *) name_buf.value) + 1; - maj_stat = gss_import_name (&min_stat, &name_buf, - name_type_, &server_name); + maj_stat = gss_import_name (&min_stat, &name_buf, name_type_, &server_name); if (maj_stat != GSS_S_COMPLETE) return -1; - maj_stat = gss_acquire_cred (&min_stat, server_name, 0, - GSS_C_NO_OID_SET, GSS_C_BOTH, - cred_, NULL, NULL); + maj_stat = gss_acquire_cred (&min_stat, server_name, 0, GSS_C_NO_OID_SET, + GSS_C_BOTH, cred_, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) return -1; - gss_release_name(&min_stat, &server_name); + gss_release_name (&min_stat, &server_name); return 0; } diff --git a/src/gssapi_mechanism_base.hpp b/src/gssapi_mechanism_base.hpp index befa7e279d..4e14809c4c 100644 --- a/src/gssapi_mechanism_base.hpp +++ b/src/gssapi_mechanism_base.hpp @@ -42,91 +42,89 @@ namespace zmq { +class msg_t; - class msg_t; - - /// Commonalities between clients and servers are captured here. - /// For example, clients and servers both need to produce and - /// process context-level GSSAPI tokens (via INITIATE commands) - /// and per-message GSSAPI tokens (via MESSAGE commands). - class gssapi_mechanism_base_t : public virtual mechanism_base_t - { - public: - gssapi_mechanism_base_t (session_base_t *session_, - const options_t &options_); - virtual ~gssapi_mechanism_base_t () = 0; - - protected: - // Produce a context-level GSSAPI token (INITIATE command) - // during security context initialization. - int produce_initiate (msg_t *msg_, void *data_, size_t data_len_); +/// Commonalities between clients and servers are captured here. +/// For example, clients and servers both need to produce and +/// process context-level GSSAPI tokens (via INITIATE commands) +/// and per-message GSSAPI tokens (via MESSAGE commands). +class gssapi_mechanism_base_t : public virtual mechanism_base_t +{ + public: + gssapi_mechanism_base_t (session_base_t *session_, + const options_t &options_); + virtual ~gssapi_mechanism_base_t () = 0; - // Process a context-level GSSAPI token (INITIATE command) - // during security context initialization. - int process_initiate (msg_t *msg_, void **data_, size_t &data_len_); + protected: + // Produce a context-level GSSAPI token (INITIATE command) + // during security context initialization. + int produce_initiate (msg_t *msg_, void *data_, size_t data_len_); - // Produce a metadata ready msg (READY) to conclude handshake - int produce_ready (msg_t *msg_); + // Process a context-level GSSAPI token (INITIATE command) + // during security context initialization. + int process_initiate (msg_t *msg_, void **data_, size_t &data_len_); - // Process a metadata ready msg (READY) - int process_ready (msg_t *msg_); + // Produce a metadata ready msg (READY) to conclude handshake + int produce_ready (msg_t *msg_); - // Encode a per-message GSSAPI token (MESSAGE command) using - // the established security context. - int encode_message (msg_t *msg_); + // Process a metadata ready msg (READY) + int process_ready (msg_t *msg_); - // Decode a per-message GSSAPI token (MESSAGE command) using - // the established security context. - int decode_message (msg_t *msg_); + // Encode a per-message GSSAPI token (MESSAGE command) using + // the established security context. + int encode_message (msg_t *msg_); - // Convert ZMQ_GSSAPI_NT values to GSSAPI name_type - static const gss_OID convert_nametype (int zmq_name_type_); + // Decode a per-message GSSAPI token (MESSAGE command) using + // the established security context. + int decode_message (msg_t *msg_); - // Acquire security context credentials from the - // underlying mechanism. - static int acquire_credentials (char * principal_name_, - gss_cred_id_t * cred_, - gss_OID name_type_); + // Convert ZMQ_GSSAPI_NT values to GSSAPI name_type + static const gss_OID convert_nametype (int zmq_name_type_); - protected: - // Opaque GSSAPI token for outgoing data - gss_buffer_desc send_tok; + // Acquire security context credentials from the + // underlying mechanism. + static int acquire_credentials (char *principal_name_, + gss_cred_id_t *cred_, + gss_OID name_type_); - // Opaque GSSAPI token for incoming data - gss_buffer_desc recv_tok; + protected: + // Opaque GSSAPI token for outgoing data + gss_buffer_desc send_tok; - // Opaque GSSAPI representation of principal - gss_name_t target_name; + // Opaque GSSAPI token for incoming data + gss_buffer_desc recv_tok; - // Human-readable principal name - char * principal_name; + // Opaque GSSAPI representation of principal + gss_name_t target_name; - // Status code returned by GSSAPI functions - OM_uint32 maj_stat; + // Human-readable principal name + char *principal_name; - // Status code returned by the underlying mechanism - OM_uint32 min_stat; + // Status code returned by GSSAPI functions + OM_uint32 maj_stat; - // Status code returned by the underlying mechanism - // during context initialization - OM_uint32 init_sec_min_stat; + // Status code returned by the underlying mechanism + OM_uint32 min_stat; - // Flags returned by GSSAPI (ignored) - OM_uint32 ret_flags; + // Status code returned by the underlying mechanism + // during context initialization + OM_uint32 init_sec_min_stat; - // Flags returned by GSSAPI (ignored) - OM_uint32 gss_flags; + // Flags returned by GSSAPI (ignored) + OM_uint32 ret_flags; - // Credentials used to establish security context - gss_cred_id_t cred; + // Flags returned by GSSAPI (ignored) + OM_uint32 gss_flags; - // Opaque GSSAPI representation of the security context - gss_ctx_id_t context; + // Credentials used to establish security context + gss_cred_id_t cred; - // If true, use gss to encrypt messages. If false, only utilize gss for auth. - bool do_encryption; - }; + // Opaque GSSAPI representation of the security context + gss_ctx_id_t context; + // If true, use gss to encrypt messages. If false, only utilize gss for auth. + bool do_encryption; +}; } #endif diff --git a/src/gssapi_server.cpp b/src/gssapi_server.cpp index a45aaf35d8..0a43349a5b 100644 --- a/src/gssapi_server.cpp +++ b/src/gssapi_server.cpp @@ -54,12 +54,13 @@ zmq::gssapi_server_t::gssapi_server_t (session_base_t *session_, security_context_established (false) { maj_stat = GSS_S_CONTINUE_NEEDED; - if(!options_.gss_principal.empty()) - { - const std::string::size_type principal_size = options_.gss_principal.size(); - principal_name = static_cast (malloc(principal_size+1)); - assert(principal_name); - memcpy(principal_name, options_.gss_principal.c_str(), principal_size+1 ); + if (!options_.gss_principal.empty ()) { + const std::string::size_type principal_size = + options_.gss_principal.size (); + principal_name = static_cast (malloc (principal_size + 1)); + assert (principal_name); + memcpy (principal_name, options_.gss_principal.c_str (), + principal_size + 1); gss_OID name_type = convert_nametype (options_.gss_principal_nt); if (acquire_credentials (principal_name, &cred, name_type) != 0) maj_stat = GSS_S_FAILURE; @@ -68,17 +69,17 @@ zmq::gssapi_server_t::gssapi_server_t (session_base_t *session_, zmq::gssapi_server_t::~gssapi_server_t () { - if(cred) - gss_release_cred(&min_stat, &cred); + if (cred) + gss_release_cred (&min_stat, &cred); - if(target_name) - gss_release_name(&min_stat, &target_name); + if (target_name) + gss_release_name (&min_stat, &target_name); } int zmq::gssapi_server_t::next_handshake_command (msg_t *msg_) { if (state == send_ready) { - int rc = produce_ready(msg_); + int rc = produce_ready (msg_); if (rc == 0) state = recv_ready; @@ -108,7 +109,7 @@ int zmq::gssapi_server_t::next_handshake_command (msg_t *msg_) int zmq::gssapi_server_t::process_handshake_command (msg_t *msg_) { if (state == recv_ready) { - int rc = process_ready(msg_); + int rc = process_ready (msg_); if (rc == 0) state = connected; @@ -117,8 +118,7 @@ int zmq::gssapi_server_t::process_handshake_command (msg_t *msg_) if (state != recv_next_token) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; return -1; } @@ -138,7 +138,7 @@ int zmq::gssapi_server_t::process_handshake_command (msg_t *msg_) expecting_zap_reply = true; } } - state = expecting_zap_reply? expect_zap_reply: send_ready; + state = expecting_zap_reply ? expect_zap_reply : send_ready; return 0; } @@ -158,9 +158,9 @@ void zmq::gssapi_server_t::send_zap_request () { gss_buffer_desc principal; gss_display_name (&min_stat, target_name, &principal, NULL); - zap_client_t::send_zap_request ("GSSAPI", 6, - reinterpret_cast (principal.value), - principal.length); + zap_client_t::send_zap_request ( + "GSSAPI", 6, reinterpret_cast (principal.value), + principal.length); gss_release_buffer (&min_stat, &principal); } @@ -170,7 +170,7 @@ int zmq::gssapi_server_t::encode (msg_t *msg_) zmq_assert (state == connected); if (do_encryption) - return encode_message (msg_); + return encode_message (msg_); return 0; } @@ -180,7 +180,7 @@ int zmq::gssapi_server_t::decode (msg_t *msg_) zmq_assert (state == connected); if (do_encryption) - return decode_message (msg_); + return decode_message (msg_); return 0; } @@ -199,21 +199,21 @@ int zmq::gssapi_server_t::zap_msg_available () zmq::mechanism_t::status_t zmq::gssapi_server_t::status () const { - return state == connected? mechanism_t::ready: mechanism_t::handshaking; + return state == connected ? mechanism_t::ready : mechanism_t::handshaking; } int zmq::gssapi_server_t::produce_next_token (msg_t *msg_) { if (send_tok.length != 0) { // Client expects another token - if (produce_initiate(msg_, send_tok.value, send_tok.length) < 0) + if (produce_initiate (msg_, send_tok.value, send_tok.length) < 0) return -1; - gss_release_buffer(&min_stat, &send_tok); + gss_release_buffer (&min_stat, &send_tok); } if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED) { - gss_release_name(&min_stat, &target_name); + gss_release_name (&min_stat, &target_name); if (context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &context, GSS_C_NO_BUFFER); + gss_delete_sec_context (&min_stat, &context, GSS_C_NO_BUFFER); return -1; } @@ -223,9 +223,9 @@ int zmq::gssapi_server_t::produce_next_token (msg_t *msg_) int zmq::gssapi_server_t::process_next_token (msg_t *msg_) { if (maj_stat == GSS_S_CONTINUE_NEEDED) { - if (process_initiate(msg_, &recv_tok.value, recv_tok.length) < 0) { + if (process_initiate (msg_, &recv_tok.value, recv_tok.length) < 0) { if (target_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &target_name); + gss_release_name (&min_stat, &target_name); return -1; } } @@ -235,10 +235,9 @@ int zmq::gssapi_server_t::process_next_token (msg_t *msg_) void zmq::gssapi_server_t::accept_context () { - maj_stat = gss_accept_sec_context(&init_sec_min_stat, &context, cred, - &recv_tok, GSS_C_NO_CHANNEL_BINDINGS, - &target_name, &doid, &send_tok, - &ret_flags, NULL, NULL); + maj_stat = gss_accept_sec_context ( + &init_sec_min_stat, &context, cred, &recv_tok, GSS_C_NO_CHANNEL_BINDINGS, + &target_name, &doid, &send_tok, &ret_flags, NULL, NULL); if (recv_tok.value) { free (recv_tok.value); diff --git a/src/gssapi_server.hpp b/src/gssapi_server.hpp index d6fe4c8346..d4a0dd93be 100644 --- a/src/gssapi_server.hpp +++ b/src/gssapi_server.hpp @@ -37,57 +37,54 @@ namespace zmq { +class msg_t; +class session_base_t; - class msg_t; - class session_base_t; - - class gssapi_server_t - : public gssapi_mechanism_base_t, public zap_client_t +class gssapi_server_t : public gssapi_mechanism_base_t, public zap_client_t +{ + public: + gssapi_server_t (session_base_t *session_, + const std::string &peer_address, + const options_t &options_); + virtual ~gssapi_server_t (); + + // mechanism implementation + virtual int next_handshake_command (msg_t *msg_); + virtual int process_handshake_command (msg_t *msg_); + virtual int encode (msg_t *msg_); + virtual int decode (msg_t *msg_); + virtual int zap_msg_available (); + virtual status_t status () const; + + private: + enum state_t { - public: - gssapi_server_t (session_base_t *session_, - const std::string &peer_address, - const options_t &options_); - virtual ~gssapi_server_t (); - - // mechanism implementation - virtual int next_handshake_command (msg_t *msg_); - virtual int process_handshake_command (msg_t *msg_); - virtual int encode (msg_t *msg_); - virtual int decode (msg_t *msg_); - virtual int zap_msg_available (); - virtual status_t status () const; - - private: - - enum state_t { - send_next_token, - recv_next_token, - expect_zap_reply, - send_ready, - recv_ready, - connected - }; - - session_base_t * const session; - - const std::string peer_address; - - // Current FSM state - state_t state; - - // True iff server considers the client authenticated - bool security_context_established; - - // The underlying mechanism type (ignored) - gss_OID doid; - - void accept_context (); - int produce_next_token (msg_t *msg_); - int process_next_token (msg_t *msg_); - void send_zap_request (); + send_next_token, + recv_next_token, + expect_zap_reply, + send_ready, + recv_ready, + connected }; + session_base_t *const session; + + const std::string peer_address; + + // Current FSM state + state_t state; + + // True iff server considers the client authenticated + bool security_context_established; + + // The underlying mechanism type (ignored) + gss_OID doid; + + void accept_context (); + int produce_next_token (msg_t *msg_); + int process_next_token (msg_t *msg_); + void send_zap_request (); +}; } #endif diff --git a/src/i_decoder.hpp b/src/i_decoder.hpp index e23104993d..73d5601514 100644 --- a/src/i_decoder.hpp +++ b/src/i_decoder.hpp @@ -34,31 +34,27 @@ namespace zmq { +class msg_t; - class msg_t; +// Interface to be implemented by message decoder. - // Interface to be implemented by message decoder. - - class i_decoder - { - public: - virtual ~i_decoder () {} - - virtual void get_buffer (unsigned char **data_, size_t *size_) = 0; - - virtual void resize_buffer(size_t) = 0; - // Decodes data pointed to by data_. - // When a message is decoded, 1 is returned. - // When the decoder needs more data, 0 is returned. - // On error, -1 is returned and errno is set accordingly. - virtual int decode (const unsigned char *data_, size_t size_, - size_t &processed) = 0; - - virtual msg_t *msg () = 0; +class i_decoder +{ + public: + virtual ~i_decoder () {} + virtual void get_buffer (unsigned char **data_, size_t *size_) = 0; - }; + virtual void resize_buffer (size_t) = 0; + // Decodes data pointed to by data_. + // When a message is decoded, 1 is returned. + // When the decoder needs more data, 0 is returned. + // On error, -1 is returned and errno is set accordingly. + virtual int + decode (const unsigned char *data_, size_t size_, size_t &processed) = 0; + virtual msg_t *msg () = 0; +}; } #endif diff --git a/src/i_encoder.hpp b/src/i_encoder.hpp index 2d5cd258b9..c2efef1f82 100644 --- a/src/i_encoder.hpp +++ b/src/i_encoder.hpp @@ -34,27 +34,24 @@ namespace zmq { +// Forward declaration +class msg_t; - // Forward declaration - class msg_t; +// Interface to be implemented by message encoder. - // Interface to be implemented by message encoder. - - struct i_encoder - { - virtual ~i_encoder () {} - - // The function returns a batch of binary data. The data - // are filled to a supplied buffer. If no buffer is supplied (data_ - // is NULL) encoder will provide buffer of its own. - // Function returns 0 when a new message is required. - virtual size_t encode (unsigned char **data_, size_t size) = 0; - - // Load a new message into encoder. - virtual void load_msg (msg_t *msg_) = 0; +struct i_encoder +{ + virtual ~i_encoder () {} - }; + // The function returns a batch of binary data. The data + // are filled to a supplied buffer. If no buffer is supplied (data_ + // is NULL) encoder will provide buffer of its own. + // Function returns 0 when a new message is required. + virtual size_t encode (unsigned char **data_, size_t size) = 0; + // Load a new message into encoder. + virtual void load_msg (msg_t *msg_) = 0; +}; } #endif diff --git a/src/i_engine.hpp b/src/i_engine.hpp index 0897606d25..5e610468a6 100644 --- a/src/i_engine.hpp +++ b/src/i_engine.hpp @@ -32,37 +32,34 @@ namespace zmq { +class io_thread_t; - class io_thread_t; +// Abstract interface to be implemented by various engines. - // Abstract interface to be implemented by various engines. - - struct i_engine - { - virtual ~i_engine () {} - - // Plug the engine to the session. - virtual void plug (zmq::io_thread_t *io_thread_, - class session_base_t *session_) = 0; - - // Terminate and deallocate the engine. Note that 'detached' - // events are not fired on termination. - virtual void terminate () = 0; +struct i_engine +{ + virtual ~i_engine () {} - // This method is called by the session to signalise that more - // messages can be written to the pipe. - virtual void restart_input () = 0; + // Plug the engine to the session. + virtual void plug (zmq::io_thread_t *io_thread_, + class session_base_t *session_) = 0; - // This method is called by the session to signalise that there - // are messages to send available. - virtual void restart_output () = 0; + // Terminate and deallocate the engine. Note that 'detached' + // events are not fired on termination. + virtual void terminate () = 0; - virtual void zap_msg_available () = 0; + // This method is called by the session to signalise that more + // messages can be written to the pipe. + virtual void restart_input () = 0; - virtual const char * get_endpoint() const = 0; + // This method is called by the session to signalise that there + // are messages to send available. + virtual void restart_output () = 0; - }; + virtual void zap_msg_available () = 0; + virtual const char *get_endpoint () const = 0; +}; } #endif diff --git a/src/i_mailbox.hpp b/src/i_mailbox.hpp index 4c07a036ed..0e5c7d5f11 100644 --- a/src/i_mailbox.hpp +++ b/src/i_mailbox.hpp @@ -34,27 +34,24 @@ namespace zmq { - // Interface to be implemented by mailbox. +// Interface to be implemented by mailbox. - class i_mailbox - { - public: - virtual ~i_mailbox () {} +class i_mailbox +{ + public: + virtual ~i_mailbox () {} - virtual void send (const command_t &cmd_) = 0; - virtual int recv (command_t *cmd_, int timeout_) = 0; + virtual void send (const command_t &cmd_) = 0; + virtual int recv (command_t *cmd_, int timeout_) = 0; #ifdef HAVE_FORK - // close the file descriptors in the signaller. This is used in a forked - // child process to close the file descriptors so that they do not interfere - // with the context in the parent process. - virtual void forked () = 0; + // close the file descriptors in the signaller. This is used in a forked + // child process to close the file descriptors so that they do not interfere + // with the context in the parent process. + virtual void forked () = 0; #endif - - - }; - +}; } #endif diff --git a/src/i_poll_events.hpp b/src/i_poll_events.hpp index 1b28df8aed..e2536a169c 100644 --- a/src/i_poll_events.hpp +++ b/src/i_poll_events.hpp @@ -32,24 +32,22 @@ namespace zmq { +// Virtual interface to be exposed by object that want to be notified +// about events on file descriptors. - // Virtual interface to be exposed by object that want to be notified - // about events on file descriptors. - - struct i_poll_events - { - virtual ~i_poll_events () {} - - // Called by I/O thread when file descriptor is ready for reading. - virtual void in_event () = 0; +struct i_poll_events +{ + virtual ~i_poll_events () {} - // Called by I/O thread when file descriptor is ready for writing. - virtual void out_event () = 0; + // Called by I/O thread when file descriptor is ready for reading. + virtual void in_event () = 0; - // Called when timer expires. - virtual void timer_event (int id_) = 0; - }; + // Called by I/O thread when file descriptor is ready for writing. + virtual void out_event () = 0; + // Called when timer expires. + virtual void timer_event (int id_) = 0; +}; } #endif diff --git a/src/io_object.cpp b/src/io_object.cpp index 442d50bc92..992cd57733 100644 --- a/src/io_object.cpp +++ b/src/io_object.cpp @@ -32,8 +32,7 @@ #include "io_thread.hpp" #include "err.hpp" -zmq::io_object_t::io_object_t (io_thread_t *io_thread_) : - poller (NULL) +zmq::io_object_t::io_object_t (io_thread_t *io_thread_) : poller (NULL) { if (io_thread_) plug (io_thread_); diff --git a/src/io_object.hpp b/src/io_object.hpp index 1f6a33491a..b6a61a1797 100644 --- a/src/io_object.hpp +++ b/src/io_object.hpp @@ -38,52 +38,47 @@ namespace zmq { +class io_thread_t; - class io_thread_t; - - // Simple base class for objects that live in I/O threads. - // It makes communication with the poller object easier and - // makes defining unneeded event handlers unnecessary. - - class io_object_t : public i_poll_events - { - public: - - io_object_t (zmq::io_thread_t *io_thread_ = NULL); - ~io_object_t (); - - // When migrating an object from one I/O thread to another, first - // unplug it, then migrate it, then plug it to the new thread. - void plug (zmq::io_thread_t *io_thread_); - void unplug (); - - protected: - - typedef poller_t::handle_t handle_t; - - // Methods to access underlying poller object. - handle_t add_fd (fd_t fd_); - void rm_fd (handle_t handle_); - void set_pollin (handle_t handle_); - void reset_pollin (handle_t handle_); - void set_pollout (handle_t handle_); - void reset_pollout (handle_t handle_); - void add_timer (int timout_, int id_); - void cancel_timer (int id_); - - // i_poll_events interface implementation. - void in_event (); - void out_event (); - void timer_event (int id_); - - private: - - poller_t *poller; - - io_object_t (const io_object_t&); - const io_object_t &operator = (const io_object_t&); - }; +// Simple base class for objects that live in I/O threads. +// It makes communication with the poller object easier and +// makes defining unneeded event handlers unnecessary. +class io_object_t : public i_poll_events +{ + public: + io_object_t (zmq::io_thread_t *io_thread_ = NULL); + ~io_object_t (); + + // When migrating an object from one I/O thread to another, first + // unplug it, then migrate it, then plug it to the new thread. + void plug (zmq::io_thread_t *io_thread_); + void unplug (); + + protected: + typedef poller_t::handle_t handle_t; + + // Methods to access underlying poller object. + handle_t add_fd (fd_t fd_); + void rm_fd (handle_t handle_); + void set_pollin (handle_t handle_); + void reset_pollin (handle_t handle_); + void set_pollout (handle_t handle_); + void reset_pollout (handle_t handle_); + void add_timer (int timout_, int id_); + void cancel_timer (int id_); + + // i_poll_events interface implementation. + void in_event (); + void out_event (); + void timer_event (int id_); + + private: + poller_t *poller; + + io_object_t (const io_object_t &); + const io_object_t &operator= (const io_object_t &); +}; } #endif diff --git a/src/io_thread.cpp b/src/io_thread.cpp index 35635ca2f1..4b25bc3468 100644 --- a/src/io_thread.cpp +++ b/src/io_thread.cpp @@ -51,7 +51,7 @@ zmq::io_thread_t::io_thread_t (ctx_t *ctx_, uint32_t tid_) : zmq::io_thread_t::~io_thread_t () { - LIBZMQ_DELETE(poller); + LIBZMQ_DELETE (poller); } void zmq::io_thread_t::start () diff --git a/src/io_thread.hpp b/src/io_thread.hpp index 880bedbc09..08fd67c58d 100644 --- a/src/io_thread.hpp +++ b/src/io_thread.hpp @@ -40,60 +40,56 @@ namespace zmq { +class ctx_t; - class ctx_t; +// Generic part of the I/O thread. Polling-mechanism-specific features +// are implemented in separate "polling objects". - // Generic part of the I/O thread. Polling-mechanism-specific features - // are implemented in separate "polling objects". - - class io_thread_t : public object_t, public i_poll_events - { - public: - - io_thread_t (zmq::ctx_t *ctx_, uint32_t tid_); - - // Clean-up. If the thread was started, it's necessary to call 'stop' - // before invoking destructor. Otherwise the destructor would hang up. - ~io_thread_t (); - - // Launch the physical thread. - void start (); +class io_thread_t : public object_t, public i_poll_events +{ + public: + io_thread_t (zmq::ctx_t *ctx_, uint32_t tid_); - // Ask underlying thread to stop. - void stop (); + // Clean-up. If the thread was started, it's necessary to call 'stop' + // before invoking destructor. Otherwise the destructor would hang up. + ~io_thread_t (); - // Returns mailbox associated with this I/O thread. - mailbox_t *get_mailbox (); + // Launch the physical thread. + void start (); - // i_poll_events implementation. - void in_event (); - void out_event (); - void timer_event (int id_); + // Ask underlying thread to stop. + void stop (); - // Used by io_objects to retrieve the associated poller object. - poller_t *get_poller (); + // Returns mailbox associated with this I/O thread. + mailbox_t *get_mailbox (); - // Command handlers. - void process_stop (); + // i_poll_events implementation. + void in_event (); + void out_event (); + void timer_event (int id_); - // Returns load experienced by the I/O thread. - int get_load (); + // Used by io_objects to retrieve the associated poller object. + poller_t *get_poller (); - private: + // Command handlers. + void process_stop (); - // I/O thread accesses incoming commands via this mailbox. - mailbox_t mailbox; + // Returns load experienced by the I/O thread. + int get_load (); - // Handle associated with mailbox' file descriptor. - poller_t::handle_t mailbox_handle; + private: + // I/O thread accesses incoming commands via this mailbox. + mailbox_t mailbox; - // I/O multiplexing is performed using a poller object. - poller_t *poller; + // Handle associated with mailbox' file descriptor. + poller_t::handle_t mailbox_handle; - io_thread_t (const io_thread_t&); - const io_thread_t &operator = (const io_thread_t&); - }; + // I/O multiplexing is performed using a poller object. + poller_t *poller; + io_thread_t (const io_thread_t &); + const io_thread_t &operator= (const io_thread_t &); +}; } #endif diff --git a/src/ip.cpp b/src/ip.cpp index f9c5e5dee1..c2a8f8a2fb 100644 --- a/src/ip.cpp +++ b/src/ip.cpp @@ -64,9 +64,9 @@ zmq::fd_t zmq::open_socket (int domain_, int type_, int protocol_) return -1; #endif - // If there's no SOCK_CLOEXEC, let's try the second best option. Note that - // race condition can cause socket not to be closed (if fork happens - // between socket creation and this point). + // If there's no SOCK_CLOEXEC, let's try the second best option. Note that + // race condition can cause socket not to be closed (if fork happens + // between socket creation and this point). #if !defined ZMQ_HAVE_SOCK_CLOEXEC && defined FD_CLOEXEC rc = fcntl (s, F_SETFD, FD_CLOEXEC); errno_assert (rc != -1); @@ -106,7 +106,7 @@ void zmq::unblock_socket (fd_t s_) void zmq::enable_ipv4_mapping (fd_t s_) { - (void) s_; + (void) s_; #if defined IPV6_V6ONLY && !defined ZMQ_HAVE_OPENBSD #ifdef ZMQ_HAVE_WINDOWS @@ -114,8 +114,8 @@ void zmq::enable_ipv4_mapping (fd_t s_) #else int flag = 0; #endif - int rc = setsockopt (s_, IPPROTO_IPV6, IPV6_V6ONLY, (const char*) &flag, - sizeof (flag)); + int rc = setsockopt (s_, IPPROTO_IPV6, IPV6_V6ONLY, (const char *) &flag, + sizeof (flag)); #ifdef ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); #else @@ -130,38 +130,36 @@ int zmq::get_peer_ip_address (fd_t sockfd_, std::string &ip_addr_) struct sockaddr_storage ss; #if defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_WINDOWS - int addrlen = static_cast (sizeof ss); + int addrlen = static_cast (sizeof ss); #else socklen_t addrlen = sizeof ss; #endif - rc = getpeername (sockfd_, (struct sockaddr*) &ss, &addrlen); + rc = getpeername (sockfd_, (struct sockaddr *) &ss, &addrlen); #ifdef ZMQ_HAVE_WINDOWS if (rc == SOCKET_ERROR) { - const int last_error = WSAGetLastError(); - wsa_assert (last_error != WSANOTINITIALISED && - last_error != WSAEFAULT && - last_error != WSAEINPROGRESS && - last_error != WSAENOTSOCK); + const int last_error = WSAGetLastError (); + wsa_assert (last_error != WSANOTINITIALISED && last_error != WSAEFAULT + && last_error != WSAEINPROGRESS + && last_error != WSAENOTSOCK); return 0; } #else if (rc == -1) { - errno_assert (errno != EBADF && - errno != EFAULT && - errno != ENOTSOCK); + errno_assert (errno != EBADF && errno != EFAULT && errno != ENOTSOCK); return 0; } #endif - char host [NI_MAXHOST]; - rc = getnameinfo ((struct sockaddr*) &ss, addrlen, host, sizeof host, - NULL, 0, NI_NUMERICHOST); + char host[NI_MAXHOST]; + rc = getnameinfo ((struct sockaddr *) &ss, addrlen, host, sizeof host, NULL, + 0, NI_NUMERICHOST); if (rc != 0) return 0; ip_addr_ = host; - union { + union + { struct sockaddr sa; struct sockaddr_storage sa_stor; } u; @@ -172,7 +170,9 @@ int zmq::get_peer_ip_address (fd_t sockfd_, std::string &ip_addr_) void zmq::set_ip_type_of_service (fd_t s_, int iptos) { - int rc = setsockopt(s_, IPPROTO_IP, IP_TOS, reinterpret_cast(&iptos), sizeof(iptos)); + int rc = + setsockopt (s_, IPPROTO_IP, IP_TOS, + reinterpret_cast (&iptos), sizeof (iptos)); #ifdef ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); @@ -181,19 +181,14 @@ void zmq::set_ip_type_of_service (fd_t s_, int iptos) #endif // Windows and Hurd do not support IPV6_TCLASS -#if !defined (ZMQ_HAVE_WINDOWS) && defined (IPV6_TCLASS) - rc = setsockopt( - s_, - IPPROTO_IPV6, - IPV6_TCLASS, - reinterpret_cast(&iptos), - sizeof(iptos)); +#if !defined(ZMQ_HAVE_WINDOWS) && defined(IPV6_TCLASS) + rc = setsockopt (s_, IPPROTO_IPV6, IPV6_TCLASS, + reinterpret_cast (&iptos), sizeof (iptos)); // If IPv6 is not enabled ENOPROTOOPT will be returned on Linux and // EINVAL on OSX if (rc == -1) { - errno_assert (errno == ENOPROTOOPT || - errno == EINVAL); + errno_assert (errno == ENOPROTOOPT || errno == EINVAL); } #endif } @@ -221,7 +216,8 @@ int zmq::set_nosigpipe (fd_t s_) void zmq::bind_to_device (fd_t s_, std::string &bound_device_) { #ifdef ZMQ_HAVE_SO_BINDTODEVICE - int rc = setsockopt(s_, SOL_SOCKET, SO_BINDTODEVICE, bound_device_.c_str (), bound_device_.length ()); + int rc = setsockopt (s_, SOL_SOCKET, SO_BINDTODEVICE, + bound_device_.c_str (), bound_device_.length ()); #ifdef ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); diff --git a/src/ip.hpp b/src/ip.hpp index 5c718189cb..19cd186b0c 100644 --- a/src/ip.hpp +++ b/src/ip.hpp @@ -35,30 +35,28 @@ namespace zmq { +// Same as socket(2), but allows for transparent tweaking the options. +fd_t open_socket (int domain_, int type_, int protocol_); - // Same as socket(2), but allows for transparent tweaking the options. - fd_t open_socket (int domain_, int type_, int protocol_); +// Sets the socket into non-blocking mode. +void unblock_socket (fd_t s_); - // Sets the socket into non-blocking mode. - void unblock_socket (fd_t s_); +// Enable IPv4-mapping of addresses in case it is disabled by default. +void enable_ipv4_mapping (fd_t s_); - // Enable IPv4-mapping of addresses in case it is disabled by default. - void enable_ipv4_mapping (fd_t s_); +// Returns string representation of peer's address. +// Socket sockfd_ must be connected. Returns true iff successful. +int get_peer_ip_address (fd_t sockfd_, std::string &ip_addr_); - // Returns string representation of peer's address. - // Socket sockfd_ must be connected. Returns true iff successful. - int get_peer_ip_address (fd_t sockfd_, std::string &ip_addr_); +// Sets the IP Type-Of-Service for the underlying socket +void set_ip_type_of_service (fd_t s_, int iptos); - // Sets the IP Type-Of-Service for the underlying socket - void set_ip_type_of_service (fd_t s_, int iptos); - - // Sets the SO_NOSIGPIPE option for the underlying socket. - // Return 0 on success, -1 if the connection has been closed by the peer - int set_nosigpipe (fd_t s_); - - // Binds the underlying socket to the given device, eg. VRF or interface - void bind_to_device (fd_t s_, std::string &bound_device_); +// Sets the SO_NOSIGPIPE option for the underlying socket. +// Return 0 on success, -1 if the connection has been closed by the peer +int set_nosigpipe (fd_t s_); +// Binds the underlying socket to the given device, eg. VRF or interface +void bind_to_device (fd_t s_, std::string &bound_device_); } #endif diff --git a/src/ipc_address.cpp b/src/ipc_address.cpp index 137ee84959..a26d519b52 100644 --- a/src/ipc_address.cpp +++ b/src/ipc_address.cpp @@ -48,7 +48,7 @@ zmq::ipc_address_t::ipc_address_t (const sockaddr *sa, socklen_t sa_len) memset (&address, 0, sizeof address); if (sa->sa_family == AF_UNIX) - memcpy(&address, sa, sa_len); + memcpy (&address, sa, sa_len); } zmq::ipc_address_t::~ipc_address_t () @@ -61,7 +61,7 @@ int zmq::ipc_address_t::resolve (const char *path_) errno = ENAMETOOLONG; return -1; } - if (path_ [0] == '@' && !path_ [1]) { + if (path_[0] == '@' && !path_[1]) { errno = EINVAL; return -1; } @@ -69,7 +69,7 @@ int zmq::ipc_address_t::resolve (const char *path_) address.sun_family = AF_UNIX; strcpy (address.sun_path, path_); /* Abstract sockets start with '\0' */ - if (path_ [0] == '@') + if (path_[0] == '@') *address.sun_path = '\0'; return 0; } @@ -83,23 +83,24 @@ int zmq::ipc_address_t::to_string (std::string &addr_) std::stringstream s; s << "ipc://"; - if (!address.sun_path [0] && address.sun_path [1]) - s << "@" << address.sun_path + 1; + if (!address.sun_path[0] && address.sun_path[1]) + s << "@" << address.sun_path + 1; else - s << address.sun_path; + s << address.sun_path; addr_ = s.str (); return 0; } const sockaddr *zmq::ipc_address_t::addr () const { - return (sockaddr*) &address; + return (sockaddr *) &address; } socklen_t zmq::ipc_address_t::addrlen () const { - if (!address.sun_path [0] && address.sun_path [1]) - return (socklen_t) strlen (address.sun_path + 1) + sizeof (sa_family_t) + 1; + if (!address.sun_path[0] && address.sun_path[1]) + return (socklen_t) strlen (address.sun_path + 1) + sizeof (sa_family_t) + + 1; return (socklen_t) sizeof address; } diff --git a/src/ipc_address.hpp b/src/ipc_address.hpp index a77b0d58b6..e6ce271aa6 100644 --- a/src/ipc_address.hpp +++ b/src/ipc_address.hpp @@ -39,36 +39,30 @@ namespace zmq { +class ipc_address_t +{ + public: + ipc_address_t (); + ipc_address_t (const sockaddr *sa, socklen_t sa_len); + ~ipc_address_t (); - class ipc_address_t - { - public: - - ipc_address_t (); - ipc_address_t (const sockaddr *sa, socklen_t sa_len); - ~ipc_address_t (); - - // This function sets up the address for UNIX domain transport. - int resolve (const char *path_); - - // The opposite to resolve() - int to_string (std::string &addr_); - - const sockaddr *addr () const; - socklen_t addrlen () const; + // This function sets up the address for UNIX domain transport. + int resolve (const char *path_); - private: + // The opposite to resolve() + int to_string (std::string &addr_); - struct sockaddr_un address; + const sockaddr *addr () const; + socklen_t addrlen () const; - ipc_address_t (const ipc_address_t&); - const ipc_address_t &operator = (const ipc_address_t&); - }; + private: + struct sockaddr_un address; + ipc_address_t (const ipc_address_t &); + const ipc_address_t &operator= (const ipc_address_t &); +}; } #endif #endif - - diff --git a/src/ipc_connecter.cpp b/src/ipc_connecter.cpp index 48793e8c4a..7ec3538129 100644 --- a/src/ipc_connecter.cpp +++ b/src/ipc_connecter.cpp @@ -50,8 +50,10 @@ #include zmq::ipc_connecter_t::ipc_connecter_t (class io_thread_t *io_thread_, - class session_base_t *session_, const options_t &options_, - const address_t *addr_, bool delayed_start_) : + class session_base_t *session_, + const options_t &options_, + const address_t *addr_, + bool delayed_start_) : own_t (io_thread_, options_), io_object_t (io_thread_), addr (addr_), @@ -60,12 +62,12 @@ zmq::ipc_connecter_t::ipc_connecter_t (class io_thread_t *io_thread_, delayed_start (delayed_start_), timer_started (false), session (session_), - current_reconnect_ivl(options.reconnect_ivl) + current_reconnect_ivl (options.reconnect_ivl) { zmq_assert (addr); zmq_assert (addr->protocol == "ipc"); addr->to_string (endpoint); - socket = session-> get_socket(); + socket = session->get_socket (); } zmq::ipc_connecter_t::~ipc_connecter_t () @@ -118,12 +120,12 @@ void zmq::ipc_connecter_t::out_event () // Handle the error condition by attempt to reconnect. if (fd == retired_fd) { close (); - add_reconnect_timer(); + add_reconnect_timer (); return; } // Create the engine object for this connection. - stream_engine_t *engine = new (std::nothrow) - stream_engine_t (fd, options, endpoint); + stream_engine_t *engine = + new (std::nothrow) stream_engine_t (fd, options, endpoint); alloc_assert (engine); // Attach the engine to the corresponding session object. @@ -155,12 +157,11 @@ void zmq::ipc_connecter_t::start_connecting () } // Connection establishment may be delayed. Poll for its completion. - else - if (rc == -1 && errno == EINPROGRESS) { + else if (rc == -1 && errno == EINPROGRESS) { handle = add_fd (s); handle_valid = true; set_pollout (handle); - socket->event_connect_delayed (endpoint, zmq_errno()); + socket->event_connect_delayed (endpoint, zmq_errno ()); } // Handle any other error condition by eventual reconnect. @@ -171,9 +172,9 @@ void zmq::ipc_connecter_t::start_connecting () } } -void zmq::ipc_connecter_t::add_reconnect_timer() +void zmq::ipc_connecter_t::add_reconnect_timer () { - int rc_ivl = get_new_reconnect_ivl(); + int rc_ivl = get_new_reconnect_ivl (); add_timer (rc_ivl, reconnect_timer_id); socket->event_connect_retried (endpoint, rc_ivl); timer_started = true; @@ -182,17 +183,16 @@ void zmq::ipc_connecter_t::add_reconnect_timer() int zmq::ipc_connecter_t::get_new_reconnect_ivl () { // The new interval is the current interval + random value. - int this_interval = current_reconnect_ivl + - (generate_random () % options.reconnect_ivl); + int this_interval = + current_reconnect_ivl + (generate_random () % options.reconnect_ivl); // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. - if (options.reconnect_ivl_max > 0 && - options.reconnect_ivl_max > options.reconnect_ivl) { - + if (options.reconnect_ivl_max > 0 + && options.reconnect_ivl_max > options.reconnect_ivl) { // Calculate the next interval current_reconnect_ivl = current_reconnect_ivl * 2; - if(current_reconnect_ivl >= options.reconnect_ivl_max) { + if (current_reconnect_ivl >= options.reconnect_ivl_max) { current_reconnect_ivl = options.reconnect_ivl_max; } } @@ -212,9 +212,8 @@ int zmq::ipc_connecter_t::open () unblock_socket (s); // Connect to the remote peer. - int rc = ::connect ( - s, addr->resolved.ipc_addr->addr (), - addr->resolved.ipc_addr->addrlen ()); + int rc = ::connect (s, addr->resolved.ipc_addr->addr (), + addr->resolved.ipc_addr->addrlen ()); // Connect was successful immediately. if (rc == 0) @@ -251,20 +250,19 @@ zmq::fd_t zmq::ipc_connecter_t::connect () #else socklen_t len = sizeof (err); #endif - int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char*) &err, &len); + int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char *) &err, &len); if (rc == -1) { if (errno == ENOPROTOOPT) errno = 0; err = errno; } if (err != 0) { - // Assert if the error was caused by 0MQ bug. // Networking problems are OK. No need to assert. errno = err; - errno_assert (errno == ECONNREFUSED || errno == ECONNRESET || - errno == ETIMEDOUT || errno == EHOSTUNREACH || - errno == ENETUNREACH || errno == ENETDOWN); + errno_assert (errno == ECONNREFUSED || errno == ECONNRESET + || errno == ETIMEDOUT || errno == EHOSTUNREACH + || errno == ENETUNREACH || errno == ENETDOWN); return retired_fd; } @@ -275,4 +273,3 @@ zmq::fd_t zmq::ipc_connecter_t::connect () } #endif - diff --git a/src/ipc_connecter.hpp b/src/ipc_connecter.hpp index 6149d626e2..1506d3c2c0 100644 --- a/src/ipc_connecter.hpp +++ b/src/ipc_connecter.hpp @@ -39,97 +39,97 @@ namespace zmq { +class io_thread_t; +class session_base_t; +struct address_t; - class io_thread_t; - class session_base_t; - struct address_t; - - class ipc_connecter_t : public own_t, public io_object_t +class ipc_connecter_t : public own_t, public io_object_t +{ + public: + // If 'delayed_start' is true connecter first waits for a while, + // then starts connection process. + ipc_connecter_t (zmq::io_thread_t *io_thread_, + zmq::session_base_t *session_, + const options_t &options_, + const address_t *addr_, + bool delayed_start_); + ~ipc_connecter_t (); + + private: + // ID of the timer used to delay the reconnection. + enum { - public: - - // If 'delayed_start' is true connecter first waits for a while, - // then starts connection process. - ipc_connecter_t (zmq::io_thread_t *io_thread_, - zmq::session_base_t *session_, const options_t &options_, - const address_t *addr_, bool delayed_start_); - ~ipc_connecter_t (); - - private: - - // ID of the timer used to delay the reconnection. - enum {reconnect_timer_id = 1}; - - // Handlers for incoming commands. - void process_plug (); - void process_term (int linger_); + reconnect_timer_id = 1 + }; - // Handlers for I/O events. - void in_event (); - void out_event (); - void timer_event (int id_); + // Handlers for incoming commands. + void process_plug (); + void process_term (int linger_); - // Internal function to start the actual connection establishment. - void start_connecting (); + // Handlers for I/O events. + void in_event (); + void out_event (); + void timer_event (int id_); - // Internal function to add a reconnect timer - void add_reconnect_timer(); + // Internal function to start the actual connection establishment. + void start_connecting (); - // Internal function to return a reconnect backoff delay. - // Will modify the current_reconnect_ivl used for next call - // Returns the currently used interval - int get_new_reconnect_ivl (); + // Internal function to add a reconnect timer + void add_reconnect_timer (); - // Open IPC connecting socket. Returns -1 in case of error, - // 0 if connect was successful immediately. Returns -1 with - // EAGAIN errno if async connect was launched. - int open (); + // Internal function to return a reconnect backoff delay. + // Will modify the current_reconnect_ivl used for next call + // Returns the currently used interval + int get_new_reconnect_ivl (); - // Close the connecting socket. - int close (); + // Open IPC connecting socket. Returns -1 in case of error, + // 0 if connect was successful immediately. Returns -1 with + // EAGAIN errno if async connect was launched. + int open (); - // Get the file descriptor of newly created connection. Returns - // retired_fd if the connection was unsuccessful. - fd_t connect (); + // Close the connecting socket. + int close (); - // Address to connect to. Owned by session_base_t. - const address_t *addr; + // Get the file descriptor of newly created connection. Returns + // retired_fd if the connection was unsuccessful. + fd_t connect (); - // Underlying socket. - fd_t s; + // Address to connect to. Owned by session_base_t. + const address_t *addr; - // Handle corresponding to the listening socket. - handle_t handle; + // Underlying socket. + fd_t s; - // If true file descriptor is registered with the poller and 'handle' - // contains valid value. - bool handle_valid; + // Handle corresponding to the listening socket. + handle_t handle; - // If true, connecter is waiting a while before trying to connect. - const bool delayed_start; + // If true file descriptor is registered with the poller and 'handle' + // contains valid value. + bool handle_valid; - // True iff a timer has been started. - bool timer_started; + // If true, connecter is waiting a while before trying to connect. + const bool delayed_start; - // Reference to the session we belong to. - zmq::session_base_t *session; + // True iff a timer has been started. + bool timer_started; - // Current reconnect ivl, updated for backoff strategy - int current_reconnect_ivl; + // Reference to the session we belong to. + zmq::session_base_t *session; - // String representation of endpoint to connect to - std::string endpoint; + // Current reconnect ivl, updated for backoff strategy + int current_reconnect_ivl; - // Socket - zmq::socket_base_t *socket; + // String representation of endpoint to connect to + std::string endpoint; - ipc_connecter_t (const ipc_connecter_t&); - const ipc_connecter_t &operator = (const ipc_connecter_t&); - }; + // Socket + zmq::socket_base_t *socket; + ipc_connecter_t (const ipc_connecter_t &); + const ipc_connecter_t &operator= (const ipc_connecter_t &); +}; } #endif #endif - diff --git a/src/ipc_listener.cpp b/src/ipc_listener.cpp index 40e9ecba61..3a6881220a 100644 --- a/src/ipc_listener.cpp +++ b/src/ipc_listener.cpp @@ -52,42 +52,41 @@ #include #ifdef ZMQ_HAVE_LOCAL_PEERCRED -# include -# include +#include +#include #endif #ifdef ZMQ_HAVE_SO_PEERCRED -# include -# include -# include -# if defined ZMQ_HAVE_OPENBSD -# define ucred sockpeercred -# endif +#include +#include +#include +#if defined ZMQ_HAVE_OPENBSD +#define ucred sockpeercred +#endif #endif const char *zmq::ipc_listener_t::tmp_env_vars[] = { - "TMPDIR", - "TEMPDIR", - "TMP", - 0 // Sentinel + "TMPDIR", "TEMPDIR", "TMP", + 0 // Sentinel }; -int zmq::ipc_listener_t::create_wildcard_address(std::string& path_, - std::string& file_) +int zmq::ipc_listener_t::create_wildcard_address (std::string &path_, + std::string &file_) { std::string tmp_path; // If TMPDIR, TEMPDIR, or TMP are available and are directories, create // the socket directory there. const char **tmp_env = tmp_env_vars; - while ( tmp_path.empty() && *tmp_env != 0 ) { - char *tmpdir = getenv(*tmp_env); + while (tmp_path.empty () && *tmp_env != 0) { + char *tmpdir = getenv (*tmp_env); struct stat statbuf; // Confirm it is actually a directory before trying to use - if ( tmpdir != 0 && ::stat(tmpdir, &statbuf) == 0 && S_ISDIR(statbuf.st_mode) ) { - tmp_path.assign(tmpdir); - if ( *(tmp_path.rbegin()) != '/' ) { - tmp_path.push_back('/'); + if (tmpdir != 0 && ::stat (tmpdir, &statbuf) == 0 + && S_ISDIR (statbuf.st_mode)) { + tmp_path.assign (tmpdir); + if (*(tmp_path.rbegin ()) != '/') { + tmp_path.push_back ('/'); } } @@ -96,10 +95,10 @@ int zmq::ipc_listener_t::create_wildcard_address(std::string& path_, } // Append a directory name - tmp_path.append("tmpXXXXXX"); + tmp_path.append ("tmpXXXXXX"); // We need room for tmp_path + trailing NUL - std::vector buffer(tmp_path.length()+1); + std::vector buffer (tmp_path.length () + 1); strcpy (&buffer[0], tmp_path.c_str ()); #ifdef HAVE_MKDTEMP @@ -121,7 +120,7 @@ int zmq::ipc_listener_t::create_wildcard_address(std::string& path_, (void) path_; int fd = mkstemp (&buffer[0]); if (fd == -1) - return -1; + return -1; ::close (fd); file_.assign (&buffer[0]); @@ -131,7 +130,8 @@ int zmq::ipc_listener_t::create_wildcard_address(std::string& path_, } zmq::ipc_listener_t::ipc_listener_t (io_thread_t *io_thread_, - socket_base_t *socket_, const options_t &options_) : + socket_base_t *socket_, + const options_t &options_) : own_t (io_thread_, options_), io_object_t (io_thread_), has_file (false), @@ -166,13 +166,13 @@ void zmq::ipc_listener_t::in_event () // If connection was reset by the peer in the meantime, just ignore it. // TODO: Handle specific errors like ENFILE/EMFILE etc. if (fd == retired_fd) { - socket->event_accept_failed (endpoint, zmq_errno()); + socket->event_accept_failed (endpoint, zmq_errno ()); return; } // Create the engine object for this connection. - stream_engine_t *engine = new (std::nothrow) - stream_engine_t (fd, options, endpoint); + stream_engine_t *engine = + new (std::nothrow) stream_engine_t (fd, options, endpoint); alloc_assert (engine); // Choose I/O thread to run connecter in. Given that we are already @@ -181,8 +181,8 @@ void zmq::ipc_listener_t::in_event () zmq_assert (io_thread); // Create and launch a session object. - session_base_t *session = session_base_t::create (io_thread, false, socket, - options, NULL); + session_base_t *session = + session_base_t::create (io_thread, false, socket, options, NULL); errno_assert (session); session->inc_seqnum (); launch_child (session); @@ -214,8 +214,8 @@ int zmq::ipc_listener_t::set_address (const char *addr_) std::string addr (addr_); // Allow wildcard file - if (options.use_fd == -1 && addr [0] == '*') { - if ( create_wildcard_address(tmp_socket_dirname, addr) < 0 ) { + if (options.use_fd == -1 && addr[0] == '*') { + if (create_wildcard_address (tmp_socket_dirname, addr) < 0) { return -1; } } @@ -226,19 +226,19 @@ int zmq::ipc_listener_t::set_address (const char *addr_) // working after the first client connects. The user will take care of // cleaning up the file after the service is stopped. if (options.use_fd == -1) { - ::unlink (addr.c_str()); + ::unlink (addr.c_str ()); } filename.clear (); // Initialise the address structure. ipc_address_t address; - int rc = address.resolve (addr.c_str()); + int rc = address.resolve (addr.c_str ()); if (rc != 0) { - if ( !tmp_socket_dirname.empty() ) { + if (!tmp_socket_dirname.empty ()) { // We need to preserve errno to return to the user int errno_ = errno; - ::rmdir(tmp_socket_dirname.c_str ()); - tmp_socket_dirname.clear(); + ::rmdir (tmp_socket_dirname.c_str ()); + tmp_socket_dirname.clear (); errno = errno_; } return -1; @@ -252,11 +252,11 @@ int zmq::ipc_listener_t::set_address (const char *addr_) // Create a listening socket. s = open_socket (AF_UNIX, SOCK_STREAM, 0); if (s == -1) { - if ( !tmp_socket_dirname.empty() ) { + if (!tmp_socket_dirname.empty ()) { // We need to preserve errno to return to the user int errno_ = errno; - ::rmdir(tmp_socket_dirname.c_str ()); - tmp_socket_dirname.clear(); + ::rmdir (tmp_socket_dirname.c_str ()); + tmp_socket_dirname.clear (); errno = errno_; } return -1; @@ -273,7 +273,7 @@ int zmq::ipc_listener_t::set_address (const char *addr_) goto error; } - filename.assign (addr.c_str()); + filename.assign (addr.c_str ()); has_file = true; socket->event_listening (endpoint, s); @@ -298,13 +298,13 @@ int zmq::ipc_listener_t::close () if (has_file && options.use_fd == -1) { rc = 0; - if ( rc == 0 && !tmp_socket_dirname.empty() ) { - rc = ::rmdir(tmp_socket_dirname.c_str ()); - tmp_socket_dirname.clear(); + if (rc == 0 && !tmp_socket_dirname.empty ()) { + rc = ::rmdir (tmp_socket_dirname.c_str ()); + tmp_socket_dirname.clear (); } if (rc != 0) { - socket->event_close_failed (endpoint, zmq_errno()); + socket->event_close_failed (endpoint, zmq_errno ()); return -1; } } @@ -317,9 +317,9 @@ int zmq::ipc_listener_t::close () bool zmq::ipc_listener_t::filter (fd_t sock) { - if (options.ipc_uid_accept_filters.empty () && - options.ipc_pid_accept_filters.empty () && - options.ipc_gid_accept_filters.empty ()) + if (options.ipc_uid_accept_filters.empty () + && options.ipc_pid_accept_filters.empty () + && options.ipc_gid_accept_filters.empty ()) return true; struct ucred cred; @@ -327,9 +327,12 @@ bool zmq::ipc_listener_t::filter (fd_t sock) if (getsockopt (sock, SOL_SOCKET, SO_PEERCRED, &cred, &size)) return false; - if (options.ipc_uid_accept_filters.find (cred.uid) != options.ipc_uid_accept_filters.end () || - options.ipc_gid_accept_filters.find (cred.gid) != options.ipc_gid_accept_filters.end () || - options.ipc_pid_accept_filters.find (cred.pid) != options.ipc_pid_accept_filters.end ()) + if (options.ipc_uid_accept_filters.find (cred.uid) + != options.ipc_uid_accept_filters.end () + || options.ipc_gid_accept_filters.find (cred.gid) + != options.ipc_gid_accept_filters.end () + || options.ipc_pid_accept_filters.find (cred.pid) + != options.ipc_pid_accept_filters.end ()) return true; struct passwd *pw; @@ -337,8 +340,9 @@ bool zmq::ipc_listener_t::filter (fd_t sock) if (!(pw = getpwuid (cred.uid))) return false; - for (options_t::ipc_gid_accept_filters_t::const_iterator it = options.ipc_gid_accept_filters.begin (); - it != options.ipc_gid_accept_filters.end (); it++) { + for (options_t::ipc_gid_accept_filters_t::const_iterator it = + options.ipc_gid_accept_filters.begin (); + it != options.ipc_gid_accept_filters.end (); it++) { if (!(gr = getgrgid (*it))) continue; for (char **mem = gr->gr_mem; *mem; mem++) { @@ -353,8 +357,8 @@ bool zmq::ipc_listener_t::filter (fd_t sock) bool zmq::ipc_listener_t::filter (fd_t sock) { - if (options.ipc_uid_accept_filters.empty () && - options.ipc_gid_accept_filters.empty ()) + if (options.ipc_uid_accept_filters.empty () + && options.ipc_gid_accept_filters.empty ()) return true; struct xucred cred; @@ -364,10 +368,12 @@ bool zmq::ipc_listener_t::filter (fd_t sock) return false; if (cred.cr_version != XUCRED_VERSION) return false; - if (options.ipc_uid_accept_filters.find (cred.cr_uid) != options.ipc_uid_accept_filters.end ()) + if (options.ipc_uid_accept_filters.find (cred.cr_uid) + != options.ipc_uid_accept_filters.end ()) return true; for (int i = 0; i < cred.cr_ngroups; i++) { - if (options.ipc_gid_accept_filters.find (cred.cr_groups[i]) != options.ipc_gid_accept_filters.end ()) + if (options.ipc_gid_accept_filters.find (cred.cr_groups[i]) + != options.ipc_gid_accept_filters.end ()) return true; } @@ -388,13 +394,14 @@ zmq::fd_t zmq::ipc_listener_t::accept () fd_t sock = ::accept (s, NULL, NULL); #endif if (sock == -1) { - errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || - errno == EINTR || errno == ECONNABORTED || errno == EPROTO || - errno == ENFILE); + errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR + || errno == ECONNABORTED || errno == EPROTO + || errno == ENFILE); return retired_fd; } -#if (!defined ZMQ_HAVE_SOCK_CLOEXEC || !defined HAVE_ACCEPT4) && defined FD_CLOEXEC +#if (!defined ZMQ_HAVE_SOCK_CLOEXEC || !defined HAVE_ACCEPT4) \ + && defined FD_CLOEXEC // Race condition can cause socket not to be closed (if fork happens // between accept and this point). int rc = fcntl (sock, F_SETFD, FD_CLOEXEC); diff --git a/src/ipc_listener.hpp b/src/ipc_listener.hpp index 29d808e045..4c5d53c504 100644 --- a/src/ipc_listener.hpp +++ b/src/ipc_listener.hpp @@ -41,83 +41,78 @@ namespace zmq { +class io_thread_t; +class socket_base_t; - class io_thread_t; - class socket_base_t; - - class ipc_listener_t : public own_t, public io_object_t - { - public: - - ipc_listener_t (zmq::io_thread_t *io_thread_, - zmq::socket_base_t *socket_, const options_t &options_); - ~ipc_listener_t (); - - // Set address to listen on. - int set_address (const char *addr_); - - // Get the bound address for use with wildcards - int get_address (std::string &addr_); +class ipc_listener_t : public own_t, public io_object_t +{ + public: + ipc_listener_t (zmq::io_thread_t *io_thread_, + zmq::socket_base_t *socket_, + const options_t &options_); + ~ipc_listener_t (); - private: + // Set address to listen on. + int set_address (const char *addr_); - // Handlers for incoming commands. - void process_plug (); - void process_term (int linger_); + // Get the bound address for use with wildcards + int get_address (std::string &addr_); - // Handlers for I/O events. - void in_event (); + private: + // Handlers for incoming commands. + void process_plug (); + void process_term (int linger_); - // Close the listening socket. - int close (); + // Handlers for I/O events. + void in_event (); - // Create wildcard path address - static int create_wildcard_address(std::string& path_, - std::string& file_); + // Close the listening socket. + int close (); - // Filter new connections if the OS provides a mechanism to get - // the credentials of the peer process. Called from accept(). -# if defined ZMQ_HAVE_SO_PEERCRED || defined ZMQ_HAVE_LOCAL_PEERCRED - bool filter (fd_t sock); -# endif + // Create wildcard path address + static int create_wildcard_address (std::string &path_, std::string &file_); - // Accept the new connection. Returns the file descriptor of the - // newly created connection. The function may return retired_fd - // if the connection was dropped while waiting in the listen backlog. - fd_t accept (); + // Filter new connections if the OS provides a mechanism to get + // the credentials of the peer process. Called from accept(). +#if defined ZMQ_HAVE_SO_PEERCRED || defined ZMQ_HAVE_LOCAL_PEERCRED + bool filter (fd_t sock); +#endif - // True, if the underlying file for UNIX domain socket exists. - bool has_file; + // Accept the new connection. Returns the file descriptor of the + // newly created connection. The function may return retired_fd + // if the connection was dropped while waiting in the listen backlog. + fd_t accept (); - // Name of the temporary directory (if any) that has the - // the UNIX domain socket - std::string tmp_socket_dirname; + // True, if the underlying file for UNIX domain socket exists. + bool has_file; - // Name of the file associated with the UNIX domain address. - std::string filename; + // Name of the temporary directory (if any) that has the + // the UNIX domain socket + std::string tmp_socket_dirname; - // Underlying socket. - fd_t s; + // Name of the file associated with the UNIX domain address. + std::string filename; - // Handle corresponding to the listening socket. - handle_t handle; + // Underlying socket. + fd_t s; - // Socket the listener belongs to. - zmq::socket_base_t *socket; + // Handle corresponding to the listening socket. + handle_t handle; - // String representation of endpoint to bind to - std::string endpoint; + // Socket the listener belongs to. + zmq::socket_base_t *socket; - // Acceptable temporary directory environment variables - static const char *tmp_env_vars[]; + // String representation of endpoint to bind to + std::string endpoint; - ipc_listener_t (const ipc_listener_t&); - const ipc_listener_t &operator = (const ipc_listener_t&); - }; + // Acceptable temporary directory environment variables + static const char *tmp_env_vars[]; + ipc_listener_t (const ipc_listener_t &); + const ipc_listener_t &operator= (const ipc_listener_t &); +}; } #endif #endif - diff --git a/src/kqueue.cpp b/src/kqueue.cpp index a0ec2f1ee5..cf4ce4a9d5 100644 --- a/src/kqueue.cpp +++ b/src/kqueue.cpp @@ -54,15 +54,13 @@ #define kevent_udata_t void * #endif -zmq::kqueue_t::kqueue_t (const zmq::ctx_t &ctx_) : - ctx(ctx_), - stopping (false) +zmq::kqueue_t::kqueue_t (const zmq::ctx_t &ctx_) : ctx (ctx_), stopping (false) { // Create event queue kqueue_fd = kqueue (); errno_assert (kqueue_fd != -1); #ifdef HAVE_FORK - pid = getpid(); + pid = getpid (); #endif } @@ -76,7 +74,7 @@ void zmq::kqueue_t::kevent_add (fd_t fd_, short filter_, void *udata_) { struct kevent ev; - EV_SET (&ev, fd_, filter_, EV_ADD, 0, 0, (kevent_udata_t)udata_); + EV_SET (&ev, fd_, filter_, EV_ADD, 0, 0, (kevent_udata_t) udata_); int rc = kevent (kqueue_fd, &ev, 1, NULL, 0, NULL); errno_assert (rc != -1); } @@ -91,7 +89,7 @@ void zmq::kqueue_t::kevent_delete (fd_t fd_, short filter_) } zmq::kqueue_t::handle_t zmq::kqueue_t::add_fd (fd_t fd_, - i_poll_events *reactor_) + i_poll_events *reactor_) { poll_entry_t *pe = new (std::nothrow) poll_entry_t; alloc_assert (pe); @@ -108,7 +106,7 @@ zmq::kqueue_t::handle_t zmq::kqueue_t::add_fd (fd_t fd_, void zmq::kqueue_t::rm_fd (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; if (pe->flag_pollin) kevent_delete (pe->fd, EVFILT_READ); if (pe->flag_pollout) @@ -121,7 +119,7 @@ void zmq::kqueue_t::rm_fd (handle_t handle_) void zmq::kqueue_t::set_pollin (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; if (likely (!pe->flag_pollin)) { pe->flag_pollin = true; kevent_add (pe->fd, EVFILT_READ, pe); @@ -130,7 +128,7 @@ void zmq::kqueue_t::set_pollin (handle_t handle_) void zmq::kqueue_t::reset_pollin (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; if (likely (pe->flag_pollin)) { pe->flag_pollin = false; kevent_delete (pe->fd, EVFILT_READ); @@ -139,7 +137,7 @@ void zmq::kqueue_t::reset_pollin (handle_t handle_) void zmq::kqueue_t::set_pollout (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; if (likely (!pe->flag_pollout)) { pe->flag_pollout = true; kevent_add (pe->fd, EVFILT_WRITE, pe); @@ -148,11 +146,11 @@ void zmq::kqueue_t::set_pollout (handle_t handle_) void zmq::kqueue_t::reset_pollout (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; if (likely (pe->flag_pollout)) { pe->flag_pollout = false; kevent_delete (pe->fd, EVFILT_WRITE); - } + } } void zmq::kqueue_t::start () @@ -173,17 +171,16 @@ int zmq::kqueue_t::max_fds () void zmq::kqueue_t::loop () { while (!stopping) { - // Execute any due timers. int timeout = (int) execute_timers (); // Wait for events. - struct kevent ev_buf [max_io_events]; + struct kevent ev_buf[max_io_events]; timespec ts = {timeout / 1000, (timeout % 1000) * 1000000}; - int n = kevent (kqueue_fd, NULL, 0, &ev_buf [0], max_io_events, - timeout ? &ts: NULL); + int n = kevent (kqueue_fd, NULL, 0, &ev_buf[0], max_io_events, + timeout ? &ts : NULL); #ifdef HAVE_FORK - if (unlikely(pid != getpid())) { + if (unlikely (pid != getpid ())) { //printf("zmq::kqueue_t::loop aborting on forked child %d\n", (int)getpid()); // simply exit the loop in a forked process. return; @@ -194,26 +191,27 @@ void zmq::kqueue_t::loop () continue; } - for (int i = 0; i < n; i ++) { - poll_entry_t *pe = (poll_entry_t*) ev_buf [i].udata; + for (int i = 0; i < n; i++) { + poll_entry_t *pe = (poll_entry_t *) ev_buf[i].udata; if (pe->fd == retired_fd) continue; - if (ev_buf [i].flags & EV_EOF) + if (ev_buf[i].flags & EV_EOF) pe->reactor->in_event (); if (pe->fd == retired_fd) continue; - if (ev_buf [i].filter == EVFILT_WRITE) + if (ev_buf[i].filter == EVFILT_WRITE) pe->reactor->out_event (); if (pe->fd == retired_fd) continue; - if (ev_buf [i].filter == EVFILT_READ) + if (ev_buf[i].filter == EVFILT_READ) pe->reactor->in_event (); } // Destroy retired event sources. - for (retired_t::iterator it = retired.begin (); it != retired.end (); ++it) { - LIBZMQ_DELETE(*it); + for (retired_t::iterator it = retired.begin (); it != retired.end (); + ++it) { + LIBZMQ_DELETE (*it); } retired.clear (); } @@ -221,7 +219,7 @@ void zmq::kqueue_t::loop () void zmq::kqueue_t::worker_routine (void *arg_) { - ((kqueue_t*) arg_)->loop (); + ((kqueue_t *) arg_)->loop (); } #endif diff --git a/src/kqueue.hpp b/src/kqueue.hpp index 27c1b15121..a717feeb01 100644 --- a/src/kqueue.hpp +++ b/src/kqueue.hpp @@ -44,82 +44,78 @@ namespace zmq { +struct i_poll_events; - struct i_poll_events; +// Implements socket polling mechanism using the BSD-specific +// kqueue interface. - // Implements socket polling mechanism using the BSD-specific - // kqueue interface. - - class kqueue_t : public poller_base_t - { - public: - - typedef void* handle_t; - - kqueue_t (const ctx_t &ctx_); - ~kqueue_t (); +class kqueue_t : public poller_base_t +{ + public: + typedef void *handle_t; - // "poller" concept. - handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); - void rm_fd (handle_t handle_); - void set_pollin (handle_t handle_); - void reset_pollin (handle_t handle_); - void set_pollout (handle_t handle_); - void reset_pollout (handle_t handle_); - void start (); - void stop (); + kqueue_t (const ctx_t &ctx_); + ~kqueue_t (); - static int max_fds (); + // "poller" concept. + handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); + void rm_fd (handle_t handle_); + void set_pollin (handle_t handle_); + void reset_pollin (handle_t handle_); + void set_pollout (handle_t handle_); + void reset_pollout (handle_t handle_); + void start (); + void stop (); - private: + static int max_fds (); - // Main worker thread routine. - static void worker_routine (void *arg_); + private: + // Main worker thread routine. + static void worker_routine (void *arg_); - // Main event loop. - void loop (); + // Main event loop. + void loop (); - // Reference to ZMQ context. - const ctx_t &ctx; + // Reference to ZMQ context. + const ctx_t &ctx; - // File descriptor referring to the kernel event queue. - fd_t kqueue_fd; + // File descriptor referring to the kernel event queue. + fd_t kqueue_fd; - // Adds the event to the kqueue. - void kevent_add (fd_t fd_, short filter_, void *udata_); + // Adds the event to the kqueue. + void kevent_add (fd_t fd_, short filter_, void *udata_); - // Deletes the event from the kqueue. - void kevent_delete (fd_t fd_, short filter_); + // Deletes the event from the kqueue. + void kevent_delete (fd_t fd_, short filter_); - struct poll_entry_t - { - fd_t fd; - bool flag_pollin; - bool flag_pollout; - zmq::i_poll_events *reactor; - }; + struct poll_entry_t + { + fd_t fd; + bool flag_pollin; + bool flag_pollout; + zmq::i_poll_events *reactor; + }; - // List of retired event sources. - typedef std::vector retired_t; - retired_t retired; + // List of retired event sources. + typedef std::vector retired_t; + retired_t retired; - // If true, thread is in the process of shutting down. - bool stopping; + // If true, thread is in the process of shutting down. + bool stopping; - // Handle of the physical thread doing the I/O work. - thread_t worker; + // Handle of the physical thread doing the I/O work. + thread_t worker; - kqueue_t (const kqueue_t&); - const kqueue_t &operator = (const kqueue_t&); + kqueue_t (const kqueue_t &); + const kqueue_t &operator= (const kqueue_t &); #ifdef HAVE_FORK - // the process that created this context. Used to detect forking. - pid_t pid; + // the process that created this context. Used to detect forking. + pid_t pid; #endif - }; - - typedef kqueue_t poller_t; +}; +typedef kqueue_t poller_t; } #endif diff --git a/src/lb.cpp b/src/lb.cpp index c4a691783d..d92928d077 100644 --- a/src/lb.cpp +++ b/src/lb.cpp @@ -33,11 +33,7 @@ #include "err.hpp" #include "msg.hpp" -zmq::lb_t::lb_t () : - active (0), - current (0), - more (false), - dropping (false) +zmq::lb_t::lb_t () : active (0), current (0), more (false), dropping (false) { } @@ -89,7 +85,6 @@ int zmq::lb_t::sendpipe (msg_t *msg_, pipe_t **pipe_) // Drop the message if required. If we are at the end of the message // switch back to non-dropping mode. if (dropping) { - more = msg_->flags () & msg_t::more ? true : false; dropping = more; @@ -101,19 +96,17 @@ int zmq::lb_t::sendpipe (msg_t *msg_, pipe_t **pipe_) } while (active > 0) { - if (pipes [current]->write (msg_)) - { + if (pipes[current]->write (msg_)) { if (pipe_) - *pipe_ = pipes [current]; + *pipe_ = pipes[current]; break; } // If send fails for multi-part msg rollback other // parts sent earlier and return EAGAIN. // Application should handle this as suitable - if (more) - { - pipes [current]->rollback (); + if (more) { + pipes[current]->rollback (); more = 0; errno = EAGAIN; return -1; @@ -134,9 +127,9 @@ int zmq::lb_t::sendpipe (msg_t *msg_, pipe_t **pipe_) // If it's final part of the message we can flush it downstream and // continue round-robining (load balance). - more = msg_->flags () & msg_t::more? true: false; + more = msg_->flags () & msg_t::more ? true : false; if (!more) { - pipes [current]->flush (); + pipes[current]->flush (); if (++current >= active) current = 0; @@ -157,9 +150,8 @@ bool zmq::lb_t::has_out () return true; while (active > 0) { - // Check whether a pipe has room for another message. - if (pipes [current]->check_write ()) + if (pipes[current]->check_write ()) return true; // Deactivate the pipe. diff --git a/src/lb.hpp b/src/lb.hpp index 90d46fc536..ba5e0bc784 100644 --- a/src/lb.hpp +++ b/src/lb.hpp @@ -35,54 +35,50 @@ namespace zmq { +// This class manages a set of outbound pipes. On send it load balances +// messages fairly among the pipes. - // This class manages a set of outbound pipes. On send it load balances - // messages fairly among the pipes. - - class lb_t - { - public: - - lb_t (); - ~lb_t (); - - void attach (pipe_t *pipe_); - void activated (pipe_t *pipe_); - void pipe_terminated (pipe_t *pipe_); - - int send (msg_t *msg_); +class lb_t +{ + public: + lb_t (); + ~lb_t (); - // Sends a message and stores the pipe that was used in pipe_. - // It is possible for this function to return success but keep pipe_ - // unset if the rest of a multipart message to a terminated pipe is - // being dropped. For the first frame, this will never happen. - int sendpipe (msg_t *msg_, pipe_t **pipe_); + void attach (pipe_t *pipe_); + void activated (pipe_t *pipe_); + void pipe_terminated (pipe_t *pipe_); - bool has_out (); + int send (msg_t *msg_); - private: + // Sends a message and stores the pipe that was used in pipe_. + // It is possible for this function to return success but keep pipe_ + // unset if the rest of a multipart message to a terminated pipe is + // being dropped. For the first frame, this will never happen. + int sendpipe (msg_t *msg_, pipe_t **pipe_); - // List of outbound pipes. - typedef array_t pipes_t; - pipes_t pipes; + bool has_out (); - // Number of active pipes. All the active pipes are located at the - // beginning of the pipes array. - pipes_t::size_type active; + private: + // List of outbound pipes. + typedef array_t pipes_t; + pipes_t pipes; - // Points to the last pipe that the most recent message was sent to. - pipes_t::size_type current; + // Number of active pipes. All the active pipes are located at the + // beginning of the pipes array. + pipes_t::size_type active; - // True if last we are in the middle of a multipart message. - bool more; + // Points to the last pipe that the most recent message was sent to. + pipes_t::size_type current; - // True if we are dropping current message. - bool dropping; + // True if last we are in the middle of a multipart message. + bool more; - lb_t (const lb_t&); - const lb_t &operator = (const lb_t&); - }; + // True if we are dropping current message. + bool dropping; + lb_t (const lb_t &); + const lb_t &operator= (const lb_t &); +}; } #endif diff --git a/src/macros.hpp b/src/macros.hpp index 3bb6267bbc..48c3db8758 100644 --- a/src/macros.hpp +++ b/src/macros.hpp @@ -3,10 +3,11 @@ /* 0MQ Internal Use */ /******************************************************************************/ -#define LIBZMQ_UNUSED(object) (void)object -#define LIBZMQ_DELETE(p_object) {\ - delete p_object; \ - p_object = 0; \ -} +#define LIBZMQ_UNUSED(object) (void) object +#define LIBZMQ_DELETE(p_object) \ + { \ + delete p_object; \ + p_object = 0; \ + } /******************************************************************************/ diff --git a/src/mailbox.hpp b/src/mailbox.hpp index 0e060269eb..596a443af3 100644 --- a/src/mailbox.hpp +++ b/src/mailbox.hpp @@ -42,51 +42,47 @@ namespace zmq { +class mailbox_t : public i_mailbox +{ + public: + mailbox_t (); + ~mailbox_t (); - class mailbox_t : public i_mailbox - { - public: - - mailbox_t (); - ~mailbox_t (); - - fd_t get_fd () const; - void send (const command_t &cmd_); - int recv (command_t *cmd_, int timeout_); + fd_t get_fd () const; + void send (const command_t &cmd_); + int recv (command_t *cmd_, int timeout_); - bool valid () const; + bool valid () const; #ifdef HAVE_FORK - // close the file descriptors in the signaller. This is used in a forked - // child process to close the file descriptors so that they do not interfere - // with the context in the parent process. - void forked () { signaler.forked (); } + // close the file descriptors in the signaller. This is used in a forked + // child process to close the file descriptors so that they do not interfere + // with the context in the parent process. + void forked () { signaler.forked (); } #endif - private: - - // The pipe to store actual commands. - typedef ypipe_t cpipe_t; - cpipe_t cpipe; - - // Signaler to pass signals from writer thread to reader thread. - signaler_t signaler; + private: + // The pipe to store actual commands. + typedef ypipe_t cpipe_t; + cpipe_t cpipe; - // There's only one thread receiving from the mailbox, but there - // is arbitrary number of threads sending. Given that ypipe requires - // synchronised access on both of its endpoints, we have to synchronise - // the sending side. - mutex_t sync; + // Signaler to pass signals from writer thread to reader thread. + signaler_t signaler; - // True if the underlying pipe is active, ie. when we are allowed to - // read commands from it. - bool active; + // There's only one thread receiving from the mailbox, but there + // is arbitrary number of threads sending. Given that ypipe requires + // synchronised access on both of its endpoints, we have to synchronise + // the sending side. + mutex_t sync; - // Disable copying of mailbox_t object. - mailbox_t (const mailbox_t&); - const mailbox_t &operator = (const mailbox_t&); - }; + // True if the underlying pipe is active, ie. when we are allowed to + // read commands from it. + bool active; + // Disable copying of mailbox_t object. + mailbox_t (const mailbox_t &); + const mailbox_t &operator= (const mailbox_t &); +}; } #endif diff --git a/src/mailbox_safe.cpp b/src/mailbox_safe.cpp index a22d7b84bf..921481d290 100644 --- a/src/mailbox_safe.cpp +++ b/src/mailbox_safe.cpp @@ -32,8 +32,7 @@ #include "clock.hpp" #include "err.hpp" -zmq::mailbox_safe_t::mailbox_safe_t (mutex_t* sync_) : - sync (sync_) +zmq::mailbox_safe_t::mailbox_safe_t (mutex_t *sync_) : sync (sync_) { // Get the pipe into passive state. That way, if the users starts by // polling on the associated file descriptor it will get woken up when @@ -52,23 +51,23 @@ zmq::mailbox_safe_t::~mailbox_safe_t () sync->unlock (); } -void zmq::mailbox_safe_t::add_signaler (signaler_t* signaler) +void zmq::mailbox_safe_t::add_signaler (signaler_t *signaler) { - signalers.push_back(signaler); + signalers.push_back (signaler); } -void zmq::mailbox_safe_t::remove_signaler (signaler_t* signaler) +void zmq::mailbox_safe_t::remove_signaler (signaler_t *signaler) { - std::vector::iterator it = signalers.begin(); + std::vector::iterator it = signalers.begin (); // TODO: make a copy of array and signal outside the lock - for (; it != signalers.end(); ++it){ + for (; it != signalers.end (); ++it) { if (*it == signaler) - break; + break; } - if (it != signalers.end()) - signalers.erase(it); + if (it != signalers.end ()) + signalers.erase (it); } void zmq::mailbox_safe_t::clear_signalers () @@ -84,8 +83,9 @@ void zmq::mailbox_safe_t::send (const command_t &cmd_) if (!ok) { cond_var.broadcast (); - for (std::vector::iterator it = signalers.begin(); it != signalers.end(); ++it){ - (*it)->send(); + for (std::vector::iterator it = signalers.begin (); + it != signalers.end (); ++it) { + (*it)->send (); } } diff --git a/src/mailbox_safe.hpp b/src/mailbox_safe.hpp index 0e1382f2be..90ddb0eaf3 100644 --- a/src/mailbox_safe.hpp +++ b/src/mailbox_safe.hpp @@ -44,51 +44,47 @@ namespace zmq { +class mailbox_safe_t : public i_mailbox +{ + public: + mailbox_safe_t (mutex_t *sync_); + ~mailbox_safe_t (); - class mailbox_safe_t : public i_mailbox - { - public: - - mailbox_safe_t (mutex_t* sync_); - ~mailbox_safe_t (); - - void send (const command_t &cmd_); - int recv (command_t *cmd_, int timeout_); + void send (const command_t &cmd_); + int recv (command_t *cmd_, int timeout_); - // Add signaler to mailbox which will be called when a message is ready - void add_signaler (signaler_t* signaler); - void remove_signaler (signaler_t* signaler); - void clear_signalers (); + // Add signaler to mailbox which will be called when a message is ready + void add_signaler (signaler_t *signaler); + void remove_signaler (signaler_t *signaler); + void clear_signalers (); #ifdef HAVE_FORK - // close the file descriptors in the signaller. This is used in a forked - // child process to close the file descriptors so that they do not interfere - // with the context in the parent process. - void forked () - { - // TODO: call fork on the condition variable - } + // close the file descriptors in the signaller. This is used in a forked + // child process to close the file descriptors so that they do not interfere + // with the context in the parent process. + void forked () + { + // TODO: call fork on the condition variable + } #endif - private: - - // The pipe to store actual commands. - typedef ypipe_t cpipe_t; - cpipe_t cpipe; - - // Condition variable to pass signals from writer thread to reader thread. - condition_variable_t cond_var; + private: + // The pipe to store actual commands. + typedef ypipe_t cpipe_t; + cpipe_t cpipe; - // Synchronize access to the mailbox from receivers and senders - mutex_t* sync; + // Condition variable to pass signals from writer thread to reader thread. + condition_variable_t cond_var; - std::vector signalers; + // Synchronize access to the mailbox from receivers and senders + mutex_t *sync; - // Disable copying of mailbox_t object. - mailbox_safe_t (const mailbox_safe_t&); - const mailbox_safe_t &operator = (const mailbox_safe_t&); - }; + std::vector signalers; + // Disable copying of mailbox_t object. + mailbox_safe_t (const mailbox_safe_t &); + const mailbox_safe_t &operator= (const mailbox_safe_t &); +}; } #endif diff --git a/src/mechanism.cpp b/src/mechanism.cpp index 24cc3f2a07..5753ed3f23 100644 --- a/src/mechanism.cpp +++ b/src/mechanism.cpp @@ -37,8 +37,7 @@ #include "wire.hpp" #include "session_base.hpp" -zmq::mechanism_t::mechanism_t (const options_t &options_) : - options (options_) +zmq::mechanism_t::mechanism_t (const options_t &options_) : options (options_) { } @@ -48,7 +47,7 @@ zmq::mechanism_t::~mechanism_t () void zmq::mechanism_t::set_peer_routing_id (const void *id_ptr, size_t id_size) { - routing_id.set (static_cast (id_ptr), id_size); + routing_id.set (static_cast (id_ptr), id_size); } void zmq::mechanism_t::peer_routing_id (msg_t *msg_) @@ -61,7 +60,7 @@ void zmq::mechanism_t::peer_routing_id (msg_t *msg_) void zmq::mechanism_t::set_user_id (const void *data_, size_t size_) { - user_id.set (static_cast (data_), size_); + user_id.set (static_cast (data_), size_); zap_properties.ZMQ_MAP_INSERT_OR_EMPLACE ( ZMQ_MSG_PROPERTY_USER_ID, std::string ((char *) data_, size_)); } @@ -73,14 +72,12 @@ const zmq::blob_t &zmq::mechanism_t::get_user_id () const const char *zmq::mechanism_t::socket_type_string (int socket_type) const { - static const char *names [] = {"PAIR", "PUB", "SUB", "REQ", "REP", - "DEALER", "ROUTER", "PULL", "PUSH", - "XPUB", "XSUB", "STREAM", - "SERVER", "CLIENT", - "RADIO", "DISH", - "GATHER", "SCATTER", "DGRAM"}; + static const char *names[] = { + "PAIR", "PUB", "SUB", "REQ", "REP", "DEALER", "ROUTER", + "PULL", "PUSH", "XPUB", "XSUB", "STREAM", "SERVER", "CLIENT", + "RADIO", "DISH", "GATHER", "SCATTER", "DGRAM"}; zmq_assert (socket_type >= 0 && socket_type <= 18); - return names [socket_type]; + return names[socket_type]; } static size_t property_len (size_t name_len, size_t value_len) @@ -105,11 +102,11 @@ size_t zmq::mechanism_t::add_property (unsigned char *ptr, const size_t total_len = ::property_len (name_len, value_len); zmq_assert (total_len <= ptr_capacity); - *ptr++ = static_cast (name_len); + *ptr++ = static_cast (name_len); memcpy (ptr, name, name_len); ptr += name_len; zmq_assert (value_len <= 0x7FFFFFFF); - put_uint32 (ptr, static_cast (value_len)); + put_uint32 (ptr, static_cast (value_len)); ptr += 4; memcpy (ptr, value, value_len); @@ -131,28 +128,26 @@ size_t zmq::mechanism_t::add_basic_properties (unsigned char *buf, // Add socket type property const char *socket_type = socket_type_string (options.type); - ptr += add_property (ptr, buf_capacity, - ZMTP_PROPERTY_SOCKET_TYPE, socket_type, - strlen (socket_type)); + ptr += add_property (ptr, buf_capacity, ZMTP_PROPERTY_SOCKET_TYPE, + socket_type, strlen (socket_type)); // Add identity (aka routing id) property if (options.type == ZMQ_REQ || options.type == ZMQ_DEALER || options.type == ZMQ_ROUTER) - ptr += add_property (ptr, buf_capacity - (ptr - buf), - ZMTP_PROPERTY_IDENTITY, options.routing_id, - options.routing_id_size); + ptr += + add_property (ptr, buf_capacity - (ptr - buf), ZMTP_PROPERTY_IDENTITY, + options.routing_id, options.routing_id_size); return ptr - buf; } -size_t zmq::mechanism_t::basic_properties_len() const +size_t zmq::mechanism_t::basic_properties_len () const { const char *socket_type = socket_type_string (options.type); return property_len (ZMTP_PROPERTY_SOCKET_TYPE, strlen (socket_type)) + ((options.type == ZMQ_REQ || options.type == ZMQ_DEALER || options.type == ZMQ_ROUTER) - ? property_len (ZMTP_PROPERTY_IDENTITY, - options.routing_id_size) + ? property_len (ZMTP_PROPERTY_IDENTITY, options.routing_id_size) : 0); } @@ -169,8 +164,8 @@ void zmq::mechanism_t::make_command_with_basic_properties ( memcpy (ptr, prefix, prefix_len); ptr += prefix_len; - add_basic_properties ( - ptr, command_size - (ptr - (unsigned char *) msg_->data ())); + add_basic_properties (ptr, command_size + - (ptr - (unsigned char *) msg_->data ())); } int zmq::mechanism_t::parse_metadata (const unsigned char *ptr_, @@ -180,7 +175,7 @@ int zmq::mechanism_t::parse_metadata (const unsigned char *ptr_, size_t bytes_left = length_; while (bytes_left > 1) { - const size_t name_length = static_cast (*ptr_); + const size_t name_length = static_cast (*ptr_); ptr_ += 1; bytes_left -= 1; if (bytes_left < name_length) @@ -192,7 +187,7 @@ int zmq::mechanism_t::parse_metadata (const unsigned char *ptr_, if (bytes_left < 4) break; - const size_t value_length = static_cast (get_uint32 (ptr_)); + const size_t value_length = static_cast (get_uint32 (ptr_)); ptr_ += 4; bytes_left -= 4; if (bytes_left < value_length) @@ -204,25 +199,23 @@ int zmq::mechanism_t::parse_metadata (const unsigned char *ptr_, if (name == ZMTP_PROPERTY_IDENTITY && options.recv_routing_id) set_peer_routing_id (value, value_length); - else - if (name == ZMTP_PROPERTY_SOCKET_TYPE) { + else if (name == ZMTP_PROPERTY_SOCKET_TYPE) { const std::string socket_type ((char *) value, value_length); if (!check_socket_type (socket_type)) { errno = EINVAL; return -1; } - } - else { + } else { const int rc = property (name, value, value_length); if (rc == -1) return -1; } if (zap_flag) zap_properties.ZMQ_MAP_INSERT_OR_EMPLACE ( - name, std::string ((char *) value, value_length)); + name, std::string ((char *) value, value_length)); else zmtp_properties.ZMQ_MAP_INSERT_OR_EMPLACE ( - name, std::string ((char *) value, value_length)); + name, std::string ((char *) value, value_length)); } if (bytes_left > 0) { errno = EPROTO; @@ -231,15 +224,16 @@ int zmq::mechanism_t::parse_metadata (const unsigned char *ptr_, return 0; } -int zmq::mechanism_t::property (const std::string& /* name_ */, - const void * /* value_ */, size_t /* length_ */) +int zmq::mechanism_t::property (const std::string & /* name_ */, + const void * /* value_ */, + size_t /* length_ */) { // Default implementation does not check // property values and returns 0 to signal success. return 0; } -bool zmq::mechanism_t::check_socket_type (const std::string& type_) const +bool zmq::mechanism_t::check_socket_type (const std::string &type_) const { switch (options.type) { case ZMQ_REQ: diff --git a/src/mechanism.hpp b/src/mechanism.hpp index cd2b7d2b18..4bce7e125f 100644 --- a/src/mechanism.hpp +++ b/src/mechanism.hpp @@ -37,116 +37,108 @@ namespace zmq { +class msg_t; +class session_base_t; - class msg_t; - class session_base_t; +// Abstract class representing security mechanism. +// Different mechanism extends this class. - // Abstract class representing security mechanism. - // Different mechanism extends this class. - - class mechanism_t +class mechanism_t +{ + public: + enum status_t { - public: - - enum status_t { - handshaking, - ready, - error - }; - - mechanism_t (const options_t &options_); - - virtual ~mechanism_t (); - - // Prepare next handshake command that is to be sent to the peer. - virtual int next_handshake_command (msg_t *msg_) = 0; + handshaking, + ready, + error + }; - // Process the handshake command received from the peer. - virtual int process_handshake_command (msg_t *msg_) = 0; + mechanism_t (const options_t &options_); - virtual int encode (msg_t *) { return 0; } + virtual ~mechanism_t (); - virtual int decode (msg_t *) { return 0; } + // Prepare next handshake command that is to be sent to the peer. + virtual int next_handshake_command (msg_t *msg_) = 0; - // Notifies mechanism about availability of ZAP message. - virtual int zap_msg_available () { return 0; } + // Process the handshake command received from the peer. + virtual int process_handshake_command (msg_t *msg_) = 0; - // Returns the status of this mechanism. - virtual status_t status () const = 0; + virtual int encode (msg_t *) { return 0; } - void set_peer_routing_id (const void *id_ptr, size_t id_size); + virtual int decode (msg_t *) { return 0; } - void peer_routing_id (msg_t *msg_); + // Notifies mechanism about availability of ZAP message. + virtual int zap_msg_available () { return 0; } - void set_user_id (const void *user_id, size_t size); + // Returns the status of this mechanism. + virtual status_t status () const = 0; - const blob_t &get_user_id () const; + void set_peer_routing_id (const void *id_ptr, size_t id_size); - const metadata_t::dict_t& get_zmtp_properties () { - return zmtp_properties; - } + void peer_routing_id (msg_t *msg_); - const metadata_t::dict_t& get_zap_properties () { - return zap_properties; - } + void set_user_id (const void *user_id, size_t size); - protected: + const blob_t &get_user_id () const; - // Only used to identify the socket for the Socket-Type - // property in the wire protocol. - const char *socket_type_string (int socket_type) const; + const metadata_t::dict_t &get_zmtp_properties () { return zmtp_properties; } - static size_t add_property (unsigned char *ptr, - size_t ptr_capacity, - const char *name, - const void *value, - size_t value_len); - static size_t property_len (const char *name, - size_t value_len); + const metadata_t::dict_t &get_zap_properties () { return zap_properties; } - size_t add_basic_properties (unsigned char *ptr, size_t ptr_capacity) const; - size_t basic_properties_len () const; + protected: + // Only used to identify the socket for the Socket-Type + // property in the wire protocol. + const char *socket_type_string (int socket_type) const; - void make_command_with_basic_properties (msg_t *msg_, - const char *prefix, - size_t prefix_len) const; + static size_t add_property (unsigned char *ptr, + size_t ptr_capacity, + const char *name, + const void *value, + size_t value_len); + static size_t property_len (const char *name, size_t value_len); - // Parses a metadata. - // Metadata consists of a list of properties consisting of - // name and value as size-specified strings. - // Returns 0 on success and -1 on error, in which case errno is set. - int parse_metadata ( - const unsigned char *ptr_, size_t length, bool zap_flag = false); + size_t add_basic_properties (unsigned char *ptr, size_t ptr_capacity) const; + size_t basic_properties_len () const; - // This is called by parse_property method whenever it - // parses a new property. The function should return 0 - // on success and -1 on error, in which case it should - // set errno. Signaling error prevents parser from - // parsing remaining data. - // Derived classes are supposed to override this - // method to handle custom processing. - virtual int property (const std::string& name_, - const void *value_, size_t length_); + void make_command_with_basic_properties (msg_t *msg_, + const char *prefix, + size_t prefix_len) const; - // Properties received from ZMTP peer. - metadata_t::dict_t zmtp_properties; + // Parses a metadata. + // Metadata consists of a list of properties consisting of + // name and value as size-specified strings. + // Returns 0 on success and -1 on error, in which case errno is set. + int parse_metadata (const unsigned char *ptr_, + size_t length, + bool zap_flag = false); - // Properties received from ZAP server. - metadata_t::dict_t zap_properties; + // This is called by parse_property method whenever it + // parses a new property. The function should return 0 + // on success and -1 on error, in which case it should + // set errno. Signaling error prevents parser from + // parsing remaining data. + // Derived classes are supposed to override this + // method to handle custom processing. + virtual int + property (const std::string &name_, const void *value_, size_t length_); - options_t options; + // Properties received from ZMTP peer. + metadata_t::dict_t zmtp_properties; - private: + // Properties received from ZAP server. + metadata_t::dict_t zap_properties; - blob_t routing_id; + options_t options; - blob_t user_id; + private: + blob_t routing_id; - // Returns true iff socket associated with the mechanism - // is compatible with a given socket type 'type_'. - bool check_socket_type (const std::string& type_) const; - }; + blob_t user_id; + // Returns true iff socket associated with the mechanism + // is compatible with a given socket type 'type_'. + bool check_socket_type (const std::string &type_) const; +}; } #endif diff --git a/src/mechanism_base.cpp b/src/mechanism_base.cpp index 216261a40f..6063c7a73e 100644 --- a/src/mechanism_base.cpp +++ b/src/mechanism_base.cpp @@ -37,7 +37,6 @@ zmq::mechanism_base_t::mechanism_base_t (session_base_t *const session_, mechanism_t (options_), session (session_) { - } int zmq::mechanism_base_t::check_basic_command_structure (msg_t *msg_) @@ -64,7 +63,7 @@ void zmq::mechanism_base_t::handle_error_reason (const char *error_reason, } } -bool zmq::mechanism_base_t::zap_required() const +bool zmq::mechanism_base_t::zap_required () const { return !options.zap_domain.empty (); } diff --git a/src/mechanism_base.hpp b/src/mechanism_base.hpp index c6e76eeaf1..a0eafdab76 100644 --- a/src/mechanism_base.hpp +++ b/src/mechanism_base.hpp @@ -44,9 +44,10 @@ class mechanism_base_t : public mechanism_t int check_basic_command_structure (msg_t *msg_); - void handle_error_reason (const char *error_reason, size_t error_reason_len); + void handle_error_reason (const char *error_reason, + size_t error_reason_len); - bool zap_required() const; + bool zap_required () const; }; } diff --git a/src/metadata.cpp b/src/metadata.cpp index e2a8a11def..a7cd7341a4 100644 --- a/src/metadata.cpp +++ b/src/metadata.cpp @@ -30,24 +30,20 @@ #include "precompiled.hpp" #include "metadata.hpp" -zmq::metadata_t::metadata_t (const dict_t &dict) : - ref_cnt (1), - dict (dict) +zmq::metadata_t::metadata_t (const dict_t &dict) : ref_cnt (1), dict (dict) { } const char *zmq::metadata_t::get (const std::string &property) const { dict_t::const_iterator it = dict.find (property); - if (it == dict.end()) - { + if (it == dict.end ()) { /** \todo remove this when support for the deprecated name "Identity" is dropped */ if (property == "Identity") return get (ZMQ_MSG_PROPERTY_ROUTING_ID); return NULL; - } - else + } else return it->second.c_str (); } diff --git a/src/metadata.hpp b/src/metadata.hpp index 2b1a89f633..aaa17d7086 100644 --- a/src/metadata.hpp +++ b/src/metadata.hpp @@ -37,34 +37,33 @@ namespace zmq { - class metadata_t - { - public: - typedef std::map dict_t; - - metadata_t (const dict_t &dict); +class metadata_t +{ + public: + typedef std::map dict_t; - // Returns pointer to property value or NULL if - // property is not found. - const char *get (const std::string &property) const; + metadata_t (const dict_t &dict); - void add_ref (); + // Returns pointer to property value or NULL if + // property is not found. + const char *get (const std::string &property) const; - // Drop reference. Returns true iff the reference - // counter drops to zero. - bool drop_ref (); + void add_ref (); - private: - metadata_t(const metadata_t&); - metadata_t & operator=(const metadata_t&); + // Drop reference. Returns true iff the reference + // counter drops to zero. + bool drop_ref (); - // Reference counter. - atomic_counter_t ref_cnt; + private: + metadata_t (const metadata_t &); + metadata_t &operator= (const metadata_t &); - // Dictionary holding metadata. - dict_t dict; - }; + // Reference counter. + atomic_counter_t ref_cnt; + // Dictionary holding metadata. + dict_t dict; +}; } #endif diff --git a/src/msg.cpp b/src/msg.cpp index 9924ba05ac..15f0af9812 100644 --- a/src/msg.cpp +++ b/src/msg.cpp @@ -43,38 +43,31 @@ // Check whether the sizes of public representation of the message (zmq_msg_t) // and private representation of the message (zmq::msg_t) match. -typedef char zmq_msg_size_check - [2 * ((sizeof (zmq::msg_t) == sizeof (zmq_msg_t)) != 0) - 1]; +typedef char + zmq_msg_size_check[2 * ((sizeof (zmq::msg_t) == sizeof (zmq_msg_t)) != 0) + - 1]; bool zmq::msg_t::check () const { - return u.base.type >= type_min && u.base.type <= type_max; + return u.base.type >= type_min && u.base.type <= type_max; } -int zmq::msg_t::init (void* data_, size_t size_, - msg_free_fn* ffn_, void* hint, - content_t* content_) +int zmq::msg_t::init ( + void *data_, size_t size_, msg_free_fn *ffn_, void *hint, content_t *content_) { if (size_ < max_vsm_size) { - int const rc = init_size(size_); + int const rc = init_size (size_); - if (rc != -1) - { - memcpy(data(), data_, size_); + if (rc != -1) { + memcpy (data (), data_, size_); return 0; - } - else - { + } else { return -1; } - } - else if(content_) - { - return init_external_storage(content_, data_, size_, ffn_, hint); - } - else - { - return init_data(data_, size_, ffn_, hint); + } else if (content_) { + return init_external_storage (content_, data_, size_, ffn_, hint); + } else { + return init_data (data_, size_, ffn_, hint); } } @@ -98,8 +91,7 @@ int zmq::msg_t::init_size (size_t size_) u.vsm.size = (unsigned char) size_; u.vsm.group[0] = '\0'; u.vsm.routing_id = 0; - } - else { + } else { u.lmsg.metadata = NULL; u.lmsg.type = type_lmsg; u.lmsg.flags = 0; @@ -107,7 +99,7 @@ int zmq::msg_t::init_size (size_t size_) u.lmsg.routing_id = 0; u.lmsg.content = NULL; if (sizeof (content_t) + size_ > size_) - u.lmsg.content = (content_t*) malloc (sizeof (content_t) + size_); + u.lmsg.content = (content_t *) malloc (sizeof (content_t) + size_); if (unlikely (!u.lmsg.content)) { errno = ENOMEM; return -1; @@ -122,11 +114,14 @@ int zmq::msg_t::init_size (size_t size_) return 0; } -int zmq::msg_t::init_external_storage(content_t* content_, void* data_, size_t size_, - msg_free_fn *ffn_, void* hint_) +int zmq::msg_t::init_external_storage (content_t *content_, + void *data_, + size_t size_, + msg_free_fn *ffn_, + void *hint_) { - zmq_assert(NULL != data_); - zmq_assert(NULL != content_); + zmq_assert (NULL != data_); + zmq_assert (NULL != content_); u.zclmsg.metadata = NULL; u.zclmsg.type = type_zclmsg; @@ -139,13 +134,15 @@ int zmq::msg_t::init_external_storage(content_t* content_, void* data_, size_t s u.zclmsg.content->size = size_; u.zclmsg.content->ffn = ffn_; u.zclmsg.content->hint = hint_; - new (&u.zclmsg.content->refcnt) zmq::atomic_counter_t(); + new (&u.zclmsg.content->refcnt) zmq::atomic_counter_t (); return 0; } -int zmq::msg_t::init_data (void *data_, size_t size_, - msg_free_fn *ffn_, void *hint_) +int zmq::msg_t::init_data (void *data_, + size_t size_, + msg_free_fn *ffn_, + void *hint_) { // If data is NULL and size is not 0, a segfault // would occur once the data is accessed @@ -160,14 +157,13 @@ int zmq::msg_t::init_data (void *data_, size_t size_, u.cmsg.size = size_; u.cmsg.group[0] = '\0'; u.cmsg.routing_id = 0; - } - else { + } else { u.lmsg.metadata = NULL; u.lmsg.type = type_lmsg; u.lmsg.flags = 0; u.lmsg.group[0] = '\0'; u.lmsg.routing_id = 0; - u.lmsg.content = (content_t*) malloc (sizeof (content_t)); + u.lmsg.content = (content_t *) malloc (sizeof (content_t)); if (!u.lmsg.content) { errno = ENOMEM; return -1; @@ -180,7 +176,6 @@ int zmq::msg_t::init_data (void *data_, size_t size_, new (&u.lmsg.content->refcnt) zmq::atomic_counter_t (); } return 0; - } int zmq::msg_t::init_delimiter () @@ -222,44 +217,40 @@ int zmq::msg_t::close () } if (u.base.type == type_lmsg) { - // If the content is not shared, or if it is shared and the reference // count has dropped to zero, deallocate it. - if (!(u.lmsg.flags & msg_t::shared) || - !u.lmsg.content->refcnt.sub (1)) { - + if (!(u.lmsg.flags & msg_t::shared) + || !u.lmsg.content->refcnt.sub (1)) { // We used "placement new" operator to initialize the reference // counter so we call the destructor explicitly now. u.lmsg.content->refcnt.~atomic_counter_t (); if (u.lmsg.content->ffn) u.lmsg.content->ffn (u.lmsg.content->data, - u.lmsg.content->hint); + u.lmsg.content->hint); free (u.lmsg.content); } } - if (is_zcmsg()) - { - zmq_assert(u.zclmsg.content->ffn); + if (is_zcmsg ()) { + zmq_assert (u.zclmsg.content->ffn); // If the content is not shared, or if it is shared and the reference // count has dropped to zero, deallocate it. - if (!(u.zclmsg.flags & msg_t::shared) || - !u.zclmsg.content->refcnt.sub (1)) { - + if (!(u.zclmsg.flags & msg_t::shared) + || !u.zclmsg.content->refcnt.sub (1)) { // We used "placement new" operator to initialize the reference // counter so we call the destructor explicitly now. u.zclmsg.content->refcnt.~atomic_counter_t (); u.zclmsg.content->ffn (u.zclmsg.content->data, - u.zclmsg.content->hint); + u.zclmsg.content->hint); } } if (u.base.metadata != NULL) { if (u.base.metadata->drop_ref ()) { - LIBZMQ_DELETE(u.base.metadata); + LIBZMQ_DELETE (u.base.metadata); } u.base.metadata = NULL; } @@ -303,8 +294,7 @@ int zmq::msg_t::copy (msg_t &src_) if (unlikely (rc < 0)) return rc; - if (src_.u.base.type == type_lmsg ) { - + if (src_.u.base.type == type_lmsg) { // One reference is added to shared messages. Non-shared messages // are turned into shared messages and reference count is set to 2. if (src_.u.lmsg.flags & msg_t::shared) @@ -315,15 +305,14 @@ int zmq::msg_t::copy (msg_t &src_) } } - if (src_.is_zcmsg()) { - + if (src_.is_zcmsg ()) { // One reference is added to shared messages. Non-shared messages // are turned into shared messages and reference count is set to 2. if (src_.u.zclmsg.flags & msg_t::shared) - src_.refcnt()->add (1); + src_.refcnt ()->add (1); else { src_.u.zclmsg.flags |= msg_t::shared; - src_.refcnt()->set (2); + src_.refcnt ()->set (2); } } if (src_.u.base.metadata != NULL) @@ -332,7 +321,6 @@ int zmq::msg_t::copy (msg_t &src_) *this = src_; return 0; - } void *zmq::msg_t::data () @@ -341,17 +329,17 @@ void *zmq::msg_t::data () zmq_assert (check ()); switch (u.base.type) { - case type_vsm: - return u.vsm.data; - case type_lmsg: - return u.lmsg.content->data; - case type_cmsg: - return u.cmsg.data; - case type_zclmsg: - return u.zclmsg.content->data; - default: - zmq_assert (false); - return NULL; + case type_vsm: + return u.vsm.data; + case type_lmsg: + return u.lmsg.content->data; + case type_cmsg: + return u.cmsg.data; + case type_zclmsg: + return u.zclmsg.content->data; + default: + zmq_assert (false); + return NULL; } } @@ -361,17 +349,17 @@ size_t zmq::msg_t::size () const zmq_assert (check ()); switch (u.base.type) { - case type_vsm: - return u.vsm.size; - case type_lmsg: - return u.lmsg.content->size; - case type_zclmsg: - return u.zclmsg.content->size; - case type_cmsg: - return u.cmsg.size; - default: - zmq_assert (false); - return 0; + case type_vsm: + return u.vsm.size; + case type_lmsg: + return u.lmsg.content->size; + case type_zclmsg: + return u.zclmsg.content->size; + case type_cmsg: + return u.cmsg.size; + default: + zmq_assert (false); + return 0; } } @@ -407,7 +395,7 @@ void zmq::msg_t::reset_metadata () { if (u.base.metadata) { if (u.base.metadata->drop_ref ()) { - LIBZMQ_DELETE(u.base.metadata); + LIBZMQ_DELETE (u.base.metadata); } u.base.metadata = NULL; } @@ -438,17 +426,17 @@ bool zmq::msg_t::is_cmsg () const return u.base.type == type_cmsg; } -bool zmq::msg_t::is_zcmsg() const +bool zmq::msg_t::is_zcmsg () const { return u.base.type == type_zclmsg; } -bool zmq::msg_t::is_join() const +bool zmq::msg_t::is_join () const { return u.base.type == type_join; } -bool zmq::msg_t::is_leave() const +bool zmq::msg_t::is_leave () const { return u.base.type == type_leave; } @@ -466,11 +454,11 @@ void zmq::msg_t::add_refs (int refs_) // VSMs, CMSGS and delimiters can be copied straight away. The only // message type that needs special care are long messages. - if (u.base.type == type_lmsg || is_zcmsg() ) { + if (u.base.type == type_lmsg || is_zcmsg ()) { if (u.base.flags & msg_t::shared) - refcnt()->add (refs_); + refcnt ()->add (refs_); else { - refcnt()->set (refs_ + 1); + refcnt ()->set (refs_ + 1); u.base.flags |= msg_t::shared; } } @@ -488,13 +476,14 @@ bool zmq::msg_t::rm_refs (int refs_) return true; // If there's only one reference close the message. - if ( (u.base.type != type_zclmsg && u.base.type != type_lmsg) || !(u.base.flags & msg_t::shared)) { + if ((u.base.type != type_zclmsg && u.base.type != type_lmsg) + || !(u.base.flags & msg_t::shared)) { close (); return false; } // The only message type that needs special care are long and zcopy messages. - if (u.base.type == type_lmsg && !u.lmsg.content->refcnt.sub(refs_)) { + if (u.base.type == type_lmsg && !u.lmsg.content->refcnt.sub (refs_)) { // We used "placement new" operator to initialize the reference // counter so we call the destructor explicitly now. u.lmsg.content->refcnt.~atomic_counter_t (); @@ -506,10 +495,11 @@ bool zmq::msg_t::rm_refs (int refs_) return false; } - if (is_zcmsg() && !u.zclmsg.content->refcnt.sub(refs_)) { + if (is_zcmsg () && !u.zclmsg.content->refcnt.sub (refs_)) { // storage for rfcnt is provided externally if (u.zclmsg.content->ffn) { - u.zclmsg.content->ffn(u.zclmsg.content->data, u.zclmsg.content->hint); + u.zclmsg.content->ffn (u.zclmsg.content->data, + u.zclmsg.content->hint); } return false; @@ -539,20 +529,19 @@ int zmq::msg_t::reset_routing_id () return 0; } -const char * zmq::msg_t::group () +const char *zmq::msg_t::group () { return u.base.group; } -int zmq::msg_t::set_group (const char * group_) +int zmq::msg_t::set_group (const char *group_) { return set_group (group_, strlen (group_)); } -int zmq::msg_t::set_group (const char * group_, size_t length_) +int zmq::msg_t::set_group (const char *group_, size_t length_) { - if (length_> ZMQ_GROUP_MAX_LENGTH) - { + if (length_ > ZMQ_GROUP_MAX_LENGTH) { errno = EINVAL; return -1; } @@ -563,16 +552,15 @@ int zmq::msg_t::set_group (const char * group_, size_t length_) return 0; } -zmq::atomic_counter_t *zmq::msg_t::refcnt() +zmq::atomic_counter_t *zmq::msg_t::refcnt () { - switch(u.base.type) - { + switch (u.base.type) { case type_lmsg: return &u.lmsg.content->refcnt; case type_zclmsg: return &u.zclmsg.content->refcnt; default: - zmq_assert(false); + zmq_assert (false); return NULL; } } diff --git a/src/msg.hpp b/src/msg.hpp index 4ce4b1f4b1..e1320b88cc 100644 --- a/src/msg.hpp +++ b/src/msg.hpp @@ -42,227 +42,232 @@ // Signature for free function to deallocate the message content. // Note that it has to be declared as "C" so that it is the same as // zmq_free_fn defined in zmq.h. -extern "C" -{ - typedef void (msg_free_fn) (void *data, void *hint); +extern "C" { +typedef void(msg_free_fn) (void *data, void *hint); } namespace zmq { +// Note that this structure needs to be explicitly constructed +// (init functions) and destructed (close function). - // Note that this structure needs to be explicitly constructed - // (init functions) and destructed (close function). - - class msg_t +class msg_t +{ + public: + // Shared message buffer. Message data are either allocated in one + // continuous block along with this structure - thus avoiding one + // malloc/free pair or they are stored in user-supplied memory. + // In the latter case, ffn member stores pointer to the function to be + // used to deallocate the data. If the buffer is actually shared (there + // are at least 2 references to it) refcount member contains number of + // references. + struct content_t { - public: - - // Shared message buffer. Message data are either allocated in one - // continuous block along with this structure - thus avoiding one - // malloc/free pair or they are stored in user-supplied memory. - // In the latter case, ffn member stores pointer to the function to be - // used to deallocate the data. If the buffer is actually shared (there - // are at least 2 references to it) refcount member contains number of - // references. - struct content_t - { - void *data; - size_t size; - msg_free_fn *ffn; - void *hint; - zmq::atomic_counter_t refcnt; - }; + void *data; + size_t size; + msg_free_fn *ffn; + void *hint; + zmq::atomic_counter_t refcnt; + }; - // Message flags. - enum - { - more = 1, // Followed by more parts - command = 2, // Command frame (see ZMTP spec) - credential = 32, - routing_id = 64, - shared = 128 - }; + // Message flags. + enum + { + more = 1, // Followed by more parts + command = 2, // Command frame (see ZMTP spec) + credential = 32, + routing_id = 64, + shared = 128 + }; - bool check () const; - int init(); + bool check () const; + int init (); - int init (void* data, size_t size_, - msg_free_fn* ffn_, void* hint, - content_t* content_ = NULL); + int init (void *data, + size_t size_, + msg_free_fn *ffn_, + void *hint, + content_t *content_ = NULL); - int init_size (size_t size_); - int init_data (void *data_, size_t size_, msg_free_fn *ffn_, - void *hint_); - int init_external_storage(content_t* content_, void *data_, size_t size_, - msg_free_fn *ffn_, void *hint_); - int init_delimiter (); - int init_join (); - int init_leave (); - int close (); - int move (msg_t &src_); - int copy (msg_t &src_); - void *data (); - size_t size () const; - unsigned char flags () const; - void set_flags (unsigned char flags_); - void reset_flags (unsigned char flags_); - metadata_t *metadata () const; - void set_metadata (metadata_t *metadata_); - void reset_metadata (); - bool is_routing_id () const; - bool is_credential () const; - bool is_delimiter () const; - bool is_join () const; - bool is_leave () const; - bool is_vsm () const; - bool is_cmsg () const; - bool is_zcmsg() const; - uint32_t get_routing_id (); - int set_routing_id (uint32_t routing_id_); - int reset_routing_id (); - const char * group (); - int set_group (const char* group_); - int set_group (const char*, size_t length); + int init_size (size_t size_); + int init_data (void *data_, size_t size_, msg_free_fn *ffn_, void *hint_); + int init_external_storage (content_t *content_, + void *data_, + size_t size_, + msg_free_fn *ffn_, + void *hint_); + int init_delimiter (); + int init_join (); + int init_leave (); + int close (); + int move (msg_t &src_); + int copy (msg_t &src_); + void *data (); + size_t size () const; + unsigned char flags () const; + void set_flags (unsigned char flags_); + void reset_flags (unsigned char flags_); + metadata_t *metadata () const; + void set_metadata (metadata_t *metadata_); + void reset_metadata (); + bool is_routing_id () const; + bool is_credential () const; + bool is_delimiter () const; + bool is_join () const; + bool is_leave () const; + bool is_vsm () const; + bool is_cmsg () const; + bool is_zcmsg () const; + uint32_t get_routing_id (); + int set_routing_id (uint32_t routing_id_); + int reset_routing_id (); + const char *group (); + int set_group (const char *group_); + int set_group (const char *, size_t length); - // After calling this function you can copy the message in POD-style - // refs_ times. No need to call copy. - void add_refs (int refs_); + // After calling this function you can copy the message in POD-style + // refs_ times. No need to call copy. + void add_refs (int refs_); - // Removes references previously added by add_refs. If the number of - // references drops to 0, the message is closed and false is returned. - bool rm_refs (int refs_); + // Removes references previously added by add_refs. If the number of + // references drops to 0, the message is closed and false is returned. + bool rm_refs (int refs_); - // Size in bytes of the largest message that is still copied around - // rather than being reference-counted. - enum { msg_t_size = 64 }; - enum { max_vsm_size = msg_t_size - (sizeof (metadata_t *) + - 3 + - 16 + - sizeof (uint32_t))}; - private: - zmq::atomic_counter_t* refcnt(); + // Size in bytes of the largest message that is still copied around + // rather than being reference-counted. + enum + { + msg_t_size = 64 + }; + enum + { + max_vsm_size = + msg_t_size - (sizeof (metadata_t *) + 3 + 16 + sizeof (uint32_t)) + }; - // Different message types. - enum type_t - { - type_min = 101, - // VSM messages store the content in the message itself - type_vsm = 101, - // LMSG messages store the content in malloc-ed memory - type_lmsg = 102, - // Delimiter messages are used in envelopes - type_delimiter = 103, - // CMSG messages point to constant data - type_cmsg = 104, + private: + zmq::atomic_counter_t *refcnt (); - // zero-copy LMSG message for v2_decoder - type_zclmsg = 105, + // Different message types. + enum type_t + { + type_min = 101, + // VSM messages store the content in the message itself + type_vsm = 101, + // LMSG messages store the content in malloc-ed memory + type_lmsg = 102, + // Delimiter messages are used in envelopes + type_delimiter = 103, + // CMSG messages point to constant data + type_cmsg = 104, - // Join message for radio_dish - type_join = 106, + // zero-copy LMSG message for v2_decoder + type_zclmsg = 105, - // Leave message for radio_dish - type_leave = 107, + // Join message for radio_dish + type_join = 106, - type_max = 107 - }; + // Leave message for radio_dish + type_leave = 107, - // Note that fields shared between different message types are not - // moved to the parent class (msg_t). This way we get tighter packing - // of the data. Shared fields can be accessed via 'base' member of - // the union. - union { - struct { - metadata_t *metadata; - unsigned char unused [msg_t_size - (sizeof (metadata_t *) + - 2 + - 16 + - sizeof (uint32_t))]; - unsigned char type; - unsigned char flags; - char group [16]; - uint32_t routing_id; - } base; - struct { - metadata_t *metadata; - unsigned char data [max_vsm_size]; - unsigned char size; - unsigned char type; - unsigned char flags; - char group [16]; - uint32_t routing_id; - } vsm; - struct { - metadata_t *metadata; - content_t *content; - unsigned char unused [msg_t_size - (sizeof (metadata_t *) + - sizeof (content_t*) + - 2 + - 16 + - sizeof (uint32_t))]; - unsigned char type; - unsigned char flags; - char group [16]; - uint32_t routing_id; - } lmsg; - struct { - metadata_t *metadata; - content_t *content; - unsigned char unused [msg_t_size - (sizeof (metadata_t *) + - sizeof (content_t*) + - 2 + - 16 + - sizeof (uint32_t))]; - unsigned char type; - unsigned char flags; - char group [16]; - uint32_t routing_id; - } zclmsg; - struct { - metadata_t *metadata; - void* data; - size_t size; - unsigned char unused [msg_t_size - (sizeof (metadata_t *) + - sizeof (void*) + - sizeof (size_t) + - 2 + - 16 + - sizeof (uint32_t))]; - unsigned char type; - unsigned char flags; - char group [16]; - uint32_t routing_id; - } cmsg; - struct { - metadata_t *metadata; - unsigned char unused [msg_t_size - (sizeof (metadata_t *) + - 2 + - 16 + - sizeof (uint32_t))]; - unsigned char type; - unsigned char flags; - char group [16]; - uint32_t routing_id; - } delimiter; - } u; + type_max = 107 }; - inline int close_and_return (zmq::msg_t *msg, int echo) + // Note that fields shared between different message types are not + // moved to the parent class (msg_t). This way we get tighter packing + // of the data. Shared fields can be accessed via 'base' member of + // the union. + union { - // Since we abort on close failure we preserve errno for success case. - int err = errno; - const int rc = msg->close (); - errno_assert (rc == 0); - errno = err; - return echo; - } + struct + { + metadata_t *metadata; + unsigned char + unused[msg_t_size + - (sizeof (metadata_t *) + 2 + 16 + sizeof (uint32_t))]; + unsigned char type; + unsigned char flags; + char group[16]; + uint32_t routing_id; + } base; + struct + { + metadata_t *metadata; + unsigned char data[max_vsm_size]; + unsigned char size; + unsigned char type; + unsigned char flags; + char group[16]; + uint32_t routing_id; + } vsm; + struct + { + metadata_t *metadata; + content_t *content; + unsigned char unused[msg_t_size + - (sizeof (metadata_t *) + sizeof (content_t *) + + 2 + 16 + sizeof (uint32_t))]; + unsigned char type; + unsigned char flags; + char group[16]; + uint32_t routing_id; + } lmsg; + struct + { + metadata_t *metadata; + content_t *content; + unsigned char unused[msg_t_size + - (sizeof (metadata_t *) + sizeof (content_t *) + + 2 + 16 + sizeof (uint32_t))]; + unsigned char type; + unsigned char flags; + char group[16]; + uint32_t routing_id; + } zclmsg; + struct + { + metadata_t *metadata; + void *data; + size_t size; + unsigned char + unused[msg_t_size + - (sizeof (metadata_t *) + sizeof (void *) + + sizeof (size_t) + 2 + 16 + sizeof (uint32_t))]; + unsigned char type; + unsigned char flags; + char group[16]; + uint32_t routing_id; + } cmsg; + struct + { + metadata_t *metadata; + unsigned char + unused[msg_t_size + - (sizeof (metadata_t *) + 2 + 16 + sizeof (uint32_t))]; + unsigned char type; + unsigned char flags; + char group[16]; + uint32_t routing_id; + } delimiter; + } u; +}; - inline int close_and_return (zmq::msg_t msg [], int count, int echo) - { - for (int i = 0; i < count; i++) - close_and_return (&msg [i], 0); - return echo; - } +inline int close_and_return (zmq::msg_t *msg, int echo) +{ + // Since we abort on close failure we preserve errno for success case. + int err = errno; + const int rc = msg->close (); + errno_assert (rc == 0); + errno = err; + return echo; +} + +inline int close_and_return (zmq::msg_t msg[], int count, int echo) +{ + for (int i = 0; i < count; i++) + close_and_return (&msg[i], 0); + return echo; +} } #endif diff --git a/src/mtrie.cpp b/src/mtrie.cpp index a280622148..cf3f3d0181 100644 --- a/src/mtrie.cpp +++ b/src/mtrie.cpp @@ -38,25 +38,20 @@ #include "macros.hpp" #include "mtrie.hpp" -zmq::mtrie_t::mtrie_t () : - pipes (0), - min (0), - count (0), - live_nodes (0) +zmq::mtrie_t::mtrie_t () : pipes (0), min (0), count (0), live_nodes (0) { } zmq::mtrie_t::~mtrie_t () { - LIBZMQ_DELETE(pipes); + LIBZMQ_DELETE (pipes); if (count == 1) { zmq_assert (next.node); - LIBZMQ_DELETE(next.node); - } - else if (count > 1) { + LIBZMQ_DELETE (next.node); + } else if (count > 1) { for (unsigned short i = 0; i != count; ++i) { - LIBZMQ_DELETE(next.table[i]); + LIBZMQ_DELETE (next.table[i]); } free (next.table); } @@ -67,8 +62,9 @@ bool zmq::mtrie_t::add (unsigned char *prefix_, size_t size_, pipe_t *pipe_) return add_helper (prefix_, size_, pipe_); } -bool zmq::mtrie_t::add_helper (unsigned char *prefix_, size_t size_, - pipe_t *pipe_) +bool zmq::mtrie_t::add_helper (unsigned char *prefix_, + size_t size_, + pipe_t *pipe_) { // We are at the node corresponding to the prefix. We are done. if (!size_) { @@ -83,49 +79,42 @@ bool zmq::mtrie_t::add_helper (unsigned char *prefix_, size_t size_, unsigned char c = *prefix_; if (c < min || c >= min + count) { - // The character is out of range of currently handled // characters. We have to extend the table. if (!count) { min = c; count = 1; next.node = NULL; - } - else - if (count == 1) { + } else if (count == 1) { unsigned char oldc = min; mtrie_t *oldp = next.node; count = (min < c ? c - min : min - c) + 1; - next.table = (mtrie_t**) - malloc (sizeof (mtrie_t*) * count); + next.table = (mtrie_t **) malloc (sizeof (mtrie_t *) * count); alloc_assert (next.table); for (unsigned short i = 0; i != count; ++i) - next.table [i] = 0; + next.table[i] = 0; min = std::min (min, c); - next.table [oldc - min] = oldp; - } - else - if (min < c) { + next.table[oldc - min] = oldp; + } else if (min < c) { // The new character is above the current character range. unsigned short old_count = count; count = c - min + 1; - next.table = (mtrie_t**) realloc (next.table, - sizeof (mtrie_t*) * count); + next.table = + (mtrie_t **) realloc (next.table, sizeof (mtrie_t *) * count); alloc_assert (next.table); for (unsigned short i = old_count; i != count; i++) - next.table [i] = NULL; - } - else { + next.table[i] = NULL; + } else { // The new character is below the current character range. unsigned short old_count = count; count = (min + old_count) - c; - next.table = (mtrie_t**) realloc (next.table, - sizeof (mtrie_t*) * count); + next.table = + (mtrie_t **) realloc (next.table, sizeof (mtrie_t *) * count); alloc_assert (next.table); memmove (next.table + min - c, next.table, - old_count * sizeof (mtrie_t*)); + old_count * sizeof (mtrie_t *)); for (unsigned short i = 0; i != min - c; i++) - next.table [i] = NULL; + next.table[i] = NULL; min = c; } } @@ -138,31 +127,38 @@ bool zmq::mtrie_t::add_helper (unsigned char *prefix_, size_t size_, ++live_nodes; } return next.node->add_helper (prefix_ + 1, size_ - 1, pipe_); - } - else { - if (!next.table [c - min]) { - next.table [c - min] = new (std::nothrow) mtrie_t; - alloc_assert (next.table [c - min]); + } else { + if (!next.table[c - min]) { + next.table[c - min] = new (std::nothrow) mtrie_t; + alloc_assert (next.table[c - min]); ++live_nodes; } - return next.table [c - min]->add_helper (prefix_ + 1, size_ - 1, pipe_); + return next.table[c - min]->add_helper (prefix_ + 1, size_ - 1, pipe_); } } void zmq::mtrie_t::rm (pipe_t *pipe_, - void (*func_) (unsigned char *data_, size_t size_, void *arg_), - void *arg_, bool call_on_uniq_) + void (*func_) (unsigned char *data_, + size_t size_, + void *arg_), + void *arg_, + bool call_on_uniq_) { unsigned char *buff = NULL; rm_helper (pipe_, &buff, 0, 0, func_, arg_, call_on_uniq_); free (buff); } -void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_, - size_t buffsize_, size_t maxbuffsize_, - void (*func_) (unsigned char *data_, size_t size_, void *arg_), - void *arg_, bool call_on_uniq_) +void zmq::mtrie_t::rm_helper (pipe_t *pipe_, + unsigned char **buff_, + size_t buffsize_, + size_t maxbuffsize_, + void (*func_) (unsigned char *data_, + size_t size_, + void *arg_), + void *arg_, + bool call_on_uniq_) { // Remove the subscription from this node. if (pipes && pipes->erase (pipe_)) { @@ -171,14 +167,14 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_, } if (pipes->empty ()) { - LIBZMQ_DELETE(pipes); + LIBZMQ_DELETE (pipes); } } // Adjust the buffer. if (buffsize_ >= maxbuffsize_) { maxbuffsize_ = buffsize_ + 256; - *buff_ = (unsigned char*) realloc (*buff_, maxbuffsize_); + *buff_ = (unsigned char *) realloc (*buff_, maxbuffsize_); alloc_assert (*buff_); } @@ -188,14 +184,14 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_, // If there's one subnode (optimisation). if (count == 1) { - (*buff_) [buffsize_] = min; + (*buff_)[buffsize_] = min; buffsize_++; - next.node->rm_helper (pipe_, buff_, buffsize_, maxbuffsize_, - func_, arg_, call_on_uniq_); + next.node->rm_helper (pipe_, buff_, buffsize_, maxbuffsize_, func_, + arg_, call_on_uniq_); // Prune the node if it was made redundant by the removal if (next.node->is_redundant ()) { - LIBZMQ_DELETE(next.node); + LIBZMQ_DELETE (next.node); count = 0; --live_nodes; zmq_assert (live_nodes == 0); @@ -210,19 +206,18 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_, // New max non-null character in the node table after the removal unsigned char new_max = min; for (unsigned short c = 0; c != count; c++) { - (*buff_) [buffsize_] = min + c; - if (next.table [c]) { - next.table [c]->rm_helper (pipe_, buff_, buffsize_ + 1, - maxbuffsize_, func_, arg_, call_on_uniq_); + (*buff_)[buffsize_] = min + c; + if (next.table[c]) { + next.table[c]->rm_helper (pipe_, buff_, buffsize_ + 1, maxbuffsize_, + func_, arg_, call_on_uniq_); // Prune redundant nodes from the mtrie - if (next.table [c]->is_redundant ()) { - LIBZMQ_DELETE(next.table[c]); + if (next.table[c]->is_redundant ()) { + LIBZMQ_DELETE (next.table[c]); zmq_assert (live_nodes > 0); --live_nodes; - } - else { + } else { // The node is not redundant, so it's a candidate for being // the new min/max node. // @@ -247,22 +242,19 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_, count = 0; } // Compact the node table if possible - else - if (live_nodes == 1) { + else if (live_nodes == 1) { // If there's only one live node in the table we can // switch to using the more compact single-node // representation zmq_assert (new_min == new_max); zmq_assert (new_min >= min && new_min < min + count); - mtrie_t *node = next.table [new_min - min]; + mtrie_t *node = next.table[new_min - min]; zmq_assert (node); free (next.table); next.node = node; count = 1; min = new_min; - } - else - if (new_min > min || new_max < min + count - 1) { + } else if (new_min > min || new_max < min + count - 1) { zmq_assert (new_max - new_min + 1 > 1); mtrie_t **old_table = next.table; @@ -272,11 +264,11 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_, zmq_assert (new_max - new_min + 1 < count); count = new_max - new_min + 1; - next.table = (mtrie_t**) malloc (sizeof (mtrie_t*) * count); + next.table = (mtrie_t **) malloc (sizeof (mtrie_t *) * count); alloc_assert (next.table); memmove (next.table, old_table + (new_min - min), - sizeof (mtrie_t*) * count); + sizeof (mtrie_t *) * count); free (old_table); min = new_min; @@ -288,15 +280,16 @@ bool zmq::mtrie_t::rm (unsigned char *prefix_, size_t size_, pipe_t *pipe_) return rm_helper (prefix_, size_, pipe_); } -bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_, - pipe_t *pipe_) +bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, + size_t size_, + pipe_t *pipe_) { if (!size_) { if (pipes) { pipes_t::size_type erased = pipes->erase (pipe_); zmq_assert (erased == 1); if (pipes->empty ()) { - LIBZMQ_DELETE(pipes); + LIBZMQ_DELETE (pipes); } } return !pipes; @@ -306,8 +299,7 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_, if (!count || c < min || c >= min + count) return false; - mtrie_t *next_node = - count == 1 ? next.node : next.table [c - min]; + mtrie_t *next_node = count == 1 ? next.node : next.table[c - min]; if (!next_node) return false; @@ -315,7 +307,7 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_, bool ret = next_node->rm_helper (prefix_ + 1, size_ - 1, pipe_); if (next_node->is_redundant ()) { - LIBZMQ_DELETE(next_node); + LIBZMQ_DELETE (next_node); zmq_assert (count > 0); if (count == 1) { @@ -323,9 +315,8 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_, count = 0; --live_nodes; zmq_assert (live_nodes == 0); - } - else { - next.table [c - min] = 0; + } else { + next.table[c - min] = 0; zmq_assert (live_nodes > 1); --live_nodes; @@ -336,47 +327,43 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_, // representation unsigned short i; for (i = 0; i < count; ++i) - if (next.table [i]) + if (next.table[i]) break; zmq_assert (i < count); min += i; count = 1; - mtrie_t *oldp = next.table [i]; + mtrie_t *oldp = next.table[i]; free (next.table); next.node = oldp; - } - else - if (c == min) { + } else if (c == min) { // We can compact the table "from the left" unsigned short i; for (i = 1; i < count; ++i) - if (next.table [i]) + if (next.table[i]) break; zmq_assert (i < count); min += i; count -= i; mtrie_t **old_table = next.table; - next.table = (mtrie_t**) malloc (sizeof (mtrie_t*) * count); + next.table = (mtrie_t **) malloc (sizeof (mtrie_t *) * count); alloc_assert (next.table); - memmove (next.table, old_table + i, sizeof (mtrie_t*) * count); + memmove (next.table, old_table + i, sizeof (mtrie_t *) * count); free (old_table); - } - else - if (c == min + count - 1) { + } else if (c == min + count - 1) { // We can compact the table "from the right" unsigned short i; for (i = 1; i < count; ++i) - if (next.table [count - 1 - i]) + if (next.table[count - 1 - i]) break; zmq_assert (i < count); count -= i; mtrie_t **old_table = next.table; - next.table = (mtrie_t**) malloc (sizeof (mtrie_t*) * count); + next.table = (mtrie_t **) malloc (sizeof (mtrie_t *) * count); alloc_assert (next.table); - memmove (next.table, old_table, sizeof (mtrie_t*) * count); + memmove (next.table, old_table, sizeof (mtrie_t *) * count); free (old_table); } } @@ -385,16 +372,17 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_, return ret; } -void zmq::mtrie_t::match (unsigned char *data_, size_t size_, - void (*func_) (pipe_t *pipe_, void *arg_), void *arg_) +void zmq::mtrie_t::match (unsigned char *data_, + size_t size_, + void (*func_) (pipe_t *pipe_, void *arg_), + void *arg_) { mtrie_t *current = this; while (true) { - // Signal the pipes attached to this node. if (current->pipes) { for (pipes_t::iterator it = current->pipes->begin (); - it != current->pipes->end (); ++it) + it != current->pipes->end (); ++it) func_ (*it, arg_); } @@ -408,7 +396,7 @@ void zmq::mtrie_t::match (unsigned char *data_, size_t size_, // If there's one subnode (optimisation). if (current->count == 1) { - if (data_ [0] != current->min) + if (data_[0] != current->min) break; current = current->next.node; data_++; @@ -417,12 +405,12 @@ void zmq::mtrie_t::match (unsigned char *data_, size_t size_, } // If there are multiple subnodes. - if (data_ [0] < current->min || data_ [0] >= - current->min + current->count) + if (data_[0] < current->min + || data_[0] >= current->min + current->count) break; - if (!current->next.table [data_ [0] - current->min]) + if (!current->next.table[data_[0] - current->min]) break; - current = current->next.table [data_ [0] - current->min]; + current = current->next.table[data_[0] - current->min]; data_++; size_--; } diff --git a/src/mtrie.hpp b/src/mtrie.hpp index 632e0d7e5c..4b5eb88197 100644 --- a/src/mtrie.hpp +++ b/src/mtrie.hpp @@ -37,66 +37,67 @@ namespace zmq { +class pipe_t; - class pipe_t; +// Multi-trie. Each node in the trie is a set of pointers to pipes. - // Multi-trie. Each node in the trie is a set of pointers to pipes. - - class mtrie_t +class mtrie_t +{ + public: + mtrie_t (); + ~mtrie_t (); + + // Add key to the trie. Returns true if it's a new subscription + // rather than a duplicate. + bool add (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_); + + // Remove all subscriptions for a specific peer from the trie. + // The call_on_uniq_ flag controls if the callback is invoked + // when there are no subscriptions left on some topics or on + // every removal. + void rm (zmq::pipe_t *pipe_, + void (*func_) (unsigned char *data_, size_t size_, void *arg_), + void *arg_, + bool call_on_uniq_); + + // Remove specific subscription from the trie. Return true is it was + // actually removed rather than de-duplicated. + bool rm (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_); + + // Signal all the matching pipes. + void match (unsigned char *data_, + size_t size_, + void (*func_) (zmq::pipe_t *pipe_, void *arg_), + void *arg_); + + private: + bool add_helper (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_); + void + rm_helper (zmq::pipe_t *pipe_, + unsigned char **buff_, + size_t buffsize_, + size_t maxbuffsize_, + void (*func_) (unsigned char *data_, size_t size_, void *arg_), + void *arg_, + bool call_on_uniq_); + bool rm_helper (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_); + bool is_redundant () const; + + typedef std::set pipes_t; + pipes_t *pipes; + + unsigned char min; + unsigned short count; + unsigned short live_nodes; + union { - public: - - mtrie_t (); - ~mtrie_t (); - - // Add key to the trie. Returns true if it's a new subscription - // rather than a duplicate. - bool add (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_); - - // Remove all subscriptions for a specific peer from the trie. - // The call_on_uniq_ flag controls if the callback is invoked - // when there are no subscriptions left on some topics or on - // every removal. - void rm (zmq::pipe_t *pipe_, - void (*func_) (unsigned char *data_, size_t size_, void *arg_), - void *arg_, bool call_on_uniq_); - - // Remove specific subscription from the trie. Return true is it was - // actually removed rather than de-duplicated. - bool rm (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_); - - // Signal all the matching pipes. - void match (unsigned char *data_, size_t size_, - void (*func_) (zmq::pipe_t *pipe_, void *arg_), void *arg_); - - private: - - bool add_helper (unsigned char *prefix_, size_t size_, - zmq::pipe_t *pipe_); - void rm_helper (zmq::pipe_t *pipe_, unsigned char **buff_, - size_t buffsize_, size_t maxbuffsize_, - void (*func_) (unsigned char *data_, size_t size_, void *arg_), - void *arg_, bool call_on_uniq_); - bool rm_helper (unsigned char *prefix_, size_t size_, - zmq::pipe_t *pipe_); - bool is_redundant () const; - - typedef std::set pipes_t; - pipes_t *pipes; - - unsigned char min; - unsigned short count; - unsigned short live_nodes; - union { - class mtrie_t *node; - class mtrie_t **table; - } next; - - mtrie_t (const mtrie_t&); - const mtrie_t &operator = (const mtrie_t&); - }; + class mtrie_t *node; + class mtrie_t **table; + } next; + mtrie_t (const mtrie_t &); + const mtrie_t &operator= (const mtrie_t &); +}; } #endif - diff --git a/src/mutex.hpp b/src/mutex.hpp index 5391a489ce..fd0cfa6cb5 100644 --- a/src/mutex.hpp +++ b/src/mutex.hpp @@ -40,49 +40,31 @@ namespace zmq { +class mutex_t +{ + public: + inline mutex_t () { InitializeCriticalSection (&cs); } + + inline ~mutex_t () { DeleteCriticalSection (&cs); } - class mutex_t + inline void lock () { EnterCriticalSection (&cs); } + + inline bool try_lock () { - public: - inline mutex_t () - { - InitializeCriticalSection (&cs); - } - - inline ~mutex_t () - { - DeleteCriticalSection (&cs); - } - - inline void lock () - { - EnterCriticalSection (&cs); - } - - inline bool try_lock () - { - return (TryEnterCriticalSection (&cs)) ? true : false; - } - - inline void unlock () - { - LeaveCriticalSection (&cs); - } - - inline CRITICAL_SECTION* get_cs() - { - return &cs; - } - - private: - - CRITICAL_SECTION cs; - - // Disable copy construction and assignment. - mutex_t (const mutex_t&); - void operator = (const mutex_t&); - }; + return (TryEnterCriticalSection (&cs)) ? true : false; + } + + inline void unlock () { LeaveCriticalSection (&cs); } + inline CRITICAL_SECTION *get_cs () { return &cs; } + + private: + CRITICAL_SECTION cs; + + // Disable copy construction and assignment. + mutex_t (const mutex_t &); + void operator= (const mutex_t &); +}; } #else @@ -91,123 +73,105 @@ namespace zmq namespace zmq { +class mutex_t +{ + public: + inline mutex_t () + { + int rc = pthread_mutexattr_init (&attr); + posix_assert (rc); + + rc = pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE); + posix_assert (rc); - class mutex_t + rc = pthread_mutex_init (&mutex, &attr); + posix_assert (rc); + } + + inline ~mutex_t () { - public: - inline mutex_t () - { - int rc = pthread_mutexattr_init(&attr); - posix_assert (rc); - - rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - posix_assert (rc); - - rc = pthread_mutex_init (&mutex, &attr); - posix_assert (rc); - } - - inline ~mutex_t () - { - int rc = pthread_mutex_destroy (&mutex); - posix_assert (rc); - - rc = pthread_mutexattr_destroy (&attr); - posix_assert (rc); - } - - inline void lock () - { - int rc = pthread_mutex_lock (&mutex); - posix_assert (rc); - } - - inline bool try_lock () - { - int rc = pthread_mutex_trylock (&mutex); - if (rc == EBUSY) - return false; - - posix_assert (rc); - return true; - } - - inline void unlock () - { - int rc = pthread_mutex_unlock (&mutex); - posix_assert (rc); - } - - inline pthread_mutex_t* get_mutex() - { - return &mutex; - } - - private: - - pthread_mutex_t mutex; - pthread_mutexattr_t attr; - - // Disable copy construction and assignment. - mutex_t (const mutex_t&); - const mutex_t &operator = (const mutex_t&); - }; + int rc = pthread_mutex_destroy (&mutex); + posix_assert (rc); -} + rc = pthread_mutexattr_destroy (&attr); + posix_assert (rc); + } -#endif + inline void lock () + { + int rc = pthread_mutex_lock (&mutex); + posix_assert (rc); + } + + inline bool try_lock () + { + int rc = pthread_mutex_trylock (&mutex); + if (rc == EBUSY) + return false; + posix_assert (rc); + return true; + } -namespace zmq -{ - struct scoped_lock_t + inline void unlock () { - scoped_lock_t (mutex_t& mutex_) - : mutex (mutex_) - { - mutex.lock (); - } + int rc = pthread_mutex_unlock (&mutex); + posix_assert (rc); + } - ~scoped_lock_t () - { - mutex.unlock (); - } + inline pthread_mutex_t *get_mutex () { return &mutex; } - private: + private: + pthread_mutex_t mutex; + pthread_mutexattr_t attr; - mutex_t& mutex; + // Disable copy construction and assignment. + mutex_t (const mutex_t &); + const mutex_t &operator= (const mutex_t &); +}; +} - // Disable copy construction and assignment. - scoped_lock_t (const scoped_lock_t&); - const scoped_lock_t &operator = (const scoped_lock_t&); - }; +#endif - struct scoped_optional_lock_t - { - scoped_optional_lock_t (mutex_t* mutex_) - : mutex (mutex_) - { - if(mutex != NULL) - mutex->lock (); - } +namespace zmq +{ +struct scoped_lock_t +{ + scoped_lock_t (mutex_t &mutex_) : mutex (mutex_) { mutex.lock (); } - ~scoped_optional_lock_t () - { - if(mutex != NULL) - mutex->unlock (); - } + ~scoped_lock_t () { mutex.unlock (); } - private: + private: + mutex_t &mutex; - mutex_t* mutex; + // Disable copy construction and assignment. + scoped_lock_t (const scoped_lock_t &); + const scoped_lock_t &operator= (const scoped_lock_t &); +}; - // Disable copy construction and assignment. - scoped_optional_lock_t (const scoped_lock_t&); - const scoped_optional_lock_t &operator = (const scoped_lock_t&); - }; +struct scoped_optional_lock_t +{ + scoped_optional_lock_t (mutex_t *mutex_) : mutex (mutex_) + { + if (mutex != NULL) + mutex->lock (); + } + + ~scoped_optional_lock_t () + { + if (mutex != NULL) + mutex->unlock (); + } + + private: + mutex_t *mutex; + // Disable copy construction and assignment. + scoped_optional_lock_t (const scoped_lock_t &); + const scoped_optional_lock_t &operator= (const scoped_lock_t &); +}; } #endif diff --git a/src/norm_engine.cpp b/src/norm_engine.cpp index 2d424d2fb8..bb8d873afb 100644 --- a/src/norm_engine.cpp +++ b/src/norm_engine.cpp @@ -9,88 +9,90 @@ #include "session_base.hpp" #include "v2_protocol.hpp" -zmq::norm_engine_t::norm_engine_t(io_thread_t* parent_, - const options_t& options_) - : io_object_t(parent_), zmq_session(NULL), options(options_), - norm_instance(NORM_INSTANCE_INVALID), norm_session(NORM_SESSION_INVALID), - is_sender(false), is_receiver(false), - zmq_encoder(0), norm_tx_stream(NORM_OBJECT_INVALID), - tx_first_msg(true), tx_more_bit(false), - zmq_output_ready(false), norm_tx_ready(false), - tx_index(0), tx_len(0), - zmq_input_ready(false) +zmq::norm_engine_t::norm_engine_t (io_thread_t *parent_, + const options_t &options_) : + io_object_t (parent_), + zmq_session (NULL), + options (options_), + norm_instance (NORM_INSTANCE_INVALID), + norm_session (NORM_SESSION_INVALID), + is_sender (false), + is_receiver (false), + zmq_encoder (0), + norm_tx_stream (NORM_OBJECT_INVALID), + tx_first_msg (true), + tx_more_bit (false), + zmq_output_ready (false), + norm_tx_ready (false), + tx_index (0), + tx_len (0), + zmq_input_ready (false) { - int rc = tx_msg.init(); - errno_assert(0 == rc); + int rc = tx_msg.init (); + errno_assert (0 == rc); } -zmq::norm_engine_t::~norm_engine_t() +zmq::norm_engine_t::~norm_engine_t () { - shutdown(); // in case it was not already called + shutdown (); // in case it was not already called } -int zmq::norm_engine_t::init(const char* network_, bool send, bool recv) +int zmq::norm_engine_t::init (const char *network_, bool send, bool recv) { // Parse the "network_" address int "iface", "addr", and "port" // norm endpoint format: [id,][;]: // First, look for optional local NormNodeId // (default NORM_NODE_ANY causes NORM to use host IP addr for NormNodeId) NormNodeId localId = NORM_NODE_ANY; - const char* ifacePtr = strchr(network_, ','); - if (NULL != ifacePtr) - { + const char *ifacePtr = strchr (network_, ','); + if (NULL != ifacePtr) { size_t idLen = ifacePtr - network_; - if (idLen > 31) idLen = 31; + if (idLen > 31) + idLen = 31; char idText[32]; - strncpy(idText, network_, idLen); + strncpy (idText, network_, idLen); idText[idLen] = '\0'; - localId = (NormNodeId)atoi(idText); + localId = (NormNodeId) atoi (idText); ifacePtr++; - } - else - { + } else { ifacePtr = network_; } // Second, look for optional multicast ifaceName char ifaceName[256]; - const char* addrPtr = strchr(ifacePtr, ';'); - if (NULL != addrPtr) - { + const char *addrPtr = strchr (ifacePtr, ';'); + if (NULL != addrPtr) { size_t ifaceLen = addrPtr - ifacePtr; - if (ifaceLen > 255) ifaceLen = 255; // return error instead? - strncpy(ifaceName, ifacePtr, ifaceLen); + if (ifaceLen > 255) + ifaceLen = 255; // return error instead? + strncpy (ifaceName, ifacePtr, ifaceLen); ifaceName[ifaceLen] = '\0'; ifacePtr = ifaceName; addrPtr++; - } - else - { + } else { addrPtr = ifacePtr; ifacePtr = NULL; } // Finally, parse IP address and port number - const char* portPtr = strrchr(addrPtr, ':'); - if (NULL == portPtr) - { + const char *portPtr = strrchr (addrPtr, ':'); + if (NULL == portPtr) { errno = EINVAL; return -1; } char addr[256]; size_t addrLen = portPtr - addrPtr; - if (addrLen > 255) addrLen = 255; - strncpy(addr, addrPtr, addrLen); + if (addrLen > 255) + addrLen = 255; + strncpy (addr, addrPtr, addrLen); addr[addrLen] = '\0'; portPtr++; - unsigned short portNumber = atoi(portPtr); + unsigned short portNumber = atoi (portPtr); - if (NORM_INSTANCE_INVALID == norm_instance) - { - if (NORM_INSTANCE_INVALID == (norm_instance = NormCreateInstance())) - { + if (NORM_INSTANCE_INVALID == norm_instance) { + if (NORM_INSTANCE_INVALID == (norm_instance = NormCreateInstance ())) { // errno set by whatever caused NormCreateInstance() to fail return -1; } @@ -103,46 +105,44 @@ int zmq::norm_engine_t::init(const char* network_, bool send, bool recv) // c) Randomize and implement a NORM session layer // conflict detection/resolution protocol - norm_session = NormCreateSession(norm_instance, addr, portNumber, localId); - if (NORM_SESSION_INVALID == norm_session) - { + norm_session = NormCreateSession (norm_instance, addr, portNumber, localId); + if (NORM_SESSION_INVALID == norm_session) { int savedErrno = errno; - NormDestroyInstance(norm_instance); + NormDestroyInstance (norm_instance); norm_instance = NORM_INSTANCE_INVALID; errno = savedErrno; return -1; } // There's many other useful NORM options that could be applied here - if (NormIsUnicastAddress(addr)) - { - NormSetDefaultUnicastNack(norm_session, true); - } - else - { + if (NormIsUnicastAddress (addr)) { + NormSetDefaultUnicastNack (norm_session, true); + } else { // These only apply for multicast sessions //NormSetTTL(norm_session, options.multicast_hops); // ZMQ default is 1 - NormSetTTL(norm_session, 255); // since the ZMQ_MULTICAST_HOPS socket option isn't well-supported - NormSetRxPortReuse(norm_session, true); // port reuse doesn't work for non-connected unicast - NormSetLoopback(norm_session, true); // needed when multicast users on same machine - if (NULL != ifacePtr) - { + NormSetTTL ( + norm_session, + 255); // since the ZMQ_MULTICAST_HOPS socket option isn't well-supported + NormSetRxPortReuse ( + norm_session, + true); // port reuse doesn't work for non-connected unicast + NormSetLoopback (norm_session, + true); // needed when multicast users on same machine + if (NULL != ifacePtr) { // Note a bad interface may not be caught until sender or receiver start // (Since sender/receiver is not yet started, this always succeeds here) - NormSetMulticastInterface(norm_session, ifacePtr); + NormSetMulticastInterface (norm_session, ifacePtr); } } - if (recv) - { + if (recv) { // The alternative NORM_SYNC_CURRENT here would provide "instant" // receiver sync to the sender's _current_ message transmission. // NORM_SYNC_STREAM tries to get everything the sender has cached/buffered - NormSetDefaultSyncPolicy(norm_session, NORM_SYNC_STREAM); - if (!NormStartReceiver(norm_session, 2*1024*1024)) - { + NormSetDefaultSyncPolicy (norm_session, NORM_SYNC_STREAM); + if (!NormStartReceiver (norm_session, 2 * 1024 * 1024)) { // errno set by whatever failed int savedErrno = errno; - NormDestroyInstance(norm_instance); // session gets closed, too + NormDestroyInstance (norm_instance); // session gets closed, too norm_session = NORM_SESSION_INVALID; norm_instance = NORM_INSTANCE_INVALID; errno = savedErrno; @@ -151,29 +151,29 @@ int zmq::norm_engine_t::init(const char* network_, bool send, bool recv) is_receiver = true; } - if (send) - { + if (send) { // Pick a random sender instance id (aka norm sender session id) - NormSessionId instanceId = NormGetRandomSessionId(); + NormSessionId instanceId = NormGetRandomSessionId (); // TBD - provide "options" for some NORM sender parameters - if (!NormStartSender(norm_session, instanceId, 2*1024*1024, 1400, 16, 4)) - { + if (!NormStartSender (norm_session, instanceId, 2 * 1024 * 1024, 1400, + 16, 4)) { // errno set by whatever failed int savedErrno = errno; - NormDestroyInstance(norm_instance); // session gets closed, too + NormDestroyInstance (norm_instance); // session gets closed, too norm_session = NORM_SESSION_INVALID; norm_instance = NORM_INSTANCE_INVALID; errno = savedErrno; return -1; } - NormSetCongestionControl(norm_session, true); + NormSetCongestionControl (norm_session, true); norm_tx_ready = true; is_sender = true; - if (NORM_OBJECT_INVALID == (norm_tx_stream = NormStreamOpen(norm_session, 2*1024*1024))) - { + if (NORM_OBJECT_INVALID + == (norm_tx_stream = + NormStreamOpen (norm_session, 2 * 1024 * 1024))) { // errno set by whatever failed int savedErrno = errno; - NormDestroyInstance(norm_instance); // session gets closed, too + NormDestroyInstance (norm_instance); // session gets closed, too norm_session = NORM_SESSION_INVALID; norm_instance = NORM_INSTANCE_INVALID; errno = savedErrno; @@ -185,100 +185,95 @@ int zmq::norm_engine_t::init(const char* network_, bool send, bool recv) //NormSetDebugLevel(3); //NormOpenDebugLog(norm_instance, "normLog.txt"); - return 0; // no error -} // end zmq::norm_engine_t::init() + return 0; // no error +} // end zmq::norm_engine_t::init() -void zmq::norm_engine_t::shutdown() +void zmq::norm_engine_t::shutdown () { // TBD - implement a more graceful shutdown option - if (is_receiver) - { - NormStopReceiver(norm_session); + if (is_receiver) { + NormStopReceiver (norm_session); // delete any active NormRxStreamState - rx_pending_list.Destroy(); - rx_ready_list.Destroy(); - msg_ready_list.Destroy(); + rx_pending_list.Destroy (); + rx_ready_list.Destroy (); + msg_ready_list.Destroy (); is_receiver = false; } - if (is_sender) - { - NormStopSender(norm_session); + if (is_sender) { + NormStopSender (norm_session); is_sender = false; } - if (NORM_SESSION_INVALID != norm_session) - { - NormDestroySession(norm_session); + if (NORM_SESSION_INVALID != norm_session) { + NormDestroySession (norm_session); norm_session = NORM_SESSION_INVALID; } - if (NORM_INSTANCE_INVALID != norm_instance) - { - NormStopInstance(norm_instance); - NormDestroyInstance(norm_instance); + if (NORM_INSTANCE_INVALID != norm_instance) { + NormStopInstance (norm_instance); + NormDestroyInstance (norm_instance); norm_instance = NORM_INSTANCE_INVALID; } -} // end zmq::norm_engine_t::shutdown() +} // end zmq::norm_engine_t::shutdown() -void zmq::norm_engine_t::plug (io_thread_t* io_thread_, session_base_t *session_) +void zmq::norm_engine_t::plug (io_thread_t *io_thread_, + session_base_t *session_) { // TBD - we may assign the NORM engine to an io_thread in the future??? zmq_session = session_; - if (is_sender) zmq_output_ready = true; - if (is_receiver) zmq_input_ready = true; + if (is_sender) + zmq_output_ready = true; + if (is_receiver) + zmq_input_ready = true; - fd_t normDescriptor = NormGetDescriptor(norm_instance); - norm_descriptor_handle = add_fd(normDescriptor); + fd_t normDescriptor = NormGetDescriptor (norm_instance); + norm_descriptor_handle = add_fd (normDescriptor); // Set POLLIN for notification of pending NormEvents - set_pollin(norm_descriptor_handle); + set_pollin (norm_descriptor_handle); - if (is_sender) send_data(); + if (is_sender) + send_data (); -} // end zmq::norm_engine_t::init() +} // end zmq::norm_engine_t::init() -void zmq::norm_engine_t::unplug() +void zmq::norm_engine_t::unplug () { - rm_fd(norm_descriptor_handle); + rm_fd (norm_descriptor_handle); zmq_session = NULL; -} // end zmq::norm_engine_t::unplug() +} // end zmq::norm_engine_t::unplug() -void zmq::norm_engine_t::terminate() +void zmq::norm_engine_t::terminate () { - unplug(); - shutdown(); + unplug (); + shutdown (); delete this; } -void zmq::norm_engine_t::restart_output() +void zmq::norm_engine_t::restart_output () { // There's new message data available from the session zmq_output_ready = true; - if (norm_tx_ready) send_data(); + if (norm_tx_ready) + send_data (); -} // end zmq::norm_engine_t::restart_output() +} // end zmq::norm_engine_t::restart_output() -void zmq::norm_engine_t::send_data() +void zmq::norm_engine_t::send_data () { // Here we write as much as is available or we can - while (zmq_output_ready && norm_tx_ready) - { - if (0 == tx_len) - { + while (zmq_output_ready && norm_tx_ready) { + if (0 == tx_len) { // Our tx_buffer needs data to send // Get more data from encoder size_t space = BUFFER_SIZE; - unsigned char* bufPtr = (unsigned char*)tx_buffer; - tx_len = zmq_encoder.encode(&bufPtr, space); - if (0 == tx_len) - { - if (tx_first_msg) - { + unsigned char *bufPtr = (unsigned char *) tx_buffer; + tx_len = zmq_encoder.encode (&bufPtr, space); + if (0 == tx_len) { + if (tx_first_msg) { // We don't need to mark eom/flush until a message is sent tx_first_msg = false; - } - else - { + } else { // A prior message was completely written to stream, so // mark end-of-message and possibly flush (to force packet transmission, // even if it's not a full segment so message gets delivered quickly) @@ -286,16 +281,15 @@ void zmq::norm_engine_t::send_data() // Note NORM_FLUSH_ACTIVE makes NORM fairly chatty for low duty cycle messaging // but makes sure content is delivered quickly. Positive acknowledgements // with flush override would make NORM more succinct here - NormStreamFlush(norm_tx_stream, true, NORM_FLUSH_ACTIVE); + NormStreamFlush (norm_tx_stream, true, NORM_FLUSH_ACTIVE); } // Need to pull and load a new message to send - if (-1 == zmq_session->pull_msg(&tx_msg)) - { + if (-1 == zmq_session->pull_msg (&tx_msg)) { // We need to wait for "restart_output()" to be called by ZMQ zmq_output_ready = false; break; } - zmq_encoder.load_msg(&tx_msg); + zmq_encoder.load_msg (&tx_msg); // Should we write message size header for NORM to use? Or expect NORM // receiver to decode ZMQ message framing format(s)? // OK - we need to use a byte to denote when the ZMQ frame is the _first_ @@ -304,71 +298,68 @@ void zmq::norm_engine_t::send_data() // I.e.,If more_flag _was_ false previously, this is the first // frame of a ZMQ message. if (tx_more_bit) - tx_buffer[0] = (char)0xff; // this is not first frame of message + tx_buffer[0] = + (char) 0xff; // this is not first frame of message else - tx_buffer[0] = 0x00; // this is first frame of message - tx_more_bit = (0 != (tx_msg.flags() & msg_t::more)); + tx_buffer[0] = 0x00; // this is first frame of message + tx_more_bit = (0 != (tx_msg.flags () & msg_t::more)); // Go ahead an get a first chunk of the message bufPtr++; space--; - tx_len = 1 + zmq_encoder.encode(&bufPtr, space); + tx_len = 1 + zmq_encoder.encode (&bufPtr, space); tx_index = 0; } } // Do we have data in our tx_buffer pending - if (tx_index < tx_len) - { + if (tx_index < tx_len) { // We have data in our tx_buffer to send, so write it to the stream - tx_index += NormStreamWrite(norm_tx_stream, tx_buffer + tx_index, tx_len - tx_index); - if (tx_index < tx_len) - { + tx_index += NormStreamWrite (norm_tx_stream, tx_buffer + tx_index, + tx_len - tx_index); + if (tx_index < tx_len) { // NORM stream buffer full, wait for NORM_TX_QUEUE_VACANCY norm_tx_ready = false; break; } - tx_len = 0; // all buffered data was written + tx_len = 0; // all buffered data was written } - } // end while (zmq_output_ready && norm_tx_ready) -} // end zmq::norm_engine_t::send_data() + } // end while (zmq_output_ready && norm_tx_ready) +} // end zmq::norm_engine_t::send_data() -void zmq::norm_engine_t::in_event() +void zmq::norm_engine_t::in_event () { // This means a NormEvent is pending, so call NormGetNextEvent() and handle NormEvent event; - if (!NormGetNextEvent(norm_instance, &event)) - { + if (!NormGetNextEvent (norm_instance, &event)) { // NORM has died before we unplugged?! - zmq_assert(false); + zmq_assert (false); return; } - switch(event.type) - { + switch (event.type) { case NORM_TX_QUEUE_VACANCY: case NORM_TX_QUEUE_EMPTY: - if (!norm_tx_ready) - { + if (!norm_tx_ready) { norm_tx_ready = true; - send_data(); + send_data (); } break; case NORM_RX_OBJECT_NEW: //break; case NORM_RX_OBJECT_UPDATED: - recv_data(event.object); + recv_data (event.object); break; - case NORM_RX_OBJECT_ABORTED: - { - NormRxStreamState* rxState = (NormRxStreamState*)NormObjectGetUserData(event.object); - if (NULL != rxState) - { + case NORM_RX_OBJECT_ABORTED: { + NormRxStreamState *rxState = + (NormRxStreamState *) NormObjectGetUserData (event.object); + if (NULL != rxState) { // Remove the state from the list it's in // This is now unnecessary since deletion takes care of list removal // but in the interest of being clear ... - NormRxStreamState::List* list = rxState->AccessList(); - if (NULL != list) list->Remove(*rxState); + NormRxStreamState::List *list = rxState->AccessList (); + if (NULL != list) + list->Remove (*rxState); } delete rxState; break; @@ -382,278 +373,262 @@ void zmq::norm_engine_t::in_event() // user configurable timeout here to wait some amount of time // after this event to declare the remote sender truly dead // and delete its state??? - NormNodeDelete(event.sender); + NormNodeDelete (event.sender); break; default: // We ignore some NORM events break; } -} // zmq::norm_engine_t::in_event() +} // zmq::norm_engine_t::in_event() -void zmq::norm_engine_t::restart_input() +void zmq::norm_engine_t::restart_input () { // TBD - should we check/assert that zmq_input_ready was false??? zmq_input_ready = true; // Process any pending received messages - if (!msg_ready_list.IsEmpty()) - recv_data(NORM_OBJECT_INVALID); + if (!msg_ready_list.IsEmpty ()) + recv_data (NORM_OBJECT_INVALID); -} // end zmq::norm_engine_t::restart_input() +} // end zmq::norm_engine_t::restart_input() -void zmq::norm_engine_t::recv_data(NormObjectHandle object) +void zmq::norm_engine_t::recv_data (NormObjectHandle object) { - if (NORM_OBJECT_INVALID != object) - { + if (NORM_OBJECT_INVALID != object) { // Call result of NORM_RX_OBJECT_UPDATED notification // This is a rx_ready indication for a new or existing rx stream // First, determine if this is a stream we already know - zmq_assert(NORM_OBJECT_STREAM == NormObjectGetType(object)); + zmq_assert (NORM_OBJECT_STREAM == NormObjectGetType (object)); // Since there can be multiple senders (publishers), we keep // state for each separate rx stream. - NormRxStreamState* rxState = (NormRxStreamState*)NormObjectGetUserData(object); - if (NULL == rxState) - { + NormRxStreamState *rxState = + (NormRxStreamState *) NormObjectGetUserData (object); + if (NULL == rxState) { // This is a new stream, so create rxState with zmq decoder, etc - rxState = new (std::nothrow) NormRxStreamState(object, options.maxmsgsize); - errno_assert(rxState); + rxState = + new (std::nothrow) NormRxStreamState (object, options.maxmsgsize); + errno_assert (rxState); - if (!rxState->Init()) - { - errno_assert(false); + if (!rxState->Init ()) { + errno_assert (false); delete rxState; return; } - NormObjectSetUserData(object, rxState); - } - else if (!rxState->IsRxReady()) - { + NormObjectSetUserData (object, rxState); + } else if (!rxState->IsRxReady ()) { // Existing non-ready stream, so remove from pending // list to be promoted to rx_ready_list ... - rx_pending_list.Remove(*rxState); + rx_pending_list.Remove (*rxState); } - if (!rxState->IsRxReady()) - { + if (!rxState->IsRxReady ()) { // TBD - prepend up front for immediate service? - rxState->SetRxReady(true); - rx_ready_list.Append(*rxState); + rxState->SetRxReady (true); + rx_ready_list.Append (*rxState); } } // This loop repeats until we've read all data available from "rx ready" inbound streams // and pushed any accumulated messages we can up to the zmq session. - while (!rx_ready_list.IsEmpty() || (zmq_input_ready && !msg_ready_list.IsEmpty())) - { + while (!rx_ready_list.IsEmpty () + || (zmq_input_ready && !msg_ready_list.IsEmpty ())) { // Iterate through our rx_ready streams, reading data into the decoder // (This services incoming "rx ready" streams in a round-robin fashion) - NormRxStreamState::List::Iterator iterator(rx_ready_list); - NormRxStreamState* rxState; - while (NULL != (rxState = iterator.GetNextItem())) - { - switch(rxState->Decode()) - { - case 1: // msg completed + NormRxStreamState::List::Iterator iterator (rx_ready_list); + NormRxStreamState *rxState; + while (NULL != (rxState = iterator.GetNextItem ())) { + switch (rxState->Decode ()) { + case 1: // msg completed // Complete message decoded, move this stream to msg_ready_list // to push the message up to the session below. Note the stream // will be returned to the "rx_ready_list" after that's done - rx_ready_list.Remove(*rxState); - msg_ready_list.Append(*rxState); + rx_ready_list.Remove (*rxState); + msg_ready_list.Append (*rxState); continue; case -1: // decoding error (shouldn't happen w/ NORM, but ...) // We need to re-sync this stream (decoder buffer was reset) - rxState->SetSync(false); + rxState->SetSync (false); break; - default: // 0 - need more data + default: // 0 - need more data break; } // Get more data from this stream - NormObjectHandle stream = rxState->GetStreamHandle(); + NormObjectHandle stream = rxState->GetStreamHandle (); // First, make sure we're in sync ... - while (!rxState->InSync()) - { + while (!rxState->InSync ()) { // seek NORM message start - if (!NormStreamSeekMsgStart(stream)) - { + if (!NormStreamSeekMsgStart (stream)) { // Need to wait for more data break; } // read message 'flag' byte to see if this it's a 'final' frame char syncFlag; unsigned int numBytes = 1; - if (!NormStreamRead(stream, &syncFlag, &numBytes)) - { + if (!NormStreamRead (stream, &syncFlag, &numBytes)) { // broken stream (shouldn't happen after seek msg start?) - zmq_assert(false); + zmq_assert (false); continue; } - if (0 == numBytes) - { + if (0 == numBytes) { // This probably shouldn't happen either since we found msg start // Need to wait for more data break; } - if (0 == syncFlag) rxState->SetSync(true); + if (0 == syncFlag) + rxState->SetSync (true); // else keep seeking ... - } // end while(!rxState->InSync()) - if (!rxState->InSync()) - { + } // end while(!rxState->InSync()) + if (!rxState->InSync ()) { // Need more data for this stream, so remove from "rx ready" // list and iterate to next "rx ready" stream - rxState->SetRxReady(false); + rxState->SetRxReady (false); // Move from rx_ready_list to rx_pending_list - rx_ready_list.Remove(*rxState); - rx_pending_list.Append(*rxState); + rx_ready_list.Remove (*rxState); + rx_pending_list.Append (*rxState); continue; } // Now we're actually ready to read data from the NORM stream to the zmq_decoder // the underlying zmq_decoder->get_buffer() call sets how much is needed. - unsigned int numBytes = rxState->GetBytesNeeded(); - if (!NormStreamRead(stream, rxState->AccessBuffer(), &numBytes)) - { + unsigned int numBytes = rxState->GetBytesNeeded (); + if (!NormStreamRead (stream, rxState->AccessBuffer (), &numBytes)) { // broken NORM stream, so re-sync - rxState->Init(); // TBD - check result + rxState->Init (); // TBD - check result // This will retry syncing, and getting data from this stream // since we don't increment the "it" iterator continue; } - rxState->IncrementBufferCount(numBytes); - if (0 == numBytes) - { + rxState->IncrementBufferCount (numBytes); + if (0 == numBytes) { // All the data available has been read // Need to wait for NORM_RX_OBJECT_UPDATED for this stream - rxState->SetRxReady(false); + rxState->SetRxReady (false); // Move from rx_ready_list to rx_pending_list - rx_ready_list.Remove(*rxState); - rx_pending_list.Append(*rxState); + rx_ready_list.Remove (*rxState); + rx_pending_list.Append (*rxState); } - } // end while(NULL != (rxState = iterator.GetNextItem())) + } // end while(NULL != (rxState = iterator.GetNextItem())) - if (zmq_input_ready) - { + if (zmq_input_ready) { // At this point, we've made a pass through the "rx_ready" stream list // Now make a pass through the "msg_pending" list (if the zmq session // ready for more input). This may possibly return streams back to // the "rx ready" stream list after their pending message is handled - NormRxStreamState::List::Iterator iterator(msg_ready_list); - NormRxStreamState* rxState; - while (NULL != (rxState = iterator.GetNextItem())) - { - msg_t* msg = rxState->AccessMsg(); - int rc = zmq_session->push_msg(msg); - if (-1 == rc) - { - if (EAGAIN == errno) - { + NormRxStreamState::List::Iterator iterator (msg_ready_list); + NormRxStreamState *rxState; + while (NULL != (rxState = iterator.GetNextItem ())) { + msg_t *msg = rxState->AccessMsg (); + int rc = zmq_session->push_msg (msg); + if (-1 == rc) { + if (EAGAIN == errno) { // need to wait until session calls "restart_input()" zmq_input_ready = false; break; - } - else - { + } else { // session rejected message? // TBD - handle this better - zmq_assert(false); + zmq_assert (false); } } // else message was accepted. - msg_ready_list.Remove(*rxState); - if (rxState->IsRxReady()) // Move back to "rx_ready" list to read more data - rx_ready_list.Append(*rxState); - else // Move back to "rx_pending" list until NORM_RX_OBJECT_UPDATED - msg_ready_list.Append(*rxState); - } // end while(NULL != (rxState = iterator.GetNextItem())) - } // end if (zmq_input_ready) - } // end while ((!rx_ready_list.empty() || (zmq_input_ready && !msg_ready_list.empty())) + msg_ready_list.Remove (*rxState); + if ( + rxState + ->IsRxReady ()) // Move back to "rx_ready" list to read more data + rx_ready_list.Append (*rxState); + else // Move back to "rx_pending" list until NORM_RX_OBJECT_UPDATED + msg_ready_list.Append (*rxState); + } // end while(NULL != (rxState = iterator.GetNextItem())) + } // end if (zmq_input_ready) + } // end while ((!rx_ready_list.empty() || (zmq_input_ready && !msg_ready_list.empty())) // Alert zmq of the messages we have pushed up - zmq_session->flush(); - -} // end zmq::norm_engine_t::recv_data() - -zmq::norm_engine_t::NormRxStreamState::NormRxStreamState(NormObjectHandle normStream, - int64_t maxMsgSize) - : norm_stream(normStream), max_msg_size(maxMsgSize), - in_sync(false), rx_ready(false), zmq_decoder(NULL), skip_norm_sync(false), - buffer_ptr(NULL), buffer_size(0), buffer_count(0), - prev(NULL), next(NULL), list(NULL) + zmq_session->flush (); + +} // end zmq::norm_engine_t::recv_data() + +zmq::norm_engine_t::NormRxStreamState::NormRxStreamState ( + NormObjectHandle normStream, int64_t maxMsgSize) : + norm_stream (normStream), + max_msg_size (maxMsgSize), + in_sync (false), + rx_ready (false), + zmq_decoder (NULL), + skip_norm_sync (false), + buffer_ptr (NULL), + buffer_size (0), + buffer_count (0), + prev (NULL), + next (NULL), + list (NULL) { } -zmq::norm_engine_t::NormRxStreamState::~NormRxStreamState() +zmq::norm_engine_t::NormRxStreamState::~NormRxStreamState () { - if (NULL != zmq_decoder) - { + if (NULL != zmq_decoder) { delete zmq_decoder; zmq_decoder = NULL; } - if (NULL != list) - { - list->Remove(*this); + if (NULL != list) { + list->Remove (*this); list = NULL; } } -bool zmq::norm_engine_t::NormRxStreamState::Init() +bool zmq::norm_engine_t::NormRxStreamState::Init () { in_sync = false; skip_norm_sync = false; - if (NULL != zmq_decoder) delete zmq_decoder; + if (NULL != zmq_decoder) + delete zmq_decoder; // Note "in_batch_size" comes from config.h zmq_decoder = new (std::nothrow) v2_decoder_t (in_batch_size, max_msg_size); alloc_assert (zmq_decoder); - if (NULL != zmq_decoder) - { + if (NULL != zmq_decoder) { buffer_count = 0; buffer_size = 0; - zmq_decoder->get_buffer(&buffer_ptr, &buffer_size); + zmq_decoder->get_buffer (&buffer_ptr, &buffer_size); return true; - } - else - { + } else { return false; } -} // end zmq::norm_engine_t::NormRxStreamState::Init() +} // end zmq::norm_engine_t::NormRxStreamState::Init() // This decodes any pending data sitting in our stream decoder buffer // It returns 1 upon message completion, -1 on error, 1 on msg completion -int zmq::norm_engine_t::NormRxStreamState::Decode() +int zmq::norm_engine_t::NormRxStreamState::Decode () { // If we have pending bytes to decode, process those first - while (buffer_count > 0) - { + while (buffer_count > 0) { // There's pending data for the decoder to decode size_t processed = 0; // This a bit of a kludgy approach used to weed // out the NORM ZMQ message transport "syncFlag" byte // from the ZMQ message stream being decoded (but it works!) - if (skip_norm_sync) - { + if (skip_norm_sync) { buffer_ptr++; buffer_count--; skip_norm_sync = false; } - int rc = zmq_decoder->decode(buffer_ptr, buffer_count, processed); + int rc = zmq_decoder->decode (buffer_ptr, buffer_count, processed); buffer_ptr += processed; buffer_count -= processed; - switch (rc) - { + switch (rc) { case 1: // msg completed - if (0 == buffer_count) - { + if (0 == buffer_count) { buffer_size = 0; - zmq_decoder->get_buffer(&buffer_ptr, &buffer_size); + zmq_decoder->get_buffer (&buffer_ptr, &buffer_size); } skip_norm_sync = true; return 1; case -1: // decoder error (reset decoder and state variables) in_sync = false; - skip_norm_sync = false; // will get consumed by norm sync check - Init(); + skip_norm_sync = false; // will get consumed by norm sync check + Init (); break; case 0: @@ -664,33 +639,32 @@ int zmq::norm_engine_t::NormRxStreamState::Decode() // Reset buffer pointer/count for next read buffer_count = 0; buffer_size = 0; - zmq_decoder->get_buffer(&buffer_ptr, &buffer_size); - return 0; // need more data + zmq_decoder->get_buffer (&buffer_ptr, &buffer_size); + return 0; // need more data -} // end zmq::norm_engine_t::NormRxStreamState::Decode() +} // end zmq::norm_engine_t::NormRxStreamState::Decode() -zmq::norm_engine_t::NormRxStreamState::List::List() - : head(NULL), tail(NULL) +zmq::norm_engine_t::NormRxStreamState::List::List () : head (NULL), tail (NULL) { } -zmq::norm_engine_t::NormRxStreamState::List::~List() +zmq::norm_engine_t::NormRxStreamState::List::~List () { - Destroy(); + Destroy (); } -void zmq::norm_engine_t::NormRxStreamState::List::Destroy() +void zmq::norm_engine_t::NormRxStreamState::List::Destroy () { - NormRxStreamState* item = head; - while (NULL != item) - { - Remove(*item); + NormRxStreamState *item = head; + while (NULL != item) { + Remove (*item); delete item; item = head; } -} // end zmq::norm_engine_t::NormRxStreamState::List::Destroy() +} // end zmq::norm_engine_t::NormRxStreamState::List::Destroy() -void zmq::norm_engine_t::NormRxStreamState::List::Append(NormRxStreamState& item) +void zmq::norm_engine_t::NormRxStreamState::List::Append ( + NormRxStreamState &item) { item.prev = tail; if (NULL != tail) @@ -700,33 +674,37 @@ void zmq::norm_engine_t::NormRxStreamState::List::Append(NormRxStreamState& item item.next = NULL; tail = &item; item.list = this; -} // end zmq::norm_engine_t::NormRxStreamState::List::Append() +} // end zmq::norm_engine_t::NormRxStreamState::List::Append() -void zmq::norm_engine_t::NormRxStreamState::List::Remove(NormRxStreamState& item) +void zmq::norm_engine_t::NormRxStreamState::List::Remove ( + NormRxStreamState &item) { if (NULL != item.prev) item.prev->next = item.next; else head = item.next; if (NULL != item.next) - item.next ->prev = item.prev; + item.next->prev = item.prev; else tail = item.prev; item.prev = item.next = NULL; item.list = NULL; -} // end zmq::norm_engine_t::NormRxStreamState::List::Remove() +} // end zmq::norm_engine_t::NormRxStreamState::List::Remove() -zmq::norm_engine_t::NormRxStreamState::List::Iterator::Iterator(const List& list) - : next_item(list.head) +zmq::norm_engine_t::NormRxStreamState::List::Iterator::Iterator ( + const List &list) : + next_item (list.head) { } -zmq::norm_engine_t::NormRxStreamState* zmq::norm_engine_t::NormRxStreamState::List::Iterator::GetNextItem() +zmq::norm_engine_t::NormRxStreamState * +zmq::norm_engine_t::NormRxStreamState::List::Iterator::GetNextItem () { - NormRxStreamState* nextItem = next_item; - if (NULL != nextItem) next_item = nextItem->next; + NormRxStreamState *nextItem = next_item; + if (NULL != nextItem) + next_item = nextItem->next; return nextItem; -} // end zmq::norm_engine_t::NormRxStreamState::List::Iterator::GetNextItem() +} // end zmq::norm_engine_t::NormRxStreamState::List::Iterator::GetNextItem() const char *zmq::norm_engine_t::get_endpoint () const { diff --git a/src/norm_engine.hpp b/src/norm_engine.hpp index d45e194667..f932e37385 100644 --- a/src/norm_engine.hpp +++ b/src/norm_engine.hpp @@ -14,175 +14,170 @@ namespace zmq { - class io_thread_t; - class session_base_t; +class io_thread_t; +class session_base_t; - class norm_engine_t : public io_object_t, public i_engine - { - public: - norm_engine_t (zmq::io_thread_t *parent_, const options_t &options_); - ~norm_engine_t (); +class norm_engine_t : public io_object_t, public i_engine +{ + public: + norm_engine_t (zmq::io_thread_t *parent_, const options_t &options_); + ~norm_engine_t (); + + // create NORM instance, session, etc + int init (const char *network_, bool send, bool recv); + void shutdown (); + + // i_engine interface implementation. + // Plug the engine to the session. + virtual void plug (zmq::io_thread_t *io_thread_, + class session_base_t *session_); + + // Terminate and deallocate the engine. Note that 'detached' + // events are not fired on termination. + virtual void terminate (); + + // This method is called by the session to signalise that more + // messages can be written to the pipe. + virtual void restart_input (); + + // This method is called by the session to signalise that there + // are messages to send available. + virtual void restart_output (); - // create NORM instance, session, etc - int init(const char* network_, bool send, bool recv); - void shutdown(); + virtual void zap_msg_available (){}; - // i_engine interface implementation. - // Plug the engine to the session. - virtual void plug (zmq::io_thread_t *io_thread_, - class session_base_t *session_); + virtual const char *get_endpoint () const; + + // i_poll_events interface implementation. + // (we only need in_event() for NormEvent notification) + // (i.e., don't have any output events or timers (yet)) + void in_event (); + + private: + void unplug (); + void send_data (); + void recv_data (NormObjectHandle stream); + + + enum + { + BUFFER_SIZE = 2048 + }; + + // Used to keep track of streams from multiple senders + class NormRxStreamState + { + public: + NormRxStreamState (NormObjectHandle normStream, int64_t maxMsgSize); + ~NormRxStreamState (); - // Terminate and deallocate the engine. Note that 'detached' - // events are not fired on termination. - virtual void terminate (); + NormObjectHandle GetStreamHandle () const { return norm_stream; } - // This method is called by the session to signalise that more - // messages can be written to the pipe. - virtual void restart_input (); + bool Init (); - // This method is called by the session to signalise that there - // are messages to send available. - virtual void restart_output (); + void SetRxReady (bool state) { rx_ready = state; } + bool IsRxReady () const { return rx_ready; } - virtual void zap_msg_available () {}; + void SetSync (bool state) { in_sync = state; } + bool InSync () const { return in_sync; } - virtual const char *get_endpoint () const; + // These are used to feed data to decoder + // and its underlying "msg" buffer + char *AccessBuffer () { return (char *) (buffer_ptr + buffer_count); } + size_t GetBytesNeeded () const { return (buffer_size - buffer_count); } + void IncrementBufferCount (size_t count) { buffer_count += count; } + msg_t *AccessMsg () { return zmq_decoder->msg (); } + // This invokes the decoder "decode" method + // returning 0 if more data is needed, + // 1 if the message is complete, If an error + // occurs the 'sync' is dropped and the + // decoder re-initialized + int Decode (); - // i_poll_events interface implementation. - // (we only need in_event() for NormEvent notification) - // (i.e., don't have any output events or timers (yet)) - void in_event (); + class List + { + public: + List (); + ~List (); - private: - void unplug(); - void send_data(); - void recv_data(NormObjectHandle stream); + void Append (NormRxStreamState &item); + void Remove (NormRxStreamState &item); + bool IsEmpty () const { return (NULL == head); } - enum {BUFFER_SIZE = 2048}; + void Destroy (); - // Used to keep track of streams from multiple senders - class NormRxStreamState + class Iterator { - public: - NormRxStreamState(NormObjectHandle normStream, - int64_t maxMsgSize); - ~NormRxStreamState(); - - NormObjectHandle GetStreamHandle() const - {return norm_stream;} - - bool Init(); - - void SetRxReady(bool state) - {rx_ready = state;} - bool IsRxReady() const - {return rx_ready;} - - void SetSync(bool state) - {in_sync = state;} - bool InSync() const - {return in_sync;} - - // These are used to feed data to decoder - // and its underlying "msg" buffer - char* AccessBuffer() - {return (char*)(buffer_ptr + buffer_count);} - size_t GetBytesNeeded() const - {return (buffer_size - buffer_count);} - void IncrementBufferCount(size_t count) - {buffer_count += count;} - msg_t* AccessMsg() - {return zmq_decoder->msg();} - // This invokes the decoder "decode" method - // returning 0 if more data is needed, - // 1 if the message is complete, If an error - // occurs the 'sync' is dropped and the - // decoder re-initialized - int Decode(); - - class List - { - public: - List(); - ~List(); - - void Append(NormRxStreamState& item); - void Remove(NormRxStreamState& item); - - bool IsEmpty() const - {return (NULL == head);} - - void Destroy(); - - class Iterator - { - public: - Iterator(const List& list); - NormRxStreamState* GetNextItem(); - private: - NormRxStreamState* next_item; - }; - friend class Iterator; - - private: - NormRxStreamState* head; - NormRxStreamState* tail; - - }; // end class zmq::norm_engine_t::NormRxStreamState::List - - friend class List; - - List* AccessList() - {return list;} - - - private: - NormObjectHandle norm_stream; - int64_t max_msg_size; - bool in_sync; - bool rx_ready; - v2_decoder_t* zmq_decoder; - bool skip_norm_sync; - unsigned char* buffer_ptr; - size_t buffer_size; - size_t buffer_count; - - NormRxStreamState* prev; - NormRxStreamState* next; - NormRxStreamState::List* list; - - }; // end class zmq::norm_engine_t::NormRxStreamState - - session_base_t* zmq_session; - options_t options; - NormInstanceHandle norm_instance; - handle_t norm_descriptor_handle; - NormSessionHandle norm_session; - bool is_sender; - bool is_receiver; - // Sender state - msg_t tx_msg; - v2_encoder_t zmq_encoder; // for tx messages (we use v2 for now) - NormObjectHandle norm_tx_stream; - bool tx_first_msg; - bool tx_more_bit; - bool zmq_output_ready; // zmq has msg(s) to send - bool norm_tx_ready; // norm has tx queue vacancy - // TBD - maybe don't need buffer if can access zmq message buffer directly? - char tx_buffer[BUFFER_SIZE]; - unsigned int tx_index; - unsigned int tx_len; - - // Receiver state - // Lists of norm rx streams from remote senders - bool zmq_input_ready; // zmq ready to receive msg(s) - NormRxStreamState::List rx_pending_list; // rx streams waiting for data reception - NormRxStreamState::List rx_ready_list; // rx streams ready for NormStreamRead() - NormRxStreamState::List msg_ready_list; // rx streams w/ msg ready for push to zmq - - - }; // end class norm_engine_t + public: + Iterator (const List &list); + NormRxStreamState *GetNextItem (); + + private: + NormRxStreamState *next_item; + }; + friend class Iterator; + + private: + NormRxStreamState *head; + NormRxStreamState *tail; + + }; // end class zmq::norm_engine_t::NormRxStreamState::List + + friend class List; + + List *AccessList () { return list; } + + + private: + NormObjectHandle norm_stream; + int64_t max_msg_size; + bool in_sync; + bool rx_ready; + v2_decoder_t *zmq_decoder; + bool skip_norm_sync; + unsigned char *buffer_ptr; + size_t buffer_size; + size_t buffer_count; + + NormRxStreamState *prev; + NormRxStreamState *next; + NormRxStreamState::List *list; + + }; // end class zmq::norm_engine_t::NormRxStreamState + + session_base_t *zmq_session; + options_t options; + NormInstanceHandle norm_instance; + handle_t norm_descriptor_handle; + NormSessionHandle norm_session; + bool is_sender; + bool is_receiver; + // Sender state + msg_t tx_msg; + v2_encoder_t zmq_encoder; // for tx messages (we use v2 for now) + NormObjectHandle norm_tx_stream; + bool tx_first_msg; + bool tx_more_bit; + bool zmq_output_ready; // zmq has msg(s) to send + bool norm_tx_ready; // norm has tx queue vacancy + // TBD - maybe don't need buffer if can access zmq message buffer directly? + char tx_buffer[BUFFER_SIZE]; + unsigned int tx_index; + unsigned int tx_len; + + // Receiver state + // Lists of norm rx streams from remote senders + bool zmq_input_ready; // zmq ready to receive msg(s) + NormRxStreamState::List + rx_pending_list; // rx streams waiting for data reception + NormRxStreamState::List + rx_ready_list; // rx streams ready for NormStreamRead() + NormRxStreamState::List + msg_ready_list; // rx streams w/ msg ready for push to zmq + + +}; // end class norm_engine_t } #endif // ZMQ_HAVE_NORM diff --git a/src/null_mechanism.cpp b/src/null_mechanism.cpp index 560aec3c81..61c353a653 100644 --- a/src/null_mechanism.cpp +++ b/src/null_mechanism.cpp @@ -64,25 +64,23 @@ int zmq::null_mechanism_t::next_handshake_command (msg_t *msg_) return -1; } - if (zap_required() && !zap_reply_received) { + if (zap_required () && !zap_reply_received) { if (zap_request_sent) { errno = EAGAIN; return -1; } - int rc = session->zap_connect(); - if (rc == -1) - { - session->get_socket()->event_handshake_failed_no_detail ( - session->get_endpoint(), - EFAULT); + int rc = session->zap_connect (); + if (rc == -1) { + session->get_socket ()->event_handshake_failed_no_detail ( + session->get_endpoint (), EFAULT); return -1; } send_zap_request (); zap_request_sent = true; - // TODO actually, it is quite unlikely that we can read the ZAP + // TODO actually, it is quite unlikely that we can read the ZAP // reply already, but removing this has some strange side-effect - // (probably because the pipe's in_active flag is true until a read + // (probably because the pipe's in_active flag is true until a read // is attempted) rc = receive_and_process_zap_reply (); if (rc != 0) @@ -120,26 +118,23 @@ int zmq::null_mechanism_t::process_handshake_command (msg_t *msg_) { if (ready_command_received || error_command_received) { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; return -1; } const unsigned char *cmd_data = - static_cast (msg_->data ()); + static_cast (msg_->data ()); const size_t data_size = msg_->size (); int rc = 0; if (data_size >= 6 && !memcmp (cmd_data, "\5READY", 6)) rc = process_ready_command (cmd_data, data_size); - else - if (data_size >= 6 && !memcmp (cmd_data, "\5ERROR", 6)) + else if (data_size >= 6 && !memcmp (cmd_data, "\5ERROR", 6)) rc = process_error_command (cmd_data, data_size); else { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), - ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); + session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); errno = EPROTO; rc = -1; } @@ -153,15 +148,15 @@ int zmq::null_mechanism_t::process_handshake_command (msg_t *msg_) return rc; } -int zmq::null_mechanism_t::process_ready_command ( - const unsigned char *cmd_data, size_t data_size) +int zmq::null_mechanism_t::process_ready_command (const unsigned char *cmd_data, + size_t data_size) { ready_command_received = true; return parse_metadata (cmd_data + 6, data_size - 6); } -int zmq::null_mechanism_t::process_error_command ( - const unsigned char *cmd_data, size_t data_size) +int zmq::null_mechanism_t::process_error_command (const unsigned char *cmd_data, + size_t data_size) { if (data_size < 7) { session->get_socket ()->event_handshake_failed_protocol ( @@ -171,7 +166,7 @@ int zmq::null_mechanism_t::process_error_command ( errno = EPROTO; return -1; } - const size_t error_reason_len = static_cast (cmd_data [6]); + const size_t error_reason_len = static_cast (cmd_data[6]); if (error_reason_len > data_size - 7) { session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), @@ -200,15 +195,13 @@ int zmq::null_mechanism_t::zap_msg_available () zmq::mechanism_t::status_t zmq::null_mechanism_t::status () const { - const bool command_sent = - ready_command_sent || error_command_sent; + const bool command_sent = ready_command_sent || error_command_sent; const bool command_received = - ready_command_received || error_command_received; + ready_command_received || error_command_received; if (ready_command_sent && ready_command_received) return mechanism_t::ready; - else - if (command_sent && command_received) + else if (command_sent && command_received) return error; else return handshaking; diff --git a/src/null_mechanism.hpp b/src/null_mechanism.hpp index 4fca49df4f..dffd2e4c21 100644 --- a/src/null_mechanism.hpp +++ b/src/null_mechanism.hpp @@ -36,42 +36,36 @@ namespace zmq { +class msg_t; +class session_base_t; - class msg_t; - class session_base_t; - - class null_mechanism_t : public zap_client_t - { - public: - - null_mechanism_t (session_base_t *session_, - const std::string &peer_address, - const options_t &options_); - virtual ~null_mechanism_t (); - - // mechanism implementation - virtual int next_handshake_command (msg_t *msg_); - virtual int process_handshake_command (msg_t *msg_); - virtual int zap_msg_available (); - virtual status_t status () const; - - private: - - bool ready_command_sent; - bool error_command_sent; - bool ready_command_received; - bool error_command_received; - bool zap_request_sent; - bool zap_reply_received; - - int process_ready_command ( - const unsigned char *cmd_data, size_t data_size); - int process_error_command ( - const unsigned char *cmd_data, size_t data_size); - - void send_zap_request (); - }; - +class null_mechanism_t : public zap_client_t +{ + public: + null_mechanism_t (session_base_t *session_, + const std::string &peer_address, + const options_t &options_); + virtual ~null_mechanism_t (); + + // mechanism implementation + virtual int next_handshake_command (msg_t *msg_); + virtual int process_handshake_command (msg_t *msg_); + virtual int zap_msg_available (); + virtual status_t status () const; + + private: + bool ready_command_sent; + bool error_command_sent; + bool ready_command_received; + bool error_command_received; + bool zap_request_sent; + bool zap_reply_received; + + int process_ready_command (const unsigned char *cmd_data, size_t data_size); + int process_error_command (const unsigned char *cmd_data, size_t data_size); + + void send_zap_request (); +}; } #endif diff --git a/src/object.cpp b/src/object.cpp index 1e07226fcd..6b673770f2 100644 --- a/src/object.cpp +++ b/src/object.cpp @@ -39,9 +39,7 @@ #include "session_base.hpp" #include "socket_base.hpp" -zmq::object_t::object_t (ctx_t *ctx_, uint32_t tid_) : - ctx (ctx_), - tid (tid_) +zmq::object_t::object_t (ctx_t *ctx_, uint32_t tid_) : ctx (ctx_), tid (tid_) { } @@ -60,7 +58,7 @@ uint32_t zmq::object_t::get_tid () return tid; } -void zmq::object_t::set_tid(uint32_t id) +void zmq::object_t::set_tid (uint32_t id) { tid = id; } @@ -73,97 +71,97 @@ zmq::ctx_t *zmq::object_t::get_ctx () void zmq::object_t::process_command (command_t &cmd_) { switch (cmd_.type) { - - case command_t::activate_read: - process_activate_read (); - break; - - case command_t::activate_write: - process_activate_write (cmd_.args.activate_write.msgs_read); - break; - - case command_t::stop: - process_stop (); - break; - - case command_t::plug: - process_plug (); - process_seqnum (); - break; - - case command_t::own: - process_own (cmd_.args.own.object); - process_seqnum (); - break; - - case command_t::attach: - process_attach (cmd_.args.attach.engine); - process_seqnum (); - break; - - case command_t::bind: - process_bind (cmd_.args.bind.pipe); - process_seqnum (); - break; - - case command_t::hiccup: - process_hiccup (cmd_.args.hiccup.pipe); - break; - - case command_t::pipe_term: - process_pipe_term (); - break; - - case command_t::pipe_term_ack: - process_pipe_term_ack (); - break; - - case command_t::pipe_hwm: - process_pipe_hwm (cmd_.args.pipe_hwm.inhwm, cmd_.args.pipe_hwm.outhwm); - break; - - case command_t::term_req: - process_term_req (cmd_.args.term_req.object); - break; - - case command_t::term: - process_term (cmd_.args.term.linger); - break; - - case command_t::term_ack: - process_term_ack (); - break; - - case command_t::term_endpoint: - process_term_endpoint (cmd_.args.term_endpoint.endpoint); - break; - - case command_t::reap: - process_reap (cmd_.args.reap.socket); - break; - - case command_t::reaped: - process_reaped (); - break; - - case command_t::inproc_connected: - process_seqnum (); - break; - - case command_t::done: - default: - zmq_assert (false); + case command_t::activate_read: + process_activate_read (); + break; + + case command_t::activate_write: + process_activate_write (cmd_.args.activate_write.msgs_read); + break; + + case command_t::stop: + process_stop (); + break; + + case command_t::plug: + process_plug (); + process_seqnum (); + break; + + case command_t::own: + process_own (cmd_.args.own.object); + process_seqnum (); + break; + + case command_t::attach: + process_attach (cmd_.args.attach.engine); + process_seqnum (); + break; + + case command_t::bind: + process_bind (cmd_.args.bind.pipe); + process_seqnum (); + break; + + case command_t::hiccup: + process_hiccup (cmd_.args.hiccup.pipe); + break; + + case command_t::pipe_term: + process_pipe_term (); + break; + + case command_t::pipe_term_ack: + process_pipe_term_ack (); + break; + + case command_t::pipe_hwm: + process_pipe_hwm (cmd_.args.pipe_hwm.inhwm, + cmd_.args.pipe_hwm.outhwm); + break; + + case command_t::term_req: + process_term_req (cmd_.args.term_req.object); + break; + + case command_t::term: + process_term (cmd_.args.term.linger); + break; + + case command_t::term_ack: + process_term_ack (); + break; + + case command_t::term_endpoint: + process_term_endpoint (cmd_.args.term_endpoint.endpoint); + break; + + case command_t::reap: + process_reap (cmd_.args.reap.socket); + break; + + case command_t::reaped: + process_reaped (); + break; + + case command_t::inproc_connected: + process_seqnum (); + break; + + case command_t::done: + default: + zmq_assert (false); } } int zmq::object_t::register_endpoint (const char *addr_, - const endpoint_t &endpoint_) + const endpoint_t &endpoint_) { return ctx->register_endpoint (addr_, endpoint_); } -int zmq::object_t::unregister_endpoint ( - const std::string &addr_, socket_base_t *socket_) +int zmq::object_t::unregister_endpoint (const std::string &addr_, + socket_base_t *socket_) { return ctx->unregister_endpoint (addr_, socket_); } @@ -179,14 +177,16 @@ zmq::endpoint_t zmq::object_t::find_endpoint (const char *addr_) } void zmq::object_t::pend_connection (const std::string &addr_, - const endpoint_t &endpoint_, pipe_t **pipes_) + const endpoint_t &endpoint_, + pipe_t **pipes_) { ctx->pend_connection (addr_, endpoint_, pipes_); } -void zmq::object_t::connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_) +void zmq::object_t::connect_pending (const char *addr_, + zmq::socket_base_t *bind_socket_) { - return ctx->connect_pending(addr_, bind_socket_); + return ctx->connect_pending (addr_, bind_socket_); } void zmq::object_t::destroy_socket (socket_base_t *socket_) @@ -231,7 +231,8 @@ void zmq::object_t::send_own (own_t *destination_, own_t *object_) } void zmq::object_t::send_attach (session_base_t *destination_, - i_engine *engine_, bool inc_seqnum_) + i_engine *engine_, + bool inc_seqnum_) { if (inc_seqnum_) destination_->inc_seqnum (); @@ -243,8 +244,9 @@ void zmq::object_t::send_attach (session_base_t *destination_, send_command (cmd); } -void zmq::object_t::send_bind (own_t *destination_, pipe_t *pipe_, - bool inc_seqnum_) +void zmq::object_t::send_bind (own_t *destination_, + pipe_t *pipe_, + bool inc_seqnum_) { if (inc_seqnum_) destination_->inc_seqnum (); @@ -265,7 +267,7 @@ void zmq::object_t::send_activate_read (pipe_t *destination_) } void zmq::object_t::send_activate_write (pipe_t *destination_, - uint64_t msgs_read_) + uint64_t msgs_read_) { command_t cmd; cmd.destination = destination_; @@ -299,7 +301,9 @@ void zmq::object_t::send_pipe_term_ack (pipe_t *destination_) send_command (cmd); } -void zmq::object_t::send_pipe_hwm (pipe_t *destination_, int inhwm_, int outhwm_) +void zmq::object_t::send_pipe_hwm (pipe_t *destination_, + int inhwm_, + int outhwm_) { command_t cmd; cmd.destination = destination_; @@ -309,8 +313,7 @@ void zmq::object_t::send_pipe_hwm (pipe_t *destination_, int inhwm_, int outhwm_ send_command (cmd); } -void zmq::object_t::send_term_req (own_t *destination_, - own_t *object_) +void zmq::object_t::send_term_req (own_t *destination_, own_t *object_) { command_t cmd; cmd.destination = destination_; @@ -337,7 +340,7 @@ void zmq::object_t::send_term_ack (own_t *destination_) } void zmq::object_t::send_term_endpoint (own_t *destination_, - std::string *endpoint_) + std::string *endpoint_) { command_t cmd; cmd.destination = destination_; @@ -473,4 +476,3 @@ void zmq::object_t::send_command (command_t &cmd_) { ctx->send_command (cmd_.destination->get_tid (), cmd_); } - diff --git a/src/object.hpp b/src/object.hpp index 90e12dd6a4..10cdacac4f 100644 --- a/src/object.hpp +++ b/src/object.hpp @@ -35,122 +35,115 @@ namespace zmq { - - struct i_engine; - struct endpoint_t; - struct pending_connection_t; - struct command_t; - class ctx_t; - class pipe_t; - class socket_base_t; - class session_base_t; - class io_thread_t; - class own_t; - - // Base class for all objects that participate in inter-thread - // communication. - - class object_t - { - public: - - object_t (zmq::ctx_t *ctx_, uint32_t tid_); - object_t (object_t *parent_); - virtual ~object_t (); - - uint32_t get_tid (); - void set_tid(uint32_t id); - ctx_t *get_ctx (); - void process_command (zmq::command_t &cmd_); - void send_inproc_connected (zmq::socket_base_t *socket_); - void send_bind (zmq::own_t *destination_, zmq::pipe_t *pipe_, bool inc_seqnum_ = true); - - protected: - - // Using following function, socket is able to access global - // repository of inproc endpoints. - int register_endpoint (const char *addr_, - const zmq::endpoint_t &endpoint_); - int unregister_endpoint ( - const std::string &addr_, socket_base_t *socket_); - void unregister_endpoints (zmq::socket_base_t *socket_); - zmq::endpoint_t find_endpoint (const char *addr_); - void pend_connection (const std::string &addr_, - const endpoint_t &endpoint, pipe_t **pipes_); - void connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_); - - void destroy_socket (zmq::socket_base_t *socket_); - - // Logs an message. - void log (const char *format_, ...); - - // Chooses least loaded I/O thread. - zmq::io_thread_t *choose_io_thread (uint64_t affinity_); - - // Derived object can use these functions to send commands - // to other objects. - void send_stop (); - void send_plug (zmq::own_t *destination_, - bool inc_seqnum_ = true); - void send_own (zmq::own_t *destination_, - zmq::own_t *object_); - void send_attach (zmq::session_base_t *destination_, - zmq::i_engine *engine_, bool inc_seqnum_ = true); - void send_activate_read (zmq::pipe_t *destination_); - void send_activate_write (zmq::pipe_t *destination_, - uint64_t msgs_read_); - void send_hiccup (zmq::pipe_t *destination_, void *pipe_); - void send_pipe_term (zmq::pipe_t *destination_); - void send_pipe_term_ack (zmq::pipe_t *destination_); - void send_pipe_hwm (zmq::pipe_t *destination_, int inhwm_, int outhwm_); - void send_term_req (zmq::own_t *destination_, - zmq::own_t *object_); - void send_term (zmq::own_t *destination_, int linger_); - void send_term_ack (zmq::own_t *destination_); - void send_term_endpoint (own_t *destination_, std::string *endpoint_); - void send_reap (zmq::socket_base_t *socket_); - void send_reaped (); - void send_done (); - - // These handlers can be overridden by the derived objects. They are - // called when command arrives from another thread. - virtual void process_stop (); - virtual void process_plug (); - virtual void process_own (zmq::own_t *object_); - virtual void process_attach (zmq::i_engine *engine_); - virtual void process_bind (zmq::pipe_t *pipe_); - virtual void process_activate_read (); - virtual void process_activate_write (uint64_t msgs_read_); - virtual void process_hiccup (void *pipe_); - virtual void process_pipe_term (); - virtual void process_pipe_term_ack (); - virtual void process_pipe_hwm (int inhwm_, int outhwm_); - virtual void process_term_req (zmq::own_t *object_); - virtual void process_term (int linger_); - virtual void process_term_ack (); - virtual void process_term_endpoint (std::string *endpoint_); - virtual void process_reap (zmq::socket_base_t *socket_); - virtual void process_reaped (); - - // Special handler called after a command that requires a seqnum - // was processed. The implementation should catch up with its counter - // of processed commands here. - virtual void process_seqnum (); - - private: - - // Context provides access to the global state. - zmq::ctx_t *ctx; - - // Thread ID of the thread the object belongs to. - uint32_t tid; - - void send_command (command_t &cmd_); - - object_t (const object_t&); - const object_t &operator = (const object_t&); - }; - +struct i_engine; +struct endpoint_t; +struct pending_connection_t; +struct command_t; +class ctx_t; +class pipe_t; +class socket_base_t; +class session_base_t; +class io_thread_t; +class own_t; + +// Base class for all objects that participate in inter-thread +// communication. + +class object_t +{ + public: + object_t (zmq::ctx_t *ctx_, uint32_t tid_); + object_t (object_t *parent_); + virtual ~object_t (); + + uint32_t get_tid (); + void set_tid (uint32_t id); + ctx_t *get_ctx (); + void process_command (zmq::command_t &cmd_); + void send_inproc_connected (zmq::socket_base_t *socket_); + void send_bind (zmq::own_t *destination_, + zmq::pipe_t *pipe_, + bool inc_seqnum_ = true); + + protected: + // Using following function, socket is able to access global + // repository of inproc endpoints. + int register_endpoint (const char *addr_, const zmq::endpoint_t &endpoint_); + int unregister_endpoint (const std::string &addr_, socket_base_t *socket_); + void unregister_endpoints (zmq::socket_base_t *socket_); + zmq::endpoint_t find_endpoint (const char *addr_); + void pend_connection (const std::string &addr_, + const endpoint_t &endpoint, + pipe_t **pipes_); + void connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_); + + void destroy_socket (zmq::socket_base_t *socket_); + + // Logs an message. + void log (const char *format_, ...); + + // Chooses least loaded I/O thread. + zmq::io_thread_t *choose_io_thread (uint64_t affinity_); + + // Derived object can use these functions to send commands + // to other objects. + void send_stop (); + void send_plug (zmq::own_t *destination_, bool inc_seqnum_ = true); + void send_own (zmq::own_t *destination_, zmq::own_t *object_); + void send_attach (zmq::session_base_t *destination_, + zmq::i_engine *engine_, + bool inc_seqnum_ = true); + void send_activate_read (zmq::pipe_t *destination_); + void send_activate_write (zmq::pipe_t *destination_, uint64_t msgs_read_); + void send_hiccup (zmq::pipe_t *destination_, void *pipe_); + void send_pipe_term (zmq::pipe_t *destination_); + void send_pipe_term_ack (zmq::pipe_t *destination_); + void send_pipe_hwm (zmq::pipe_t *destination_, int inhwm_, int outhwm_); + void send_term_req (zmq::own_t *destination_, zmq::own_t *object_); + void send_term (zmq::own_t *destination_, int linger_); + void send_term_ack (zmq::own_t *destination_); + void send_term_endpoint (own_t *destination_, std::string *endpoint_); + void send_reap (zmq::socket_base_t *socket_); + void send_reaped (); + void send_done (); + + // These handlers can be overridden by the derived objects. They are + // called when command arrives from another thread. + virtual void process_stop (); + virtual void process_plug (); + virtual void process_own (zmq::own_t *object_); + virtual void process_attach (zmq::i_engine *engine_); + virtual void process_bind (zmq::pipe_t *pipe_); + virtual void process_activate_read (); + virtual void process_activate_write (uint64_t msgs_read_); + virtual void process_hiccup (void *pipe_); + virtual void process_pipe_term (); + virtual void process_pipe_term_ack (); + virtual void process_pipe_hwm (int inhwm_, int outhwm_); + virtual void process_term_req (zmq::own_t *object_); + virtual void process_term (int linger_); + virtual void process_term_ack (); + virtual void process_term_endpoint (std::string *endpoint_); + virtual void process_reap (zmq::socket_base_t *socket_); + virtual void process_reaped (); + + // Special handler called after a command that requires a seqnum + // was processed. The implementation should catch up with its counter + // of processed commands here. + virtual void process_seqnum (); + + private: + // Context provides access to the global state. + zmq::ctx_t *ctx; + + // Thread ID of the thread the object belongs to. + uint32_t tid; + + void send_command (command_t &cmd_); + + object_t (const object_t &); + const object_t &operator= (const object_t &); +}; } #endif diff --git a/src/options.cpp b/src/options.cpp index 6aeb14a7aa..05eec97bf8 100644 --- a/src/options.cpp +++ b/src/options.cpp @@ -69,7 +69,7 @@ zmq::options_t::options_t () : ipv6 (0), immediate (0), filter (false), - invert_matching(false), + invert_matching (false), recv_routing_id (false), raw_socket (false), raw_notify (true), @@ -103,10 +103,11 @@ zmq::options_t::options_t () : #endif } -int zmq::options_t::set_curve_key(uint8_t * destination, const void * optval_, size_t optvallen_) +int zmq::options_t::set_curve_key (uint8_t *destination, + const void *optval_, + size_t optvallen_) { switch (optvallen_) { - case CURVE_KEYSIZE: memcpy (destination, optval_, optvallen_); mechanism = ZMQ_CURVE; @@ -120,9 +121,9 @@ int zmq::options_t::set_curve_key(uint8_t * destination, const void * optval_, s break; case CURVE_KEYSIZE_Z85: - char z85_key [CURVE_KEYSIZE_Z85 + 1]; + char z85_key[CURVE_KEYSIZE_Z85 + 1]; memcpy (z85_key, (char *) optval_, optvallen_); - z85_key [CURVE_KEYSIZE_Z85] = 0; + z85_key[CURVE_KEYSIZE_Z85] = 0; if (zmq_z85_decode (destination, z85_key)) { mechanism = ZMQ_CURVE; return 0; @@ -135,14 +136,16 @@ int zmq::options_t::set_curve_key(uint8_t * destination, const void * optval_, s return -1; } -int zmq::options_t::setsockopt (int option_, const void *optval_, - size_t optvallen_) +int zmq::options_t::setsockopt (int option_, + const void *optval_, + size_t optvallen_) { bool is_int = (optvallen_ == sizeof (int)); int value = 0; - if (is_int) memcpy(&value, optval_, sizeof (int)); -#if defined (ZMQ_ACT_MILITANT) - bool malformed = true; // Did caller pass a bad option value? + if (is_int) + memcpy (&value, optval_, sizeof (int)); +#if defined(ZMQ_ACT_MILITANT) + bool malformed = true; // Did caller pass a bad option value? #endif switch (option_) { @@ -162,7 +165,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, case ZMQ_AFFINITY: if (optvallen_ == sizeof (uint64_t)) { - affinity = *((uint64_t*) optval_); + affinity = *((uint64_t *) optval_); return 0; } break; @@ -308,11 +311,9 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, if (optval_ == NULL && optvallen_ == 0) { socks_proxy_address.clear (); return 0; - } - else - if (optval_ != NULL && optvallen_ > 0 ) { + } else if (optval_ != NULL && optvallen_ > 0) { socks_proxy_address = - std::string ((const char *) optval_, optvallen_); + std::string ((const char *) optval_, optvallen_); return 0; } break; @@ -356,9 +357,8 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, if (optvallen_ == 0 && optval_ == NULL) { tcp_accept_filters.clear (); return 0; - } - else - if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL && *((const char*) optval_) != 0) { + } else if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL + && *((const char *) optval_) != 0) { std::string filter_str ((const char *) optval_, optvallen_); tcp_address_mask_t mask; int rc = mask.resolve (filter_str.c_str (), ipv6); @@ -374,9 +374,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, if (optvallen_ == 0 && optval_ == NULL) { ipc_uid_accept_filters.clear (); return 0; - } - else - if (optvallen_ == sizeof (uid_t) && optval_ != NULL) { + } else if (optvallen_ == sizeof (uid_t) && optval_ != NULL) { ipc_uid_accept_filters.insert (*((uid_t *) optval_)); return 0; } @@ -386,9 +384,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, if (optvallen_ == 0 && optval_ == NULL) { ipc_gid_accept_filters.clear (); return 0; - } - else - if (optvallen_ == sizeof (gid_t) && optval_ != NULL) { + } else if (optvallen_ == sizeof (gid_t) && optval_ != NULL) { ipc_gid_accept_filters.insert (*((gid_t *) optval_)); return 0; } @@ -400,9 +396,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, if (optvallen_ == 0 && optval_ == NULL) { ipc_pid_accept_filters.clear (); return 0; - } - else - if (optvallen_ == sizeof (pid_t) && optval_ != NULL) { + } else if (optvallen_ == sizeof (pid_t) && optval_ != NULL) { ipc_pid_accept_filters.insert (*((pid_t *) optval_)); return 0; } @@ -412,7 +406,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, case ZMQ_PLAIN_SERVER: if (is_int && (value == 0 || value == 1)) { as_server = value; - mechanism = value? ZMQ_PLAIN: ZMQ_NULL; + mechanism = value ? ZMQ_PLAIN : ZMQ_NULL; return 0; } break; @@ -421,9 +415,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, if (optvallen_ == 0 && optval_ == NULL) { mechanism = ZMQ_NULL; return 0; - } - else - if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL) { + } else if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL) { plain_username.assign ((const char *) optval_, optvallen_); as_server = 0; mechanism = ZMQ_PLAIN; @@ -435,9 +427,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, if (optvallen_ == 0 && optval_ == NULL) { mechanism = ZMQ_NULL; return 0; - } - else - if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL) { + } else if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL) { plain_password.assign ((const char *) optval_, optvallen_); as_server = 0; mechanism = ZMQ_PLAIN; @@ -452,30 +442,30 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, } break; - // If curve encryption isn't built, these options provoke EINVAL + // If curve encryption isn't built, these options provoke EINVAL #ifdef ZMQ_HAVE_CURVE case ZMQ_CURVE_SERVER: if (is_int && (value == 0 || value == 1)) { as_server = value; - mechanism = value? ZMQ_CURVE: ZMQ_NULL; + mechanism = value ? ZMQ_CURVE : ZMQ_NULL; return 0; } break; case ZMQ_CURVE_PUBLICKEY: - if(0 == set_curve_key(curve_public_key, optval_, optvallen_)) { + if (0 == set_curve_key (curve_public_key, optval_, optvallen_)) { return 0; } break; case ZMQ_CURVE_SECRETKEY: - if(0 == set_curve_key(curve_secret_key, optval_, optvallen_)) { + if (0 == set_curve_key (curve_secret_key, optval_, optvallen_)) { return 0; } break; case ZMQ_CURVE_SERVERKEY: - if(0 == set_curve_key(curve_server_key, optval_, optvallen_)) { + if (0 == set_curve_key (curve_server_key, optval_, optvallen_)) { as_server = 0; return 0; } @@ -489,7 +479,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, } break; - // If libgssapi isn't installed, these options provoke EINVAL + // If libgssapi isn't installed, these options provoke EINVAL #ifdef HAVE_LIBGSSAPI_KRB5 case ZMQ_GSSAPI_SERVER: if (is_int && (value == 0 || value == 1)) { @@ -509,7 +499,8 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, case ZMQ_GSSAPI_SERVICE_PRINCIPAL: if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL) { - gss_service_principal.assign ((const char *) optval_, optvallen_); + gss_service_principal.assign ((const char *) optval_, + optvallen_); mechanism = ZMQ_GSSAPI; as_server = 0; return 0; @@ -524,18 +515,20 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, break; case ZMQ_GSSAPI_PRINCIPAL_NAMETYPE: - if (is_int && (value == ZMQ_GSSAPI_NT_HOSTBASED - || value == ZMQ_GSSAPI_NT_USER_NAME - || value == ZMQ_GSSAPI_NT_KRB5_PRINCIPAL)) { + if (is_int + && (value == ZMQ_GSSAPI_NT_HOSTBASED + || value == ZMQ_GSSAPI_NT_USER_NAME + || value == ZMQ_GSSAPI_NT_KRB5_PRINCIPAL)) { gss_principal_nt = value; return 0; } break; case ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE: - if (is_int && (value == ZMQ_GSSAPI_NT_HOSTBASED - || value == ZMQ_GSSAPI_NT_USER_NAME - || value == ZMQ_GSSAPI_NT_KRB5_PRINCIPAL)) { + if (is_int + && (value == ZMQ_GSSAPI_NT_HOSTBASED + || value == ZMQ_GSSAPI_NT_USER_NAME + || value == ZMQ_GSSAPI_NT_KRB5_PRINCIPAL)) { gss_service_principal_nt = value; return 0; } @@ -567,7 +560,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, // Convert this to deciseconds from milliseconds value = value / 100; if (is_int && value >= 0 && value <= 6553) { - heartbeat_ttl = (uint16_t)value; + heartbeat_ttl = (uint16_t) value; return 0; } break; @@ -582,28 +575,28 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, #ifdef ZMQ_HAVE_VMCI case ZMQ_VMCI_BUFFER_SIZE: if (optvallen_ == sizeof (uint64_t)) { - vmci_buffer_size = *((uint64_t*) optval_); + vmci_buffer_size = *((uint64_t *) optval_); return 0; } break; case ZMQ_VMCI_BUFFER_MIN_SIZE: if (optvallen_ == sizeof (uint64_t)) { - vmci_buffer_min_size = *((uint64_t*) optval_); + vmci_buffer_min_size = *((uint64_t *) optval_); return 0; } break; case ZMQ_VMCI_BUFFER_MAX_SIZE: if (optvallen_ == sizeof (uint64_t)) { - vmci_buffer_max_size = *((uint64_t*) optval_); + vmci_buffer_max_size = *((uint64_t *) optval_); return 0; } break; case ZMQ_VMCI_CONNECT_TIMEOUT: if (optvallen_ == sizeof (int)) { - vmci_connect_timeout = *((int*) optval_); + vmci_connect_timeout = *((int *) optval_); return 0; } break; @@ -620,11 +613,9 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, if (optval_ == NULL && optvallen_ == 0) { bound_device.clear (); return 0; - } - else - if (optval_ != NULL && optvallen_ > 0 && optvallen_ <= BINDDEVSIZ) { - bound_device = - std::string ((const char *) optval_, optvallen_); + } else if (optval_ != NULL && optvallen_ > 0 + && optvallen_ <= BINDDEVSIZ) { + bound_device = std::string ((const char *) optval_, optvallen_); return 0; } break; @@ -638,7 +629,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, default: -#if defined (ZMQ_ACT_MILITANT) +#if defined(ZMQ_ACT_MILITANT) // There are valid scenarios for probing with unknown socket option // values, e.g. to check if security is enabled or not. This will not // provoke a militant assert. However, passing bad values to a valid @@ -647,7 +638,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, #endif break; } -#if defined (ZMQ_ACT_MILITANT) +#if defined(ZMQ_ACT_MILITANT) // There is no valid use case for passing an error back to the application // when it sent malformed arguments to a socket option. Use ./configure // --with-militant to enable this checking. @@ -658,12 +649,14 @@ int zmq::options_t::setsockopt (int option_, const void *optval_, return -1; } -int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) const +int zmq::options_t::getsockopt (int option_, + void *optval_, + size_t *optvallen_) const { bool is_int = (*optvallen_ == sizeof (int)); int *value = (int *) optval_; -#if defined (ZMQ_ACT_MILITANT) - bool malformed = true; // Did caller pass a bad option value? +#if defined(ZMQ_ACT_MILITANT) + bool malformed = true; // Did caller pass a bad option value? #endif switch (option_) { @@ -839,7 +832,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) case ZMQ_SOCKS_PROXY: if (*optvallen_ >= socks_proxy_address.size () + 1) { - memcpy (optval_, socks_proxy_address.c_str (), socks_proxy_address.size () + 1); + memcpy (optval_, socks_proxy_address.c_str (), + socks_proxy_address.size () + 1); *optvallen_ = socks_proxy_address.size () + 1; return 0; } @@ -889,7 +883,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) case ZMQ_PLAIN_USERNAME: if (*optvallen_ >= plain_username.size () + 1) { - memcpy (optval_, plain_username.c_str (), plain_username.size () + 1); + memcpy (optval_, plain_username.c_str (), + plain_username.size () + 1); *optvallen_ = plain_username.size () + 1; return 0; } @@ -897,7 +892,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) case ZMQ_PLAIN_PASSWORD: if (*optvallen_ >= plain_password.size () + 1) { - memcpy (optval_, plain_password.c_str (), plain_password.size () + 1); + memcpy (optval_, plain_password.c_str (), + plain_password.size () + 1); *optvallen_ = plain_password.size () + 1; return 0; } @@ -911,7 +907,7 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) } break; - // If curve encryption isn't built, these options provoke EINVAL + // If curve encryption isn't built, these options provoke EINVAL #ifdef ZMQ_HAVE_CURVE case ZMQ_CURVE_SERVER: if (is_int) { @@ -924,10 +920,9 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) if (*optvallen_ == CURVE_KEYSIZE) { memcpy (optval_, curve_public_key, CURVE_KEYSIZE); return 0; - } - else - if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) { - zmq_z85_encode ((char *) optval_, curve_public_key, CURVE_KEYSIZE); + } else if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) { + zmq_z85_encode ((char *) optval_, curve_public_key, + CURVE_KEYSIZE); return 0; } break; @@ -936,10 +931,9 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) if (*optvallen_ == CURVE_KEYSIZE) { memcpy (optval_, curve_secret_key, CURVE_KEYSIZE); return 0; - } - else - if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) { - zmq_z85_encode ((char *) optval_, curve_secret_key, CURVE_KEYSIZE); + } else if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) { + zmq_z85_encode ((char *) optval_, curve_secret_key, + CURVE_KEYSIZE); return 0; } break; @@ -948,10 +942,9 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) if (*optvallen_ == CURVE_KEYSIZE) { memcpy (optval_, curve_server_key, CURVE_KEYSIZE); return 0; - } - else - if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) { - zmq_z85_encode ((char *) optval_, curve_server_key, CURVE_KEYSIZE); + } else if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) { + zmq_z85_encode ((char *) optval_, curve_server_key, + CURVE_KEYSIZE); return 0; } break; @@ -964,7 +957,7 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) } break; - // If libgssapi isn't installed, these options provoke EINVAL + // If libgssapi isn't installed, these options provoke EINVAL #ifdef HAVE_LIBGSSAPI_KRB5 case ZMQ_GSSAPI_SERVER: if (is_int) { @@ -975,7 +968,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) case ZMQ_GSSAPI_PRINCIPAL: if (*optvallen_ >= gss_principal.size () + 1) { - memcpy (optval_, gss_principal.c_str (), gss_principal.size () + 1); + memcpy (optval_, gss_principal.c_str (), + gss_principal.size () + 1); *optvallen_ = gss_principal.size () + 1; return 0; } @@ -983,7 +977,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) case ZMQ_GSSAPI_SERVICE_PRINCIPAL: if (*optvallen_ >= gss_service_principal.size () + 1) { - memcpy (optval_, gss_service_principal.c_str (), gss_service_principal.size () + 1); + memcpy (optval_, gss_service_principal.c_str (), + gss_service_principal.size () + 1); *optvallen_ = gss_service_principal.size () + 1; return 0; } @@ -1055,7 +1050,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) case ZMQ_BINDTODEVICE: if (*optvallen_ >= bound_device.size () + 1) { - memcpy (optval_, bound_device.c_str (), bound_device.size () + 1); + memcpy (optval_, bound_device.c_str (), + bound_device.size () + 1); *optvallen_ = bound_device.size () + 1; return 0; } @@ -1069,12 +1065,12 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_) break; default: -#if defined (ZMQ_ACT_MILITANT) +#if defined(ZMQ_ACT_MILITANT) malformed = false; #endif break; } -#if defined (ZMQ_ACT_MILITANT) +#if defined(ZMQ_ACT_MILITANT) if (malformed) zmq_assert (false); #endif diff --git a/src/options.hpp b/src/options.hpp index ff9fac056d..d5104f72b7 100644 --- a/src/options.hpp +++ b/src/options.hpp @@ -46,206 +46,208 @@ #endif // Normal base 256 key is 32 bytes -#define CURVE_KEYSIZE 32 +#define CURVE_KEYSIZE 32 // Key encoded using Z85 is 40 bytes -#define CURVE_KEYSIZE_Z85 40 +#define CURVE_KEYSIZE_Z85 40 namespace zmq { - struct options_t - { - options_t (); +struct options_t +{ + options_t (); + + int set_curve_key (uint8_t *destination, + const void *optval_, + size_t optvallen_); + + int setsockopt (int option_, const void *optval_, size_t optvallen_); + int getsockopt (int option_, void *optval_, size_t *optvallen_) const; + + bool is_valid (int option_) const; + + // High-water marks for message pipes. + int sndhwm; + int rcvhwm; + + // I/O thread affinity. + uint64_t affinity; + + // Socket routing id. + unsigned char routing_id_size; + unsigned char routing_id[256]; + + // Maximum transfer rate [kb/s]. Default 100kb/s. + int rate; - int set_curve_key(uint8_t * destination, const void * optval_, size_t optvallen_); + // Reliability time interval [ms]. Default 10 seconds. + int recovery_ivl; - int setsockopt (int option_, const void *optval_, size_t optvallen_); - int getsockopt (int option_, void *optval_, size_t *optvallen_) const; + // Sets the time-to-live field in every multicast packet sent. + int multicast_hops; - bool is_valid (int option_) const; + // Sets the maximum transport data unit size in every multicast + // packet sent. + int multicast_maxtpdu; - // High-water marks for message pipes. - int sndhwm; - int rcvhwm; + // SO_SNDBUF and SO_RCVBUF to be passed to underlying transport sockets. + int sndbuf; + int rcvbuf; - // I/O thread affinity. - uint64_t affinity; + // Type of service (containing DSCP and ECN socket options) + int tos; - // Socket routing id. - unsigned char routing_id_size; - unsigned char routing_id [256]; + // Socket type. + int type; - // Maximum transfer rate [kb/s]. Default 100kb/s. - int rate; + // Linger time, in milliseconds. + int linger; - // Reliability time interval [ms]. Default 10 seconds. - int recovery_ivl; + // Maximum interval in milliseconds beyond which userspace will + // timeout connect(). + // Default 0 (unused) + int connect_timeout; - // Sets the time-to-live field in every multicast packet sent. - int multicast_hops; + // Maximum interval in milliseconds beyond which TCP will timeout + // retransmitted packets. + // Default 0 (unused) + int tcp_maxrt; - // Sets the maximum transport data unit size in every multicast - // packet sent. - int multicast_maxtpdu; + // Minimum interval between attempts to reconnect, in milliseconds. + // Default 100ms + int reconnect_ivl; - // SO_SNDBUF and SO_RCVBUF to be passed to underlying transport sockets. - int sndbuf; - int rcvbuf; + // Maximum interval between attempts to reconnect, in milliseconds. + // Default 0 (unused) + int reconnect_ivl_max; - // Type of service (containing DSCP and ECN socket options) - int tos; + // Maximum backlog for pending connections. + int backlog; - // Socket type. - int type; + // Maximal size of message to handle. + int64_t maxmsgsize; - // Linger time, in milliseconds. - int linger; + // The timeout for send/recv operations for this socket, in milliseconds. + int rcvtimeo; + int sndtimeo; - // Maximum interval in milliseconds beyond which userspace will - // timeout connect(). - // Default 0 (unused) - int connect_timeout; + // If true, IPv6 is enabled (as well as IPv4) + bool ipv6; - // Maximum interval in milliseconds beyond which TCP will timeout - // retransmitted packets. - // Default 0 (unused) - int tcp_maxrt; + // If 1, connecting pipes are not attached immediately, meaning a send() + // on a socket with only connecting pipes would block + int immediate; - // Minimum interval between attempts to reconnect, in milliseconds. - // Default 100ms - int reconnect_ivl; + // If 1, (X)SUB socket should filter the messages. If 0, it should not. + bool filter; - // Maximum interval between attempts to reconnect, in milliseconds. - // Default 0 (unused) - int reconnect_ivl_max; + // If true, the subscription matching on (X)PUB and (X)SUB sockets + // is reversed. Messages are sent to and received by non-matching + // sockets. + bool invert_matching; - // Maximum backlog for pending connections. - int backlog; + // If true, the routing id message is forwarded to the socket. + bool recv_routing_id; - // Maximal size of message to handle. - int64_t maxmsgsize; + // if true, router socket accepts non-zmq tcp connections + bool raw_socket; + bool raw_notify; // Provide connect notifications - // The timeout for send/recv operations for this socket, in milliseconds. - int rcvtimeo; - int sndtimeo; + // Address of SOCKS proxy + std::string socks_proxy_address; - // If true, IPv6 is enabled (as well as IPv4) - bool ipv6; + // TCP keep-alive settings. + // Defaults to -1 = do not change socket options + int tcp_keepalive; + int tcp_keepalive_cnt; + int tcp_keepalive_idle; + int tcp_keepalive_intvl; + + // TCP accept() filters + typedef std::vector tcp_accept_filters_t; + tcp_accept_filters_t tcp_accept_filters; + + // IPC accept() filters +#if defined ZMQ_HAVE_SO_PEERCRED || defined ZMQ_HAVE_LOCAL_PEERCRED + typedef std::set ipc_uid_accept_filters_t; + ipc_uid_accept_filters_t ipc_uid_accept_filters; + typedef std::set ipc_gid_accept_filters_t; + ipc_gid_accept_filters_t ipc_gid_accept_filters; +#endif +#if defined ZMQ_HAVE_SO_PEERCRED + typedef std::set ipc_pid_accept_filters_t; + ipc_pid_accept_filters_t ipc_pid_accept_filters; +#endif + + // Security mechanism for all connections on this socket + int mechanism; + + // If peer is acting as server for PLAIN or CURVE mechanisms + int as_server; + + // ZAP authentication domain + std::string zap_domain; + + // Security credentials for PLAIN mechanism + std::string plain_username; + std::string plain_password; + + // Security credentials for CURVE mechanism + uint8_t curve_public_key[CURVE_KEYSIZE]; + uint8_t curve_secret_key[CURVE_KEYSIZE]; + uint8_t curve_server_key[CURVE_KEYSIZE]; + + // Principals for GSSAPI mechanism + std::string gss_principal; + std::string gss_service_principal; + + // Name types GSSAPI principals + int gss_principal_nt; + int gss_service_principal_nt; + + // If true, gss encryption will be disabled + bool gss_plaintext; + + // ID of the socket. + int socket_id; + + // If true, socket conflates outgoing/incoming messages. + // Applicable to dealer, push/pull, pub/sub socket types. + // Cannot receive multi-part messages. + // Ignores hwm + bool conflate; + + // If connection handshake is not done after this many milliseconds, + // close socket. Default is 30 secs. 0 means no handshake timeout. + int handshake_ivl; + + bool connected; + // If remote peer receives a PING message and doesn't receive another + // message within the ttl value, it should close the connection + // (measured in tenths of a second) + uint16_t heartbeat_ttl; + // Time in milliseconds between sending heartbeat PING messages. + int heartbeat_interval; + // Time in milliseconds to wait for a PING response before disconnecting + int heartbeat_timeout; + +#if defined ZMQ_HAVE_VMCI + uint64_t vmci_buffer_size; + uint64_t vmci_buffer_min_size; + uint64_t vmci_buffer_max_size; + int vmci_connect_timeout; +#endif - // If 1, connecting pipes are not attached immediately, meaning a send() - // on a socket with only connecting pipes would block - int immediate; + // When creating a new ZMQ socket, if this option is set the value + // will be used as the File Descriptor instead of allocating a new + // one via the socket () system call. + int use_fd; - // If 1, (X)SUB socket should filter the messages. If 0, it should not. - bool filter; - - // If true, the subscription matching on (X)PUB and (X)SUB sockets - // is reversed. Messages are sent to and received by non-matching - // sockets. - bool invert_matching; + // Device to bind the underlying socket to, eg. VRF or interface + std::string bound_device; - // If true, the routing id message is forwarded to the socket. - bool recv_routing_id; - - // if true, router socket accepts non-zmq tcp connections - bool raw_socket; - bool raw_notify; // Provide connect notifications - - // Address of SOCKS proxy - std::string socks_proxy_address; - - // TCP keep-alive settings. - // Defaults to -1 = do not change socket options - int tcp_keepalive; - int tcp_keepalive_cnt; - int tcp_keepalive_idle; - int tcp_keepalive_intvl; - - // TCP accept() filters - typedef std::vector tcp_accept_filters_t; - tcp_accept_filters_t tcp_accept_filters; - - // IPC accept() filters -# if defined ZMQ_HAVE_SO_PEERCRED || defined ZMQ_HAVE_LOCAL_PEERCRED - typedef std::set ipc_uid_accept_filters_t; - ipc_uid_accept_filters_t ipc_uid_accept_filters; - typedef std::set ipc_gid_accept_filters_t; - ipc_gid_accept_filters_t ipc_gid_accept_filters; -# endif -# if defined ZMQ_HAVE_SO_PEERCRED - typedef std::set ipc_pid_accept_filters_t; - ipc_pid_accept_filters_t ipc_pid_accept_filters; -# endif - - // Security mechanism for all connections on this socket - int mechanism; - - // If peer is acting as server for PLAIN or CURVE mechanisms - int as_server; - - // ZAP authentication domain - std::string zap_domain; - - // Security credentials for PLAIN mechanism - std::string plain_username; - std::string plain_password; - - // Security credentials for CURVE mechanism - uint8_t curve_public_key [CURVE_KEYSIZE]; - uint8_t curve_secret_key [CURVE_KEYSIZE]; - uint8_t curve_server_key [CURVE_KEYSIZE]; - - // Principals for GSSAPI mechanism - std::string gss_principal; - std::string gss_service_principal; - - // Name types GSSAPI principals - int gss_principal_nt; - int gss_service_principal_nt; - - // If true, gss encryption will be disabled - bool gss_plaintext; - - // ID of the socket. - int socket_id; - - // If true, socket conflates outgoing/incoming messages. - // Applicable to dealer, push/pull, pub/sub socket types. - // Cannot receive multi-part messages. - // Ignores hwm - bool conflate; - - // If connection handshake is not done after this many milliseconds, - // close socket. Default is 30 secs. 0 means no handshake timeout. - int handshake_ivl; - - bool connected; - // If remote peer receives a PING message and doesn't receive another - // message within the ttl value, it should close the connection - // (measured in tenths of a second) - uint16_t heartbeat_ttl; - // Time in milliseconds between sending heartbeat PING messages. - int heartbeat_interval; - // Time in milliseconds to wait for a PING response before disconnecting - int heartbeat_timeout; - -# if defined ZMQ_HAVE_VMCI - uint64_t vmci_buffer_size; - uint64_t vmci_buffer_min_size; - uint64_t vmci_buffer_max_size; - int vmci_connect_timeout; -# endif - - // When creating a new ZMQ socket, if this option is set the value - // will be used as the File Descriptor instead of allocating a new - // one via the socket () system call. - int use_fd; - - // Device to bind the underlying socket to, eg. VRF or interface - std::string bound_device; - - // Enforce a non-empty ZAP domain requirement for PLAIN auth - bool zap_enforce_domain; - }; + // Enforce a non-empty ZAP domain requirement for PLAIN auth + bool zap_enforce_domain; +}; } #endif diff --git a/src/own.cpp b/src/own.cpp index b87f4ee034..3fc4fabf0f 100644 --- a/src/own.cpp +++ b/src/own.cpp @@ -193,9 +193,8 @@ void zmq::own_t::process_term_ack () void zmq::own_t::check_term_acks () { - if (terminating && processed_seqnum == sent_seqnum.get () && - term_acks == 0) { - + if (terminating && processed_seqnum == sent_seqnum.get () + && term_acks == 0) { // Sanity check. There should be no active children at this point. zmq_assert (owned.empty ()); @@ -213,4 +212,3 @@ void zmq::own_t::process_destroy () { delete this; } - diff --git a/src/own.hpp b/src/own.hpp index 4c71dbd5ba..8c2732fcd0 100644 --- a/src/own.hpp +++ b/src/own.hpp @@ -40,115 +40,110 @@ namespace zmq { +class ctx_t; +class io_thread_t; - class ctx_t; - class io_thread_t; - - // Base class for objects forming a part of ownership hierarchy. - // It handles initialisation and destruction of such objects. - - class own_t : public object_t - { - public: - - // Note that the owner is unspecified in the constructor. - // It'll be supplied later on when the object is plugged in. - - // The object is not living within an I/O thread. It has it's own - // thread outside of 0MQ infrastructure. - own_t (zmq::ctx_t *parent_, uint32_t tid_); - - // The object is living within I/O thread. - own_t (zmq::io_thread_t *io_thread_, const options_t &options_); - - // When another owned object wants to send command to this object - // it calls this function to let it know it should not shut down - // before the command is delivered. - void inc_seqnum (); - - // Use following two functions to wait for arbitrary events before - // terminating. Just add number of events to wait for using - // register_tem_acks functions. When event occurs, call - // remove_term_ack. When number of pending acks reaches zero - // object will be deallocated. - void register_term_acks (int count_); - void unregister_term_ack (); - - protected: - - // Launch the supplied object and become its owner. - void launch_child (own_t *object_); - - // Terminate owned object - void term_child (own_t *object_); - - // Ask owner object to terminate this object. It may take a while - // while actual termination is started. This function should not be - // called more than once. - void terminate (); - - // Returns true if the object is in process of termination. - bool is_terminating (); - - // Derived object destroys own_t. There's no point in allowing - // others to invoke the destructor. At the same time, it has to be - // virtual so that generic own_t deallocation mechanism destroys - // specific type of the owned object correctly. - virtual ~own_t (); - - // Term handler is protected rather than private so that it can - // be intercepted by the derived class. This is useful to add custom - // steps to the beginning of the termination process. - void process_term (int linger_); - - // A place to hook in when physical destruction of the object - // is to be delayed. - virtual void process_destroy (); - - // Socket options associated with this object. - options_t options; - - private: - - // Set owner of the object - void set_owner (own_t *owner_); - - // Handlers for incoming commands. - void process_own (own_t *object_); - void process_term_req (own_t *object_); - void process_term_ack (); - void process_seqnum (); - - // Check whether all the pending term acks were delivered. - // If so, deallocate this object. - void check_term_acks (); - - // True if termination was already initiated. If so, we can destroy - // the object if there are no more child objects or pending term acks. - bool terminating; - - // Sequence number of the last command sent to this object. - atomic_counter_t sent_seqnum; - - // Sequence number of the last command processed by this object. - uint64_t processed_seqnum; - - // Socket owning this object. It's responsible for shutting down - // this object. - own_t *owner; - - // List of all objects owned by this socket. We are responsible - // for deallocating them before we quit. - typedef std::set owned_t; - owned_t owned; - - // Number of events we have to get before we can destroy the object. - int term_acks; - - own_t (const own_t&); - const own_t &operator = (const own_t&); - }; +// Base class for objects forming a part of ownership hierarchy. +// It handles initialisation and destruction of such objects. +class own_t : public object_t +{ + public: + // Note that the owner is unspecified in the constructor. + // It'll be supplied later on when the object is plugged in. + + // The object is not living within an I/O thread. It has it's own + // thread outside of 0MQ infrastructure. + own_t (zmq::ctx_t *parent_, uint32_t tid_); + + // The object is living within I/O thread. + own_t (zmq::io_thread_t *io_thread_, const options_t &options_); + + // When another owned object wants to send command to this object + // it calls this function to let it know it should not shut down + // before the command is delivered. + void inc_seqnum (); + + // Use following two functions to wait for arbitrary events before + // terminating. Just add number of events to wait for using + // register_tem_acks functions. When event occurs, call + // remove_term_ack. When number of pending acks reaches zero + // object will be deallocated. + void register_term_acks (int count_); + void unregister_term_ack (); + + protected: + // Launch the supplied object and become its owner. + void launch_child (own_t *object_); + + // Terminate owned object + void term_child (own_t *object_); + + // Ask owner object to terminate this object. It may take a while + // while actual termination is started. This function should not be + // called more than once. + void terminate (); + + // Returns true if the object is in process of termination. + bool is_terminating (); + + // Derived object destroys own_t. There's no point in allowing + // others to invoke the destructor. At the same time, it has to be + // virtual so that generic own_t deallocation mechanism destroys + // specific type of the owned object correctly. + virtual ~own_t (); + + // Term handler is protected rather than private so that it can + // be intercepted by the derived class. This is useful to add custom + // steps to the beginning of the termination process. + void process_term (int linger_); + + // A place to hook in when physical destruction of the object + // is to be delayed. + virtual void process_destroy (); + + // Socket options associated with this object. + options_t options; + + private: + // Set owner of the object + void set_owner (own_t *owner_); + + // Handlers for incoming commands. + void process_own (own_t *object_); + void process_term_req (own_t *object_); + void process_term_ack (); + void process_seqnum (); + + // Check whether all the pending term acks were delivered. + // If so, deallocate this object. + void check_term_acks (); + + // True if termination was already initiated. If so, we can destroy + // the object if there are no more child objects or pending term acks. + bool terminating; + + // Sequence number of the last command sent to this object. + atomic_counter_t sent_seqnum; + + // Sequence number of the last command processed by this object. + uint64_t processed_seqnum; + + // Socket owning this object. It's responsible for shutting down + // this object. + own_t *owner; + + // List of all objects owned by this socket. We are responsible + // for deallocating them before we quit. + typedef std::set owned_t; + owned_t owned; + + // Number of events we have to get before we can destroy the object. + int term_acks; + + own_t (const own_t &); + const own_t &operator= (const own_t &); +}; } #endif diff --git a/src/pair.cpp b/src/pair.cpp index 586007e551..cb60c8582f 100644 --- a/src/pair.cpp +++ b/src/pair.cpp @@ -108,7 +108,6 @@ int zmq::pair_t::xrecv (msg_t *msg_) errno_assert (rc == 0); if (!pipe || !pipe->read (msg_)) { - // Initialise the output parameter to be a 0-byte message. rc = msg_->init (); errno_assert (rc == 0); @@ -138,5 +137,5 @@ bool zmq::pair_t::xhas_out () const zmq::blob_t &zmq::pair_t::get_credential () const { - return last_in? last_in->get_credential (): saved_credential; + return last_in ? last_in->get_credential () : saved_credential; } diff --git a/src/pair.hpp b/src/pair.hpp index 63c46e29b7..7938a3636e 100644 --- a/src/pair.hpp +++ b/src/pair.hpp @@ -36,43 +36,38 @@ namespace zmq { +class ctx_t; +class msg_t; +class pipe_t; +class io_thread_t; - class ctx_t; - class msg_t; - class pipe_t; - class io_thread_t; - - class pair_t : - public socket_base_t - { - public: - - pair_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); - ~pair_t (); - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsend (zmq::msg_t *msg_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - bool xhas_out (); - const blob_t &get_credential () const; - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - - zmq::pipe_t *pipe; - - zmq::pipe_t *last_in; - - blob_t saved_credential; - - pair_t (const pair_t&); - const pair_t &operator = (const pair_t&); - }; - +class pair_t : public socket_base_t +{ + public: + pair_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); + ~pair_t (); + + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsend (zmq::msg_t *msg_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + bool xhas_out (); + const blob_t &get_credential () const; + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + zmq::pipe_t *pipe; + + zmq::pipe_t *last_in; + + blob_t saved_credential; + + pair_t (const pair_t &); + const pair_t &operator= (const pair_t &); +}; } #endif diff --git a/src/pgm_receiver.cpp b/src/pgm_receiver.cpp index 6398929fcf..cbbaf16df2 100644 --- a/src/pgm_receiver.cpp +++ b/src/pgm_receiver.cpp @@ -42,7 +42,7 @@ #include "err.hpp" zmq::pgm_receiver_t::pgm_receiver_t (class io_thread_t *parent_, - const options_t &options_) : + const options_t &options_) : io_object_t (parent_), has_rx_timer (false), pgm_socket (true, options_), @@ -65,7 +65,7 @@ int zmq::pgm_receiver_t::init (bool udp_encapsulation_, const char *network_) } void zmq::pgm_receiver_t::plug (io_thread_t *io_thread_, - session_base_t *session_) + session_base_t *session_) { LIBZMQ_UNUSED (io_thread_); // Retrieve PGM fds and start polling. @@ -88,7 +88,7 @@ void zmq::pgm_receiver_t::unplug () // Delete decoders. for (peers_t::iterator it = peers.begin (); it != peers.end (); ++it) { if (it->second.decoder != NULL) { - LIBZMQ_DELETE(it->second.decoder); + LIBZMQ_DELETE (it->second.decoder); } } peers.clear (); @@ -140,7 +140,7 @@ void zmq::pgm_receiver_t::restart_input () // Data error. Delete message decoder, mark the // peer as not joined and drop remaining data. it->second.joined = false; - LIBZMQ_DELETE(it->second.decoder); + LIBZMQ_DELETE (it->second.decoder); insize = 0; } } @@ -171,12 +171,11 @@ void zmq::pgm_receiver_t::in_event () // TODO: This loop can effectively block other engines in the same I/O // thread in the case of high load. while (true) { - // Get new batch of data. // Note the workaround made not to break strict-aliasing rules. void *tmp = NULL; ssize_t received = pgm_socket.receive (&tmp, &tsi); - inpos = (unsigned char*) tmp; + inpos = (unsigned char *) tmp; // No data to process. This may happen if the packet received is // neither ODATA nor ODATA. @@ -197,7 +196,7 @@ void zmq::pgm_receiver_t::in_event () if (it != peers.end ()) { it->second.joined = false; if (it->second.decoder != NULL) { - LIBZMQ_DELETE(it->second.decoder); + LIBZMQ_DELETE (it->second.decoder); } } break; @@ -209,7 +208,7 @@ void zmq::pgm_receiver_t::in_event () it = peers.ZMQ_MAP_INSERT_OR_EMPLACE (*tsi, peer_info).first; } - insize = static_cast (received); + insize = static_cast (received); // Read the offset of the fist message in the current packet. zmq_assert (insize >= sizeof (uint16_t)); @@ -219,7 +218,6 @@ void zmq::pgm_receiver_t::in_event () // Join the stream if needed. if (!it->second.joined) { - // There is no beginning of the message in current packet. // Ignore the data. if (offset == 0xffff) @@ -236,8 +234,8 @@ void zmq::pgm_receiver_t::in_event () it->second.joined = true; // Create and connect decoder for the peer. - it->second.decoder = new (std::nothrow) - v1_decoder_t (0, options.maxmsgsize); + it->second.decoder = + new (std::nothrow) v1_decoder_t (0, options.maxmsgsize); alloc_assert (it->second.decoder); } @@ -254,7 +252,7 @@ void zmq::pgm_receiver_t::in_event () } it->second.joined = false; - LIBZMQ_DELETE(it->second.decoder); + LIBZMQ_DELETE (it->second.decoder); insize = 0; } } @@ -304,4 +302,3 @@ void zmq::pgm_receiver_t::drop_subscriptions () } #endif - diff --git a/src/pgm_receiver.hpp b/src/pgm_receiver.hpp index 7c854e7881..d377d8fde4 100644 --- a/src/pgm_receiver.hpp +++ b/src/pgm_receiver.hpp @@ -43,103 +43,99 @@ namespace zmq { +class io_thread_t; +class session_base_t; - class io_thread_t; - class session_base_t; - - class pgm_receiver_t : public io_object_t, public i_engine +class pgm_receiver_t : public io_object_t, public i_engine +{ + public: + pgm_receiver_t (zmq::io_thread_t *parent_, const options_t &options_); + ~pgm_receiver_t (); + + int init (bool udp_encapsulation_, const char *network_); + + // i_engine interface implementation. + void plug (zmq::io_thread_t *io_thread_, zmq::session_base_t *session_); + void terminate (); + void restart_input (); + void restart_output (); + void zap_msg_available () {} + const char *get_endpoint () const; + + // i_poll_events interface implementation. + void in_event (); + void timer_event (int token); + + private: + // Unplug the engine from the session. + void unplug (); + + // Decode received data (inpos, insize) and forward decoded + // messages to the session. + int process_input (v1_decoder_t *decoder); + + // PGM is not able to move subscriptions upstream. Thus, drop all + // the pending subscriptions. + void drop_subscriptions (); + + // RX timeout timer ID. + enum { + rx_timer_id = 0xa1 + }; - public: - - pgm_receiver_t (zmq::io_thread_t *parent_, const options_t &options_); - ~pgm_receiver_t (); - - int init (bool udp_encapsulation_, const char *network_); - - // i_engine interface implementation. - void plug (zmq::io_thread_t *io_thread_, - zmq::session_base_t *session_); - void terminate (); - void restart_input (); - void restart_output (); - void zap_msg_available () {} - const char *get_endpoint () const; - - // i_poll_events interface implementation. - void in_event (); - void timer_event (int token); - - private: - - // Unplug the engine from the session. - void unplug (); - - // Decode received data (inpos, insize) and forward decoded - // messages to the session. - int process_input (v1_decoder_t *decoder); - - // PGM is not able to move subscriptions upstream. Thus, drop all - // the pending subscriptions. - void drop_subscriptions (); - - // RX timeout timer ID. - enum {rx_timer_id = 0xa1}; - - // RX timer is running. - bool has_rx_timer; + // RX timer is running. + bool has_rx_timer; - // If joined is true we are already getting messages from the peer. - // It it's false, we are getting data but still we haven't seen - // beginning of a message. - struct peer_info_t - { - bool joined; - v1_decoder_t *decoder; - }; + // If joined is true we are already getting messages from the peer. + // It it's false, we are getting data but still we haven't seen + // beginning of a message. + struct peer_info_t + { + bool joined; + v1_decoder_t *decoder; + }; - struct tsi_comp + struct tsi_comp + { + bool operator() (const pgm_tsi_t <si, const pgm_tsi_t &rtsi) const { - bool operator () (const pgm_tsi_t <si, - const pgm_tsi_t &rtsi) const - { - uint32_t ll[2], rl[2]; - memcpy (ll, <si, sizeof (ll)); - memcpy (rl, &rtsi, sizeof (rl)); - return (ll[0] < rl[0]) || (ll[0] == rl[0] && ll[1] < rl[1]); - } - }; - - typedef std::map peers_t; - peers_t peers; + uint32_t ll[2], rl[2]; + memcpy (ll, <si, sizeof (ll)); + memcpy (rl, &rtsi, sizeof (rl)); + return (ll[0] < rl[0]) || (ll[0] == rl[0] && ll[1] < rl[1]); + } + }; - // PGM socket. - pgm_socket_t pgm_socket; + typedef std::map peers_t; + peers_t peers; - // Socket options. - options_t options; + // PGM socket. + pgm_socket_t pgm_socket; - // Associated session. - zmq::session_base_t *session; + // Socket options. + options_t options; - const pgm_tsi_t *active_tsi; + // Associated session. + zmq::session_base_t *session; - // Number of bytes not consumed by the decoder due to pipe overflow. - size_t insize; + const pgm_tsi_t *active_tsi; - // Pointer to data still waiting to be processed by the decoder. - const unsigned char *inpos; + // Number of bytes not consumed by the decoder due to pipe overflow. + size_t insize; - // Poll handle associated with PGM socket. - handle_t socket_handle; + // Pointer to data still waiting to be processed by the decoder. + const unsigned char *inpos; - // Poll handle associated with engine PGM waiting pipe. - handle_t pipe_handle; + // Poll handle associated with PGM socket. + handle_t socket_handle; - pgm_receiver_t (const pgm_receiver_t&); - const pgm_receiver_t &operator = (const pgm_receiver_t&); - }; + // Poll handle associated with engine PGM waiting pipe. + handle_t pipe_handle; + pgm_receiver_t (const pgm_receiver_t &); + const pgm_receiver_t &operator= (const pgm_receiver_t &); +}; } #endif diff --git a/src/pgm_sender.cpp b/src/pgm_sender.cpp index b49fcf6733..9d2f5afa45 100644 --- a/src/pgm_sender.cpp +++ b/src/pgm_sender.cpp @@ -42,7 +42,7 @@ #include "macros.hpp" zmq::pgm_sender_t::pgm_sender_t (io_thread_t *parent_, - const options_t &options_) : + const options_t &options_) : io_object_t (parent_), has_tx_timer (false), has_rx_timer (false), @@ -66,7 +66,7 @@ int zmq::pgm_sender_t::init (bool udp_encapsulation_, const char *network_) return rc; out_buffer_size = pgm_socket.get_max_tsdu_size (); - out_buffer = (unsigned char*) malloc (out_buffer_size); + out_buffer = (unsigned char *) malloc (out_buffer_size); alloc_assert (out_buffer); return rc; @@ -85,7 +85,7 @@ void zmq::pgm_sender_t::plug (io_thread_t *io_thread_, session_base_t *session_) // Fill fds from PGM transport and add them to the poller. pgm_socket.get_sender_fds (&downlink_socket_fd, &uplink_socket_fd, - &rdata_notify_fd, &pending_notify_fd); + &rdata_notify_fd, &pending_notify_fd); handle = add_fd (downlink_socket_fd); uplink_handle = add_fd (uplink_socket_fd); @@ -175,7 +175,6 @@ void zmq::pgm_sender_t::out_event () // POLLOUT event from send socket. If write buffer is empty, // try to read new data from the encoder. if (write_size == 0) { - // First two bytes (sizeof uint16_t) are used to store message // offset in following steps. Note that by passing our buffer to // the get data function we prevent it from returning its own buffer. @@ -186,7 +185,7 @@ void zmq::pgm_sender_t::out_event () size_t bytes = encoder.encode (&bf, bfsz); while (bytes < bfsz) { if (!more_flag && offset == 0xffff) - offset = static_cast (bytes); + offset = static_cast (bytes); int rc = session->pull_msg (&msg); if (rc == -1) break; @@ -229,8 +228,7 @@ void zmq::pgm_sender_t::out_event () add_timer (timeout, tx_timer_id); reset_pollout (handle); has_tx_timer = true; - } - else + } else errno_assert (errno == EBUSY); } } @@ -241,17 +239,13 @@ void zmq::pgm_sender_t::timer_event (int token) if (token == rx_timer_id) { has_rx_timer = false; in_event (); - } - else - if (token == tx_timer_id) { + } else if (token == tx_timer_id) { // Restart polling handle and retry sending has_tx_timer = false; set_pollout (handle); out_event (); - } - else + } else zmq_assert (false); } #endif - diff --git a/src/pgm_sender.hpp b/src/pgm_sender.hpp index 973bac26e3..dfc7942546 100644 --- a/src/pgm_sender.hpp +++ b/src/pgm_sender.hpp @@ -42,82 +42,80 @@ namespace zmq { +class io_thread_t; +class session_base_t; - class io_thread_t; - class session_base_t; - - class pgm_sender_t : public io_object_t, public i_engine +class pgm_sender_t : public io_object_t, public i_engine +{ + public: + pgm_sender_t (zmq::io_thread_t *parent_, const options_t &options_); + ~pgm_sender_t (); + + int init (bool udp_encapsulation_, const char *network_); + + // i_engine interface implementation. + void plug (zmq::io_thread_t *io_thread_, zmq::session_base_t *session_); + void terminate (); + void restart_input (); + void restart_output (); + void zap_msg_available () {} + const char *get_endpoint () const; + + // i_poll_events interface implementation. + void in_event (); + void out_event (); + void timer_event (int token); + + private: + // Unplug the engine from the session. + void unplug (); + + // TX and RX timeout timer ID's. + enum { + tx_timer_id = 0xa0, + rx_timer_id = 0xa1 + }; - public: - - pgm_sender_t (zmq::io_thread_t *parent_, const options_t &options_); - ~pgm_sender_t (); - - int init (bool udp_encapsulation_, const char *network_); - - // i_engine interface implementation. - void plug (zmq::io_thread_t *io_thread_, - zmq::session_base_t *session_); - void terminate (); - void restart_input (); - void restart_output (); - void zap_msg_available () {} - const char *get_endpoint () const; - - // i_poll_events interface implementation. - void in_event (); - void out_event (); - void timer_event (int token); - - private: - - // Unplug the engine from the session. - void unplug (); - - // TX and RX timeout timer ID's. - enum {tx_timer_id = 0xa0, rx_timer_id = 0xa1}; - - // Timers are running. - bool has_tx_timer; - bool has_rx_timer; - - session_base_t *session; + // Timers are running. + bool has_tx_timer; + bool has_rx_timer; - // Message encoder. - v1_encoder_t encoder; + session_base_t *session; - msg_t msg; + // Message encoder. + v1_encoder_t encoder; - // Keeps track of message boundaries. - bool more_flag; + msg_t msg; - // PGM socket. - pgm_socket_t pgm_socket; + // Keeps track of message boundaries. + bool more_flag; - // Socket options. - options_t options; + // PGM socket. + pgm_socket_t pgm_socket; - // Poll handle associated with PGM socket. - handle_t handle; - handle_t uplink_handle; - handle_t rdata_notify_handle; - handle_t pending_notify_handle; + // Socket options. + options_t options; - // Output buffer from pgm_socket. - unsigned char *out_buffer; + // Poll handle associated with PGM socket. + handle_t handle; + handle_t uplink_handle; + handle_t rdata_notify_handle; + handle_t pending_notify_handle; - // Output buffer size. - size_t out_buffer_size; + // Output buffer from pgm_socket. + unsigned char *out_buffer; - // Number of bytes in the buffer to be written to the socket. - // If zero, there are no data to be sent. - size_t write_size; + // Output buffer size. + size_t out_buffer_size; - pgm_sender_t (const pgm_sender_t&); - const pgm_sender_t &operator = (const pgm_sender_t&); - }; + // Number of bytes in the buffer to be written to the socket. + // If zero, there are no data to be sent. + size_t write_size; + pgm_sender_t (const pgm_sender_t &); + const pgm_sender_t &operator= (const pgm_sender_t &); +}; } #endif diff --git a/src/pgm_socket.cpp b/src/pgm_socket.cpp index b064c14cdf..3357570874 100644 --- a/src/pgm_socket.cpp +++ b/src/pgm_socket.cpp @@ -68,7 +68,8 @@ zmq::pgm_socket_t::pgm_socket_t (bool receiver_, const options_t &options_) : // link-local;224.250.0.1,224.250.0.2;224.250.0.3:8000 // ;[fe80::1%en0]:7500 int zmq::pgm_socket_t::init_address (const char *network_, - struct pgm_addrinfo_t **res, uint16_t *port_number) + struct pgm_addrinfo_t **res, + uint16_t *port_number) { // Parse port number, start from end for IPv6 const char *port_delim = strrchr (network_, ':'); @@ -79,7 +80,7 @@ int zmq::pgm_socket_t::init_address (const char *network_, *port_number = atoi (port_delim + 1); - char network [256]; + char network[256]; if (port_delim - network_ >= (int) sizeof (network) - 1) { errno = EINVAL; return -1; @@ -93,15 +94,13 @@ int zmq::pgm_socket_t::init_address (const char *network_, memset (&hints, 0, sizeof (hints)); hints.ai_family = AF_UNSPEC; if (!pgm_getaddrinfo (network, NULL, res, &pgm_error)) { - // Invalid parameters don't set pgm_error_t. zmq_assert (pgm_error != NULL); if (pgm_error->domain == PGM_ERROR_DOMAIN_IF && - // NB: cannot catch EAI_BADFLAGS. - ( pgm_error->code != PGM_ERROR_SERVICE && - pgm_error->code != PGM_ERROR_SOCKTNOSUPPORT)) { - + // NB: cannot catch EAI_BADFLAGS. + (pgm_error->code != PGM_ERROR_SERVICE + && pgm_error->code != PGM_ERROR_SOCKTNOSUPPORT)) { // User, host, or network configuration or transient error. pgm_error_free (pgm_error); errno = EINVAL; @@ -132,7 +131,7 @@ int zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_) pgm_error_t *pgm_error = NULL; - if (init_address(network_, &res, &port_number) < 0) { + if (init_address (network_, &res, &port_number) < 0) { goto err_abort; } @@ -144,15 +143,14 @@ int zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_) // Create IP/PGM or UDP/PGM socket. if (udp_encapsulation_) { if (!pgm_socket (&sock, sa_family, SOCK_SEQPACKET, IPPROTO_UDP, - &pgm_error)) { - + &pgm_error)) { // Invalid parameters don't set pgm_error_t. zmq_assert (pgm_error != NULL); - if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET && ( - pgm_error->code != PGM_ERROR_BADF && - pgm_error->code != PGM_ERROR_FAULT && - pgm_error->code != PGM_ERROR_NOPROTOOPT && - pgm_error->code != PGM_ERROR_FAILED)) + if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET + && (pgm_error->code != PGM_ERROR_BADF + && pgm_error->code != PGM_ERROR_FAULT + && pgm_error->code != PGM_ERROR_NOPROTOOPT + && pgm_error->code != PGM_ERROR_FAILED)) // User, host, or network configuration or transient error. goto err_abort; @@ -164,23 +162,21 @@ int zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_) // All options are of data type int const int encapsulation_port = port_number; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_UDP_ENCAP_UCAST_PORT, - &encapsulation_port, sizeof (encapsulation_port))) + &encapsulation_port, sizeof (encapsulation_port))) goto err_abort; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_UDP_ENCAP_MCAST_PORT, - &encapsulation_port, sizeof (encapsulation_port))) + &encapsulation_port, sizeof (encapsulation_port))) goto err_abort; - } - else { + } else { if (!pgm_socket (&sock, sa_family, SOCK_SEQPACKET, IPPROTO_PGM, - &pgm_error)) { - + &pgm_error)) { // Invalid parameters don't set pgm_error_t. zmq_assert (pgm_error != NULL); - if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET && ( - pgm_error->code != PGM_ERROR_BADF && - pgm_error->code != PGM_ERROR_FAULT && - pgm_error->code != PGM_ERROR_NOPROTOOPT && - pgm_error->code != PGM_ERROR_FAILED)) + if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET + && (pgm_error->code != PGM_ERROR_BADF + && pgm_error->code != PGM_ERROR_FAULT + && pgm_error->code != PGM_ERROR_NOPROTOOPT + && pgm_error->code != PGM_ERROR_FAILED)) // User, host, or network configuration or transient error. goto err_abort; @@ -194,119 +190,107 @@ int zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_) const int rcvbuf = (int) options.rcvbuf; if (rcvbuf >= 0) { if (!pgm_setsockopt (sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, - sizeof (rcvbuf))) + sizeof (rcvbuf))) goto err_abort; } const int sndbuf = (int) options.sndbuf; if (sndbuf >= 0) { if (!pgm_setsockopt (sock, SOL_SOCKET, SO_SNDBUF, &sndbuf, - sizeof (sndbuf))) + sizeof (sndbuf))) goto err_abort; } const int max_tpdu = (int) options.multicast_maxtpdu; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MTU, &max_tpdu, - sizeof (max_tpdu))) + sizeof (max_tpdu))) goto err_abort; } if (receiver) { - const int recv_only = 1, - rxw_max_tpdu = (int) options.multicast_maxtpdu, - rxw_sqns = compute_sqns (rxw_max_tpdu), - peer_expiry = pgm_secs (300), - spmr_expiry = pgm_msecs (25), - nak_bo_ivl = pgm_msecs (50), - nak_rpt_ivl = pgm_msecs (200), - nak_rdata_ivl = pgm_msecs (200), - nak_data_retries = 50, - nak_ncf_retries = 50; + const int recv_only = 1, rxw_max_tpdu = (int) options.multicast_maxtpdu, + rxw_sqns = compute_sqns (rxw_max_tpdu), + peer_expiry = pgm_secs (300), spmr_expiry = pgm_msecs (25), + nak_bo_ivl = pgm_msecs (50), nak_rpt_ivl = pgm_msecs (200), + nak_rdata_ivl = pgm_msecs (200), nak_data_retries = 50, + nak_ncf_retries = 50; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_RECV_ONLY, &recv_only, - sizeof (recv_only)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_RXW_SQNS, &rxw_sqns, - sizeof (rxw_sqns)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_PEER_EXPIRY, &peer_expiry, - sizeof (peer_expiry)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_SPMR_EXPIRY, &spmr_expiry, - sizeof (spmr_expiry)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_BO_IVL, &nak_bo_ivl, - sizeof (nak_bo_ivl)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RPT_IVL, &nak_rpt_ivl, - sizeof (nak_rpt_ivl)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RDATA_IVL, - &nak_rdata_ivl, sizeof (nak_rdata_ivl)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_DATA_RETRIES, - &nak_data_retries, sizeof (nak_data_retries)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_NCF_RETRIES, - &nak_ncf_retries, sizeof (nak_ncf_retries))) + sizeof (recv_only)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_RXW_SQNS, &rxw_sqns, + sizeof (rxw_sqns)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_PEER_EXPIRY, + &peer_expiry, sizeof (peer_expiry)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_SPMR_EXPIRY, + &spmr_expiry, sizeof (spmr_expiry)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_BO_IVL, &nak_bo_ivl, + sizeof (nak_bo_ivl)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RPT_IVL, + &nak_rpt_ivl, sizeof (nak_rpt_ivl)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RDATA_IVL, + &nak_rdata_ivl, sizeof (nak_rdata_ivl)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_DATA_RETRIES, + &nak_data_retries, sizeof (nak_data_retries)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_NCF_RETRIES, + &nak_ncf_retries, sizeof (nak_ncf_retries))) goto err_abort; - } - else { - const int send_only = 1, - max_rte = (int) ((options.rate * 1000) / 8), - txw_max_tpdu = (int) options.multicast_maxtpdu, - txw_sqns = compute_sqns (txw_max_tpdu), - ambient_spm = pgm_secs (30), - heartbeat_spm[] = { pgm_msecs (100), - pgm_msecs (100), - pgm_msecs (100), - pgm_msecs (100), - pgm_msecs (1300), - pgm_secs (7), - pgm_secs (16), - pgm_secs (25), - pgm_secs (30) }; - - if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_SEND_ONLY, - &send_only, sizeof (send_only)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_ODATA_MAX_RTE, - &max_rte, sizeof (max_rte)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_TXW_SQNS, - &txw_sqns, sizeof (txw_sqns)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_AMBIENT_SPM, - &ambient_spm, sizeof (ambient_spm)) || - !pgm_setsockopt (sock, IPPROTO_PGM, PGM_HEARTBEAT_SPM, - &heartbeat_spm, sizeof (heartbeat_spm))) + } else { + const int send_only = 1, max_rte = (int) ((options.rate * 1000) / 8), + txw_max_tpdu = (int) options.multicast_maxtpdu, + txw_sqns = compute_sqns (txw_max_tpdu), + ambient_spm = pgm_secs (30), + heartbeat_spm[] = { + pgm_msecs (100), pgm_msecs (100), pgm_msecs (100), + pgm_msecs (100), pgm_msecs (1300), pgm_secs (7), + pgm_secs (16), pgm_secs (25), pgm_secs (30)}; + + if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_SEND_ONLY, &send_only, + sizeof (send_only)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_ODATA_MAX_RTE, &max_rte, + sizeof (max_rte)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_TXW_SQNS, &txw_sqns, + sizeof (txw_sqns)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_AMBIENT_SPM, + &ambient_spm, sizeof (ambient_spm)) + || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_HEARTBEAT_SPM, + &heartbeat_spm, sizeof (heartbeat_spm))) goto err_abort; } // PGM transport GSI. struct pgm_sockaddr_t addr; - memset (&addr, 0, sizeof(addr)); + memset (&addr, 0, sizeof (addr)); addr.sa_port = port_number; addr.sa_addr.sport = DEFAULT_DATA_SOURCE_PORT; // Create random GSI. - uint32_t buf [2]; - buf [0] = generate_random (); - buf [1] = generate_random (); - if (!pgm_gsi_create_from_data (&addr.sa_addr.gsi, (uint8_t*) buf, 8)) + uint32_t buf[2]; + buf[0] = generate_random (); + buf[1] = generate_random (); + if (!pgm_gsi_create_from_data (&addr.sa_addr.gsi, (uint8_t *) buf, 8)) goto err_abort; // Bind a transport to the specified network devices. struct pgm_interface_req_t if_req; - memset (&if_req, 0, sizeof(if_req)); + memset (&if_req, 0, sizeof (if_req)); if_req.ir_interface = res->ai_recv_addrs[0].gsr_interface; - if_req.ir_scope_id = 0; + if_req.ir_scope_id = 0; if (AF_INET6 == sa_family) { struct sockaddr_in6 sa6; memcpy (&sa6, &res->ai_recv_addrs[0].gsr_group, sizeof (sa6)); if_req.ir_scope_id = sa6.sin6_scope_id; } if (!pgm_bind3 (sock, &addr, sizeof (addr), &if_req, sizeof (if_req), - &if_req, sizeof (if_req), &pgm_error)) { - + &if_req, sizeof (if_req), &pgm_error)) { // Invalid parameters don't set pgm_error_t. zmq_assert (pgm_error != NULL); - if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET || - pgm_error->domain == PGM_ERROR_DOMAIN_IF) && ( - pgm_error->code != PGM_ERROR_INVAL && - pgm_error->code != PGM_ERROR_BADF && - pgm_error->code != PGM_ERROR_FAULT)) + if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET + || pgm_error->domain == PGM_ERROR_DOMAIN_IF) + && (pgm_error->code != PGM_ERROR_INVAL + && pgm_error->code != PGM_ERROR_BADF + && pgm_error->code != PGM_ERROR_FAULT)) // User, host, or network configuration or transient error. goto err_abort; @@ -318,11 +302,11 @@ int zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_) // Join IP multicast groups. for (unsigned i = 0; i < res->ai_recv_addrs_len; i++) { if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_JOIN_GROUP, - &res->ai_recv_addrs [i], sizeof (struct group_req))) + &res->ai_recv_addrs[i], sizeof (struct group_req))) goto err_abort; } if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_SEND_GROUP, - &res->ai_send_addrs [0], sizeof (struct group_req))) + &res->ai_send_addrs[0], sizeof (struct group_req))) goto err_abort; pgm_freeaddrinfo (res); @@ -333,30 +317,28 @@ int zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_) // Multicast loopback disabled by default const int multicast_loop = 0; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MULTICAST_LOOP, - &multicast_loop, sizeof (multicast_loop))) + &multicast_loop, sizeof (multicast_loop))) goto err_abort; const int multicast_hops = options.multicast_hops; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MULTICAST_HOPS, - &multicast_hops, sizeof (multicast_hops))) + &multicast_hops, sizeof (multicast_hops))) goto err_abort; // Expedited Forwarding PHB for network elements, no ECN. // Ignore return value due to varied runtime support. const int dscp = 0x2e << 2; if (AF_INET6 != sa_family) - pgm_setsockopt (sock, IPPROTO_PGM, PGM_TOS, - &dscp, sizeof (dscp)); + pgm_setsockopt (sock, IPPROTO_PGM, PGM_TOS, &dscp, sizeof (dscp)); const int nonblocking = 1; - if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_NOBLOCK, - &nonblocking, sizeof (nonblocking))) + if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_NOBLOCK, &nonblocking, + sizeof (nonblocking))) goto err_abort; } // Connect PGM transport to start state machine. if (!pgm_connect (sock, &pgm_error)) { - // Invalid parameters don't set pgm_error_t. zmq_assert (pgm_error != NULL); goto err_abort; @@ -371,7 +353,7 @@ int zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_) pgm_msgv_len++; zmq_assert (pgm_msgv_len); - pgm_msgv = (pgm_msgv_t*) malloc (sizeof (pgm_msgv_t) * pgm_msgv_len); + pgm_msgv = (pgm_msgv_t *) malloc (sizeof (pgm_msgv_t) * pgm_msgv_len); alloc_assert (pgm_msgv); } @@ -405,7 +387,7 @@ zmq::pgm_socket_t::~pgm_socket_t () // Get receiver fds. receive_fd_ is signaled for incoming packets, // waiting_pipe_fd_ is signaled for state driven events and data. void zmq::pgm_socket_t::get_receiver_fds (fd_t *receive_fd_, - fd_t *waiting_pipe_fd_) + fd_t *waiting_pipe_fd_) { socklen_t socklen; bool rc; @@ -414,14 +396,14 @@ void zmq::pgm_socket_t::get_receiver_fds (fd_t *receive_fd_, zmq_assert (waiting_pipe_fd_); socklen = sizeof (*receive_fd_); - rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_RECV_SOCK, receive_fd_, - &socklen); + rc = + pgm_getsockopt (sock, IPPROTO_PGM, PGM_RECV_SOCK, receive_fd_, &socklen); zmq_assert (rc); zmq_assert (socklen == sizeof (*receive_fd_)); socklen = sizeof (*waiting_pipe_fd_); rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_PENDING_SOCK, waiting_pipe_fd_, - &socklen); + &socklen); zmq_assert (rc); zmq_assert (socklen == sizeof (*waiting_pipe_fd_)); } @@ -431,8 +413,10 @@ void zmq::pgm_socket_t::get_receiver_fds (fd_t *receive_fd_, // receive_fd_ is for incoming back-channel protocol packets. // rdata_notify_fd_ is raised for waiting repair transmissions. // pending_notify_fd_ is for state driven events. -void zmq::pgm_socket_t::get_sender_fds (fd_t *send_fd_, fd_t *receive_fd_, - fd_t *rdata_notify_fd_, fd_t *pending_notify_fd_) +void zmq::pgm_socket_t::get_sender_fds (fd_t *send_fd_, + fd_t *receive_fd_, + fd_t *rdata_notify_fd_, + fd_t *pending_notify_fd_) { socklen_t socklen; bool rc; @@ -448,20 +432,20 @@ void zmq::pgm_socket_t::get_sender_fds (fd_t *send_fd_, fd_t *receive_fd_, zmq_assert (socklen == sizeof (*receive_fd_)); socklen = sizeof (*receive_fd_); - rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_RECV_SOCK, receive_fd_, - &socklen); + rc = + pgm_getsockopt (sock, IPPROTO_PGM, PGM_RECV_SOCK, receive_fd_, &socklen); zmq_assert (rc); zmq_assert (socklen == sizeof (*receive_fd_)); socklen = sizeof (*rdata_notify_fd_); rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_REPAIR_SOCK, rdata_notify_fd_, - &socklen); + &socklen); zmq_assert (rc); zmq_assert (socklen == sizeof (*rdata_notify_fd_)); socklen = sizeof (*pending_notify_fd_); rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_PENDING_SOCK, - pending_notify_fd_, &socklen); + pending_notify_fd_, &socklen); zmq_assert (rc); zmq_assert (socklen == sizeof (*pending_notify_fd_)); } @@ -478,10 +462,9 @@ size_t zmq::pgm_socket_t::send (unsigned char *data_, size_t data_len_) if (nbytes > 0) { zmq_assert (status == PGM_IO_STATUS_NORMAL); zmq_assert (nbytes == data_len_); - } - else { - zmq_assert (status == PGM_IO_STATUS_RATE_LIMITED || - status == PGM_IO_STATUS_WOULD_BLOCK); + } else { + zmq_assert (status == PGM_IO_STATUS_RATE_LIMITED + || status == PGM_IO_STATUS_WOULD_BLOCK); if (status == PGM_IO_STATUS_RATE_LIMITED) errno = ENOMEM; @@ -497,15 +480,17 @@ size_t zmq::pgm_socket_t::send (unsigned char *data_, size_t data_len_) long zmq::pgm_socket_t::get_rx_timeout () { - if (last_rx_status != PGM_IO_STATUS_RATE_LIMITED && - last_rx_status != PGM_IO_STATUS_TIMER_PENDING) + if (last_rx_status != PGM_IO_STATUS_RATE_LIMITED + && last_rx_status != PGM_IO_STATUS_TIMER_PENDING) return -1; struct timeval tv; socklen_t optlen = sizeof (tv); const bool rc = pgm_getsockopt (sock, IPPROTO_PGM, - last_rx_status == PGM_IO_STATUS_RATE_LIMITED ? PGM_RATE_REMAIN : - PGM_TIME_REMAIN, &tv, &optlen); + last_rx_status == PGM_IO_STATUS_RATE_LIMITED + ? PGM_RATE_REMAIN + : PGM_TIME_REMAIN, + &tv, &optlen); zmq_assert (rc); const long timeout = (tv.tv_sec * 1000) + (tv.tv_usec / 1000); @@ -520,8 +505,8 @@ long zmq::pgm_socket_t::get_tx_timeout () struct timeval tv; socklen_t optlen = sizeof (tv); - const bool rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_RATE_REMAIN, &tv, - &optlen); + const bool rc = + pgm_getsockopt (sock, IPPROTO_PGM, PGM_RATE_REMAIN, &tv, &optlen); zmq_assert (rc); const long timeout = (tv.tv_sec * 1000) + (tv.tv_usec / 1000); @@ -550,7 +535,6 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) // We just sent all data from pgm_transport_recvmsgv up // and have to return 0 that another engine in this thread is scheduled. if (nbytes_rec == nbytes_processed && nbytes_rec > 0) { - // Reset all the counters. nbytes_rec = 0; nbytes_processed = 0; @@ -562,7 +546,6 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) // If we have are going first time or if we have processed all pgm_msgv_t // structure previously read from the pgm socket. if (nbytes_rec == nbytes_processed) { - // Check program flow. zmq_assert (pgm_msgv_processed == 0); zmq_assert (nbytes_processed == 0); @@ -572,8 +555,8 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) // from the transport. pgm_error_t *pgm_error = NULL; - const int status = pgm_recvmsgv (sock, pgm_msgv, - pgm_msgv_len, MSG_ERRQUEUE, &nbytes_rec, &pgm_error); + const int status = pgm_recvmsgv (sock, pgm_msgv, pgm_msgv_len, + MSG_ERRQUEUE, &nbytes_rec, &pgm_error); // Invalid parameters. zmq_assert (status != PGM_IO_STATUS_ERROR); @@ -583,7 +566,6 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) // In a case when no ODATA/RDATA fired POLLIN event (SPM...) // pgm_recvmsg returns PGM_IO_STATUS_TIMER_PENDING. if (status == PGM_IO_STATUS_TIMER_PENDING) { - zmq_assert (nbytes_rec == 0); // In case if no RDATA/ODATA caused POLLIN 0 is @@ -595,7 +577,6 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) // Send SPMR, NAK, ACK is rate limited. if (status == PGM_IO_STATUS_RATE_LIMITED) { - zmq_assert (nbytes_rec == 0); // In case if no RDATA/ODATA caused POLLIN 0 is returned. @@ -606,7 +587,6 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) // No peers and hence no incoming packets. if (status == PGM_IO_STATUS_WOULD_BLOCK) { - zmq_assert (nbytes_rec == 0); // In case if no RDATA/ODATA caused POLLIN 0 is returned. @@ -617,8 +597,7 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) // Data loss. if (status == PGM_IO_STATUS_RESET) { - - struct pgm_sk_buff_t* skb = pgm_msgv [0].msgv_skb [0]; + struct pgm_sk_buff_t *skb = pgm_msgv[0].msgv_skb[0]; // Save lost data TSI. *tsi_ = &skb->tsi; @@ -631,9 +610,7 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) } zmq_assert (status == PGM_IO_STATUS_NORMAL); - } - else - { + } else { zmq_assert (pgm_msgv_processed <= pgm_msgv_len); } @@ -641,10 +618,9 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) zmq_assert (nbytes_rec > 0); // Only one APDU per pgm_msgv_t structure is allowed. - zmq_assert (pgm_msgv [pgm_msgv_processed].msgv_len == 1); + zmq_assert (pgm_msgv[pgm_msgv_processed].msgv_len == 1); - struct pgm_sk_buff_t* skb = - pgm_msgv [pgm_msgv_processed].msgv_skb [0]; + struct pgm_sk_buff_t *skb = pgm_msgv[pgm_msgv_processed].msgv_skb[0]; // Take pointers from pgm_msgv_t structure. *raw_data_ = skb->data; @@ -656,7 +632,7 @@ ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_) // Move the the next pgm_msgv_t structure. pgm_msgv_processed++; zmq_assert (pgm_msgv_processed <= pgm_msgv_len); - nbytes_processed +=raw_data_len; + nbytes_processed += raw_data_len; return raw_data_len; } @@ -668,23 +644,23 @@ void zmq::pgm_socket_t::process_upstream () size_t dummy_bytes = 0; pgm_error_t *pgm_error = NULL; - const int status = pgm_recvmsgv (sock, &dummy_msg, - 1, MSG_ERRQUEUE, &dummy_bytes, &pgm_error); + const int status = pgm_recvmsgv (sock, &dummy_msg, 1, MSG_ERRQUEUE, + &dummy_bytes, &pgm_error); // Invalid parameters. zmq_assert (status != PGM_IO_STATUS_ERROR); // No data should be returned. - zmq_assert (dummy_bytes == 0 && (status == PGM_IO_STATUS_TIMER_PENDING || - status == PGM_IO_STATUS_RATE_LIMITED || - status == PGM_IO_STATUS_WOULD_BLOCK)); + zmq_assert (dummy_bytes == 0 + && (status == PGM_IO_STATUS_TIMER_PENDING + || status == PGM_IO_STATUS_RATE_LIMITED + || status == PGM_IO_STATUS_WOULD_BLOCK)); last_rx_status = status; if (status == PGM_IO_STATUS_TIMER_PENDING) errno = EBUSY; - else - if (status == PGM_IO_STATUS_RATE_LIMITED) + else if (status == PGM_IO_STATUS_RATE_LIMITED) errno = ENOMEM; else errno = EAGAIN; @@ -709,4 +685,3 @@ int zmq::pgm_socket_t::compute_sqns (int tpdu_) } #endif - diff --git a/src/pgm_socket.hpp b/src/pgm_socket.hpp index 494a96aeeb..00ec4856e4 100644 --- a/src/pgm_socket.hpp +++ b/src/pgm_socket.hpp @@ -47,82 +47,82 @@ namespace zmq { - // Encapsulates PGM socket. - class pgm_socket_t - { - - public: - - // If receiver_ is true PGM transport is not generating SPM packets. - pgm_socket_t (bool receiver_, const options_t &options_); - - // Closes the transport. - ~pgm_socket_t (); +// Encapsulates PGM socket. +class pgm_socket_t +{ + public: + // If receiver_ is true PGM transport is not generating SPM packets. + pgm_socket_t (bool receiver_, const options_t &options_); - // Initialize PGM network structures (GSI, GSRs). - int init (bool udp_encapsulation_, const char *network_); + // Closes the transport. + ~pgm_socket_t (); - // Resolve PGM socket address. - static int init_address(const char *network_, struct pgm_addrinfo_t **addr, uint16_t *port_number); + // Initialize PGM network structures (GSI, GSRs). + int init (bool udp_encapsulation_, const char *network_); - // Get receiver fds and store them into user allocated memory. - void get_receiver_fds (fd_t *receive_fd_, fd_t *waiting_pipe_fd_); + // Resolve PGM socket address. + static int init_address (const char *network_, + struct pgm_addrinfo_t **addr, + uint16_t *port_number); - // Get sender and receiver fds and store it to user allocated - // memory. Receive fd is used to process NAKs from peers. - void get_sender_fds (fd_t *send_fd_, fd_t *receive_fd_, - fd_t *rdata_notify_fd_, fd_t *pending_notify_fd_); + // Get receiver fds and store them into user allocated memory. + void get_receiver_fds (fd_t *receive_fd_, fd_t *waiting_pipe_fd_); - // Send data as one APDU, transmit window owned memory. - size_t send (unsigned char *data_, size_t data_len_); + // Get sender and receiver fds and store it to user allocated + // memory. Receive fd is used to process NAKs from peers. + void get_sender_fds (fd_t *send_fd_, + fd_t *receive_fd_, + fd_t *rdata_notify_fd_, + fd_t *pending_notify_fd_); - // Returns max tsdu size without fragmentation. - size_t get_max_tsdu_size (); + // Send data as one APDU, transmit window owned memory. + size_t send (unsigned char *data_, size_t data_len_); - // Receive data from pgm socket. - ssize_t receive (void **data_, const pgm_tsi_t **tsi_); + // Returns max tsdu size without fragmentation. + size_t get_max_tsdu_size (); - long get_rx_timeout (); - long get_tx_timeout (); + // Receive data from pgm socket. + ssize_t receive (void **data_, const pgm_tsi_t **tsi_); - // POLLIN on sender side should mean NAK or SPMR receiving. - // process_upstream function is used to handle such a situation. - void process_upstream (); + long get_rx_timeout (); + long get_tx_timeout (); - private: + // POLLIN on sender side should mean NAK or SPMR receiving. + // process_upstream function is used to handle such a situation. + void process_upstream (); - // Compute size of the buffer based on rate and recovery interval. - int compute_sqns (int tpdu_); + private: + // Compute size of the buffer based on rate and recovery interval. + int compute_sqns (int tpdu_); - // OpenPGM transport. - pgm_sock_t* sock; + // OpenPGM transport. + pgm_sock_t *sock; - int last_rx_status, last_tx_status; + int last_rx_status, last_tx_status; - // Associated socket options. - options_t options; + // Associated socket options. + options_t options; - // true when pgm_socket should create receiving side. - bool receiver; + // true when pgm_socket should create receiving side. + bool receiver; - // Array of pgm_msgv_t structures to store received data - // from the socket (pgm_transport_recvmsgv). - pgm_msgv_t *pgm_msgv; + // Array of pgm_msgv_t structures to store received data + // from the socket (pgm_transport_recvmsgv). + pgm_msgv_t *pgm_msgv; - // Size of pgm_msgv array. - size_t pgm_msgv_len; + // Size of pgm_msgv array. + size_t pgm_msgv_len; - // How many bytes were read from pgm socket. - size_t nbytes_rec; + // How many bytes were read from pgm socket. + size_t nbytes_rec; - // How many bytes were processed from last pgm socket read. - size_t nbytes_processed; + // How many bytes were processed from last pgm socket read. + size_t nbytes_processed; - // How many messages from pgm_msgv were already sent up. - size_t pgm_msgv_processed; - }; + // How many messages from pgm_msgv were already sent up. + size_t pgm_msgv_processed; +}; } #endif #endif - diff --git a/src/pipe.cpp b/src/pipe.cpp index 956b03a18e..a52ea1c47f 100644 --- a/src/pipe.cpp +++ b/src/pipe.cpp @@ -38,44 +38,50 @@ #include "ypipe.hpp" #include "ypipe_conflate.hpp" -int zmq::pipepair (class object_t *parents_ [2], class pipe_t* pipes_ [2], - int hwms_ [2], bool conflate_ [2]) +int zmq::pipepair (class object_t *parents_[2], + class pipe_t *pipes_[2], + int hwms_[2], + bool conflate_[2]) { // Creates two pipe objects. These objects are connected by two ypipes, // each to pass messages in one direction. - typedef ypipe_t upipe_normal_t; - typedef ypipe_conflate_t upipe_conflate_t; + typedef ypipe_t upipe_normal_t; + typedef ypipe_conflate_t upipe_conflate_t; pipe_t::upipe_t *upipe1; - if(conflate_ [0]) + if (conflate_[0]) upipe1 = new (std::nothrow) upipe_conflate_t (); else upipe1 = new (std::nothrow) upipe_normal_t (); alloc_assert (upipe1); pipe_t::upipe_t *upipe2; - if(conflate_ [1]) + if (conflate_[1]) upipe2 = new (std::nothrow) upipe_conflate_t (); else upipe2 = new (std::nothrow) upipe_normal_t (); alloc_assert (upipe2); - pipes_ [0] = new (std::nothrow) pipe_t (parents_ [0], upipe1, upipe2, - hwms_ [1], hwms_ [0], conflate_ [0]); - alloc_assert (pipes_ [0]); - pipes_ [1] = new (std::nothrow) pipe_t (parents_ [1], upipe2, upipe1, - hwms_ [0], hwms_ [1], conflate_ [1]); - alloc_assert (pipes_ [1]); + pipes_[0] = new (std::nothrow) + pipe_t (parents_[0], upipe1, upipe2, hwms_[1], hwms_[0], conflate_[0]); + alloc_assert (pipes_[0]); + pipes_[1] = new (std::nothrow) + pipe_t (parents_[1], upipe2, upipe1, hwms_[0], hwms_[1], conflate_[1]); + alloc_assert (pipes_[1]); - pipes_ [0]->set_peer (pipes_ [1]); - pipes_ [1]->set_peer (pipes_ [0]); + pipes_[0]->set_peer (pipes_[1]); + pipes_[1]->set_peer (pipes_[0]); return 0; } -zmq::pipe_t::pipe_t (object_t *parent_, upipe_t *inpipe_, upipe_t *outpipe_, - int inhwm_, int outhwm_, bool conflate_) : +zmq::pipe_t::pipe_t (object_t *parent_, + upipe_t *inpipe_, + upipe_t *outpipe_, + int inhwm_, + int outhwm_, + bool conflate_) : object_t (parent_), inpipe (inpipe_), outpipe (outpipe_), @@ -83,8 +89,8 @@ zmq::pipe_t::pipe_t (object_t *parent_, upipe_t *inpipe_, upipe_t *outpipe_, out_active (true), hwm (outhwm_), lwm (compute_lwm (inhwm_)), - inhwmboost(-1), - outhwmboost(-1), + inhwmboost (-1), + outhwmboost (-1), msgs_read (0), msgs_written (0), peers_msgs_read (0), @@ -115,7 +121,8 @@ void zmq::pipe_t::set_event_sink (i_pipe_events *sink_) sink = sink_; } -void zmq::pipe_t::set_server_socket_routing_id (uint32_t server_socket_routing_id_) +void zmq::pipe_t::set_server_socket_routing_id ( + uint32_t server_socket_routing_id_) { server_socket_routing_id = server_socket_routing_id_; } @@ -125,7 +132,8 @@ uint32_t zmq::pipe_t::get_server_socket_routing_id () return server_socket_routing_id; } -void zmq::pipe_t::set_router_socket_routing_id (const blob_t &router_socket_routing_id_) +void zmq::pipe_t::set_router_socket_routing_id ( + const blob_t &router_socket_routing_id_) { router_socket_routing_id.set_deep_copy (router_socket_routing_id_); } @@ -181,7 +189,8 @@ bool zmq::pipe_t::read (msg_t *msg_) // If this is a credential, save a copy and receive next message. if (unlikely (msg_->is_credential ())) { - const unsigned char *data = static_cast (msg_->data ()); + const unsigned char *data = + static_cast (msg_->data ()); credential.set (data, msg_->size ()); const int rc = msg_->close (); zmq_assert (rc == 0); @@ -208,7 +217,7 @@ bool zmq::pipe_t::check_write () if (unlikely (!out_active || state != active)) return false; - bool full = !check_hwm(); + bool full = !check_hwm (); if (unlikely (full)) { out_active = false; @@ -282,16 +291,16 @@ void zmq::pipe_t::process_hiccup (void *pipe_) outpipe->flush (); msg_t msg; while (outpipe->read (&msg)) { - if (!(msg.flags () & msg_t::more)) + if (!(msg.flags () & msg_t::more)) msgs_written--; - int rc = msg.close (); - errno_assert (rc == 0); + int rc = msg.close (); + errno_assert (rc == 0); } - LIBZMQ_DELETE(outpipe); + LIBZMQ_DELETE (outpipe); // Plug in the new outpipe. zmq_assert (pipe_); - outpipe = (upipe_t*) pipe_; + outpipe = (upipe_t *) pipe_; out_active = true; // If appropriate, notify the user about the hiccup. @@ -301,9 +310,8 @@ void zmq::pipe_t::process_hiccup (void *pipe_) void zmq::pipe_t::process_pipe_term () { - zmq_assert (state == active - || state == delimiter_received - || state == term_req_sent1); + zmq_assert (state == active || state == delimiter_received + || state == term_req_sent1); // This is the simple case of peer-induced termination. If there are no // more pending messages to read, or if the pipe was configured to drop @@ -322,8 +330,7 @@ void zmq::pipe_t::process_pipe_term () // Delimiter happened to arrive before the term command. Now we have the // term command as well, so we can move straight to term_ack_sent state. - else - if (state == delimiter_received) { + else if (state == delimiter_received) { state = term_ack_sent; outpipe = NULL; send_pipe_term_ack (peer); @@ -332,8 +339,7 @@ void zmq::pipe_t::process_pipe_term () // This is the case where both ends of the pipe are closed in parallel. // We simply reply to the request by ack and continue waiting for our // own ack. - else - if (state == term_req_sent1) { + else if (state == term_req_sent1) { state = term_req_sent2; outpipe = NULL; send_pipe_term_ack (peer); @@ -353,8 +359,7 @@ void zmq::pipe_t::process_pipe_term_ack () if (state == term_req_sent1) { outpipe = NULL; send_pipe_term_ack (peer); - } - else + } else zmq_assert (state == term_ack_sent || state == term_req_sent2); // We'll deallocate the inbound pipe, the peer will deallocate the outbound @@ -371,7 +376,7 @@ void zmq::pipe_t::process_pipe_term_ack () } } - LIBZMQ_DELETE(inpipe); + LIBZMQ_DELETE (inpipe); // Deallocate the pipe object delete this; @@ -379,7 +384,7 @@ void zmq::pipe_t::process_pipe_term_ack () void zmq::pipe_t::process_pipe_hwm (int inhwm_, int outhwm_) { - set_hwms(inhwm_, outhwm_); + set_hwms (inhwm_, outhwm_); } void zmq::pipe_t::set_nodelay () @@ -435,7 +440,6 @@ void zmq::pipe_t::terminate (bool delay_) out_active = false; if (outpipe) { - // Drop any unfinished outbound messages. rollback (); @@ -478,8 +482,7 @@ int zmq::pipe_t::compute_lwm (int hwm_) void zmq::pipe_t::process_delimiter () { - zmq_assert (state == active - || state == waiting_for_delimiter); + zmq_assert (state == active || state == waiting_for_delimiter); if (state == active) state = delimiter_received; @@ -502,15 +505,15 @@ void zmq::pipe_t::hiccup () // Create new inpipe. if (conflate) - inpipe = new (std::nothrow)ypipe_conflate_t (); + inpipe = new (std::nothrow) ypipe_conflate_t (); else - inpipe = new (std::nothrow)ypipe_t (); + inpipe = new (std::nothrow) ypipe_t (); alloc_assert (inpipe); in_active = true; // Notify the peer about the hiccup. - send_hiccup (peer, (void*) inpipe); + send_hiccup (peer, (void *) inpipe); } void zmq::pipe_t::set_hwms (int inhwm_, int outhwm_) @@ -525,11 +528,11 @@ void zmq::pipe_t::set_hwms (int inhwm_, int outhwm_) if (outhwm_ <= 0 || outhwmboost == 0) out = 0; - lwm = compute_lwm(in); + lwm = compute_lwm (in); hwm = out; } -void zmq::pipe_t::set_hwms_boost(int inhwmboost_, int outhwmboost_) +void zmq::pipe_t::set_hwms_boost (int inhwmboost_, int outhwmboost_) { inhwmboost = inhwmboost_; outhwmboost = outhwmboost_; @@ -538,10 +541,10 @@ void zmq::pipe_t::set_hwms_boost(int inhwmboost_, int outhwmboost_) bool zmq::pipe_t::check_hwm () const { bool full = hwm > 0 && msgs_written - peers_msgs_read >= uint64_t (hwm); - return( !full ); + return (!full); } -void zmq::pipe_t::send_hwms_to_peer(int inhwm_, int outhwm_) +void zmq::pipe_t::send_hwms_to_peer (int inhwm_, int outhwm_) { - send_pipe_hwm(peer, inhwm_, outhwm_); + send_pipe_hwm (peer, inhwm_, outhwm_); } diff --git a/src/pipe.hpp b/src/pipe.hpp index c07c9849c9..63f1b7db4b 100644 --- a/src/pipe.hpp +++ b/src/pipe.hpp @@ -40,214 +40,219 @@ namespace zmq { +class object_t; +class pipe_t; + +// Create a pipepair for bi-directional transfer of messages. +// First HWM is for messages passed from first pipe to the second pipe. +// Second HWM is for messages passed from second pipe to the first pipe. +// Delay specifies how the pipe behaves when the peer terminates. If true +// pipe receives all the pending messages before terminating, otherwise it +// terminates straight away. +// If conflate is true, only the most recently arrived message could be +// read (older messages are discarded) +int pipepair (zmq::object_t *parents_[2], + zmq::pipe_t *pipes_[2], + int hwms_[2], + bool conflate_[2]); + +struct i_pipe_events +{ + virtual ~i_pipe_events () {} + + virtual void read_activated (zmq::pipe_t *pipe_) = 0; + virtual void write_activated (zmq::pipe_t *pipe_) = 0; + virtual void hiccuped (zmq::pipe_t *pipe_) = 0; + virtual void pipe_terminated (zmq::pipe_t *pipe_) = 0; +}; + +// Note that pipe can be stored in three different arrays. +// The array of inbound pipes (1), the array of outbound pipes (2) and +// the generic array of pipes to be deallocated (3). + +class pipe_t : public object_t, + public array_item_t<1>, + public array_item_t<2>, + public array_item_t<3> +{ + // This allows pipepair to create pipe objects. + friend int pipepair (zmq::object_t *parents_[2], + zmq::pipe_t *pipes_[2], + int hwms_[2], + bool conflate_[2]); + + public: + // Specifies the object to send events to. + void set_event_sink (i_pipe_events *sink_); - class object_t; - class pipe_t; - - // Create a pipepair for bi-directional transfer of messages. - // First HWM is for messages passed from first pipe to the second pipe. - // Second HWM is for messages passed from second pipe to the first pipe. - // Delay specifies how the pipe behaves when the peer terminates. If true - // pipe receives all the pending messages before terminating, otherwise it - // terminates straight away. - // If conflate is true, only the most recently arrived message could be - // read (older messages are discarded) - int pipepair (zmq::object_t *parents_ [2], zmq::pipe_t* pipes_ [2], - int hwms_ [2], bool conflate_ [2]); - - struct i_pipe_events - { - virtual ~i_pipe_events () {} - - virtual void read_activated (zmq::pipe_t *pipe_) = 0; - virtual void write_activated (zmq::pipe_t *pipe_) = 0; - virtual void hiccuped (zmq::pipe_t *pipe_) = 0; - virtual void pipe_terminated (zmq::pipe_t *pipe_) = 0; - }; - - // Note that pipe can be stored in three different arrays. - // The array of inbound pipes (1), the array of outbound pipes (2) and - // the generic array of pipes to be deallocated (3). - - class pipe_t : - public object_t, - public array_item_t <1>, - public array_item_t <2>, - public array_item_t <3> - { - // This allows pipepair to create pipe objects. - friend int pipepair (zmq::object_t *parents_ [2], zmq::pipe_t* pipes_ [2], - int hwms_ [2], bool conflate_ [2]); - - public: - - // Specifies the object to send events to. - void set_event_sink (i_pipe_events *sink_); - - // Pipe endpoint can store an routing ID to be used by its clients. - void set_server_socket_routing_id (uint32_t routing_id_); - uint32_t get_server_socket_routing_id (); - - // Pipe endpoint can store an opaque ID to be used by its clients. - void set_router_socket_routing_id (const blob_t &identity_); - const blob_t &get_routing_id (); - - const blob_t &get_credential () const; - - // Returns true if there is at least one message to read in the pipe. - bool check_read (); - - // Reads a message to the underlying pipe. - bool read (msg_t *msg_); - - // Checks whether messages can be written to the pipe. If the pipe is - // closed or if writing the message would cause high watermark the - // function returns false. - bool check_write (); - - // Writes a message to the underlying pipe. Returns false if the - // message does not pass check_write. If false, the message object - // retains ownership of its message buffer. - bool write (msg_t *msg_); - - // Remove unfinished parts of the outbound message from the pipe. - void rollback (); - - // Flush the messages downstream. - void flush (); - - // Temporarily disconnects the inbound message stream and drops - // all the messages on the fly. Causes 'hiccuped' event to be generated - // in the peer. - void hiccup (); - - // Ensure the pipe won't block on receiving pipe_term. - void set_nodelay (); - - // Ask pipe to terminate. The termination will happen asynchronously - // and user will be notified about actual deallocation by 'terminated' - // event. If delay is true, the pending messages will be processed - // before actual shutdown. - void terminate (bool delay_); - - // Set the high water marks. - void set_hwms (int inhwm_, int outhwm_); - - // Set the boost to high water marks, used by inproc sockets so total hwm are sum of connect and bind sockets watermarks - void set_hwms_boost(int inhwmboost_, int outhwmboost_); - - // send command to peer for notify the change of hwm - void send_hwms_to_peer(int inhwm_, int outhwm_); - - // Returns true if HWM is not reached - bool check_hwm () const; - private: - - // Type of the underlying lock-free pipe. - typedef ypipe_base_t upipe_t; + // Pipe endpoint can store an routing ID to be used by its clients. + void set_server_socket_routing_id (uint32_t routing_id_); + uint32_t get_server_socket_routing_id (); - // Command handlers. - void process_activate_read (); - void process_activate_write (uint64_t msgs_read_); - void process_hiccup (void *pipe_); - void process_pipe_term (); - void process_pipe_term_ack (); - void process_pipe_hwm (int inhwm_, int outhwm_); + // Pipe endpoint can store an opaque ID to be used by its clients. + void set_router_socket_routing_id (const blob_t &identity_); + const blob_t &get_routing_id (); - // Handler for delimiter read from the pipe. - void process_delimiter (); + const blob_t &get_credential () const; + + // Returns true if there is at least one message to read in the pipe. + bool check_read (); - // Constructor is private. Pipe can only be created using - // pipepair function. - pipe_t (object_t *parent_, upipe_t *inpipe_, upipe_t *outpipe_, - int inhwm_, int outhwm_, bool conflate_); + // Reads a message to the underlying pipe. + bool read (msg_t *msg_); - // Pipepair uses this function to let us know about - // the peer pipe object. - void set_peer (pipe_t *pipe_); + // Checks whether messages can be written to the pipe. If the pipe is + // closed or if writing the message would cause high watermark the + // function returns false. + bool check_write (); - // Destructor is private. Pipe objects destroy themselves. - ~pipe_t (); + // Writes a message to the underlying pipe. Returns false if the + // message does not pass check_write. If false, the message object + // retains ownership of its message buffer. + bool write (msg_t *msg_); + + // Remove unfinished parts of the outbound message from the pipe. + void rollback (); + + // Flush the messages downstream. + void flush (); + + // Temporarily disconnects the inbound message stream and drops + // all the messages on the fly. Causes 'hiccuped' event to be generated + // in the peer. + void hiccup (); + + // Ensure the pipe won't block on receiving pipe_term. + void set_nodelay (); + + // Ask pipe to terminate. The termination will happen asynchronously + // and user will be notified about actual deallocation by 'terminated' + // event. If delay is true, the pending messages will be processed + // before actual shutdown. + void terminate (bool delay_); + + // Set the high water marks. + void set_hwms (int inhwm_, int outhwm_); + + // Set the boost to high water marks, used by inproc sockets so total hwm are sum of connect and bind sockets watermarks + void set_hwms_boost (int inhwmboost_, int outhwmboost_); + + // send command to peer for notify the change of hwm + void send_hwms_to_peer (int inhwm_, int outhwm_); + + // Returns true if HWM is not reached + bool check_hwm () const; + + private: + // Type of the underlying lock-free pipe. + typedef ypipe_base_t upipe_t; + + // Command handlers. + void process_activate_read (); + void process_activate_write (uint64_t msgs_read_); + void process_hiccup (void *pipe_); + void process_pipe_term (); + void process_pipe_term_ack (); + void process_pipe_hwm (int inhwm_, int outhwm_); + + // Handler for delimiter read from the pipe. + void process_delimiter (); + + // Constructor is private. Pipe can only be created using + // pipepair function. + pipe_t (object_t *parent_, + upipe_t *inpipe_, + upipe_t *outpipe_, + int inhwm_, + int outhwm_, + bool conflate_); + + // Pipepair uses this function to let us know about + // the peer pipe object. + void set_peer (pipe_t *pipe_); + + // Destructor is private. Pipe objects destroy themselves. + ~pipe_t (); + + // Underlying pipes for both directions. + upipe_t *inpipe; + upipe_t *outpipe; + + // Can the pipe be read from / written to? + bool in_active; + bool out_active; + + // High watermark for the outbound pipe. + int hwm; + + // Low watermark for the inbound pipe. + int lwm; + + // boosts for high and low watermarks, used with inproc sockets so hwm are sum of send and recv hmws on each side of pipe + int inhwmboost; + int outhwmboost; + + // Number of messages read and written so far. + uint64_t msgs_read; + uint64_t msgs_written; + + // Last received peer's msgs_read. The actual number in the peer + // can be higher at the moment. + uint64_t peers_msgs_read; + + // The pipe object on the other side of the pipepair. + pipe_t *peer; + + // Sink to send events to. + i_pipe_events *sink; + + // States of the pipe endpoint: + // active: common state before any termination begins, + // delimiter_received: delimiter was read from pipe before + // term command was received, + // waiting_for_delimiter: term command was already received + // from the peer but there are still pending messages to read, + // term_ack_sent: all pending messages were already read and + // all we are waiting for is ack from the peer, + // term_req_sent1: 'terminate' was explicitly called by the user, + // term_req_sent2: user called 'terminate' and then we've got + // term command from the peer as well. + enum + { + active, + delimiter_received, + waiting_for_delimiter, + term_ack_sent, + term_req_sent1, + term_req_sent2 + } state; - // Underlying pipes for both directions. - upipe_t *inpipe; - upipe_t *outpipe; + // If true, we receive all the pending inbound messages before + // terminating. If false, we terminate immediately when the peer + // asks us to. + bool delay; - // Can the pipe be read from / written to? - bool in_active; - bool out_active; + // Routing id of the writer. Used uniquely by the reader side. + blob_t router_socket_routing_id; - // High watermark for the outbound pipe. - int hwm; + // Routing id of the writer. Used uniquely by the reader side. + int server_socket_routing_id; - // Low watermark for the inbound pipe. - int lwm; + // Pipe's credential. + blob_t credential; - // boosts for high and low watermarks, used with inproc sockets so hwm are sum of send and recv hmws on each side of pipe - int inhwmboost; - int outhwmboost; + // Returns true if the message is delimiter; false otherwise. + static bool is_delimiter (const msg_t &msg_); - // Number of messages read and written so far. - uint64_t msgs_read; - uint64_t msgs_written; + // Computes appropriate low watermark from the given high watermark. + static int compute_lwm (int hwm_); - // Last received peer's msgs_read. The actual number in the peer - // can be higher at the moment. - uint64_t peers_msgs_read; - - // The pipe object on the other side of the pipepair. - pipe_t *peer; - - // Sink to send events to. - i_pipe_events *sink; - - // States of the pipe endpoint: - // active: common state before any termination begins, - // delimiter_received: delimiter was read from pipe before - // term command was received, - // waiting_for_delimiter: term command was already received - // from the peer but there are still pending messages to read, - // term_ack_sent: all pending messages were already read and - // all we are waiting for is ack from the peer, - // term_req_sent1: 'terminate' was explicitly called by the user, - // term_req_sent2: user called 'terminate' and then we've got - // term command from the peer as well. - enum { - active, - delimiter_received, - waiting_for_delimiter, - term_ack_sent, - term_req_sent1, - term_req_sent2 - } state; - - // If true, we receive all the pending inbound messages before - // terminating. If false, we terminate immediately when the peer - // asks us to. - bool delay; - - // Routing id of the writer. Used uniquely by the reader side. - blob_t router_socket_routing_id; - - // Routing id of the writer. Used uniquely by the reader side. - int server_socket_routing_id; - - // Pipe's credential. - blob_t credential; - - // Returns true if the message is delimiter; false otherwise. - static bool is_delimiter (const msg_t &msg_); - - // Computes appropriate low watermark from the given high watermark. - static int compute_lwm (int hwm_); - - const bool conflate; - - // Disable copying. - pipe_t (const pipe_t&); - const pipe_t &operator = (const pipe_t&); - }; + const bool conflate; + // Disable copying. + pipe_t (const pipe_t &); + const pipe_t &operator= (const pipe_t &); +}; } #endif diff --git a/src/plain_client.cpp b/src/plain_client.cpp index 4aa023c859..6ff50b806a 100644 --- a/src/plain_client.cpp +++ b/src/plain_client.cpp @@ -73,17 +73,15 @@ int zmq::plain_client_t::next_handshake_command (msg_t *msg_) int zmq::plain_client_t::process_handshake_command (msg_t *msg_) { const unsigned char *cmd_data = - static_cast (msg_->data ()); + static_cast (msg_->data ()); const size_t data_size = msg_->size (); int rc = 0; if (data_size >= 8 && !memcmp (cmd_data, "\7WELCOME", 8)) rc = process_welcome (cmd_data, data_size); - else - if (data_size >= 6 && !memcmp (cmd_data, "\5READY", 6)) + else if (data_size >= 6 && !memcmp (cmd_data, "\5READY", 6)) rc = process_ready (cmd_data, data_size); - else - if (data_size >= 6 && !memcmp (cmd_data, "\5ERROR", 6)) + else if (data_size >= 6 && !memcmp (cmd_data, "\5ERROR", 6)) rc = process_error (cmd_data, data_size); else { session->get_socket ()->event_handshake_failed_protocol ( @@ -106,8 +104,7 @@ zmq::mechanism_t::status_t zmq::plain_client_t::status () const { if (state == ready) return mechanism_t::ready; - else - if (state == error_command_received) + else if (state == error_command_received) return mechanism_t::error; else return mechanism_t::handshaking; @@ -121,28 +118,28 @@ int zmq::plain_client_t::produce_hello (msg_t *msg_) const const std::string password = options.plain_password; zmq_assert (password.length () < 256); - const size_t command_size = 6 + 1 + username.length () - + 1 + password.length (); + const size_t command_size = + 6 + 1 + username.length () + 1 + password.length (); const int rc = msg_->init_size (command_size); errno_assert (rc == 0); - unsigned char *ptr = static_cast (msg_->data ()); + unsigned char *ptr = static_cast (msg_->data ()); memcpy (ptr, "\x05HELLO", 6); ptr += 6; - *ptr++ = static_cast (username.length ()); + *ptr++ = static_cast (username.length ()); memcpy (ptr, username.c_str (), username.length ()); ptr += username.length (); - *ptr++ = static_cast (password.length ()); + *ptr++ = static_cast (password.length ()); memcpy (ptr, password.c_str (), password.length ()); return 0; } -int zmq::plain_client_t::process_welcome ( - const unsigned char *cmd_data, size_t data_size) +int zmq::plain_client_t::process_welcome (const unsigned char *cmd_data, + size_t data_size) { LIBZMQ_UNUSED (cmd_data); @@ -170,8 +167,8 @@ int zmq::plain_client_t::produce_initiate (msg_t *msg_) const return 0; } -int zmq::plain_client_t::process_ready ( - const unsigned char *cmd_data, size_t data_size) +int zmq::plain_client_t::process_ready (const unsigned char *cmd_data, + size_t data_size) { if (state != waiting_for_ready) { session->get_socket ()->event_handshake_failed_protocol ( @@ -189,8 +186,8 @@ int zmq::plain_client_t::process_ready ( return rc; } -int zmq::plain_client_t::process_error ( - const unsigned char *cmd_data, size_t data_size) +int zmq::plain_client_t::process_error (const unsigned char *cmd_data, + size_t data_size) { if (state != waiting_for_welcome && state != waiting_for_ready) { session->get_socket ()->event_handshake_failed_protocol ( @@ -205,7 +202,7 @@ int zmq::plain_client_t::process_error ( errno = EPROTO; return -1; } - const size_t error_reason_len = static_cast (cmd_data [6]); + const size_t error_reason_len = static_cast (cmd_data[6]); if (error_reason_len > data_size - 7) { session->get_socket ()->event_handshake_failed_protocol ( session->get_endpoint (), diff --git a/src/plain_client.hpp b/src/plain_client.hpp index 76789e09f9..58346e3bf6 100644 --- a/src/plain_client.hpp +++ b/src/plain_client.hpp @@ -35,45 +35,39 @@ namespace zmq { +class msg_t; - class msg_t; - - class plain_client_t : public mechanism_base_t - { - public: - plain_client_t (session_base_t *const session_, - const options_t &options_); - virtual ~plain_client_t (); - - // mechanism implementation - virtual int next_handshake_command (msg_t *msg_); - virtual int process_handshake_command (msg_t *msg_); - virtual status_t status () const; - - private: +class plain_client_t : public mechanism_base_t +{ + public: + plain_client_t (session_base_t *const session_, const options_t &options_); + virtual ~plain_client_t (); - enum state_t { - sending_hello, - waiting_for_welcome, - sending_initiate, - waiting_for_ready, - error_command_received, - ready - }; + // mechanism implementation + virtual int next_handshake_command (msg_t *msg_); + virtual int process_handshake_command (msg_t *msg_); + virtual status_t status () const; - state_t state; + private: + enum state_t + { + sending_hello, + waiting_for_welcome, + sending_initiate, + waiting_for_ready, + error_command_received, + ready + }; - int produce_hello (msg_t *msg_) const; - int produce_initiate (msg_t *msg_) const; + state_t state; - int process_welcome ( - const unsigned char *cmd_data, size_t data_size); - int process_ready ( - const unsigned char *cmd_data, size_t data_size); - int process_error ( - const unsigned char *cmd_data, size_t data_size); - }; + int produce_hello (msg_t *msg_) const; + int produce_initiate (msg_t *msg_) const; + int process_welcome (const unsigned char *cmd_data, size_t data_size); + int process_ready (const unsigned char *cmd_data, size_t data_size); + int process_error (const unsigned char *cmd_data, size_t data_size); +}; } #endif diff --git a/src/plain_server.cpp b/src/plain_server.cpp index e993507d7e..c47cfe0e87 100644 --- a/src/plain_server.cpp +++ b/src/plain_server.cpp @@ -50,7 +50,7 @@ zmq::plain_server_t::plain_server_t (session_base_t *session_, // Given this is a backward-incompatible change, it's behind a socket // option disabled by default. if (options.zap_enforce_domain) - zmq_assert (zap_required()); + zmq_assert (zap_required ()); } zmq::plain_server_t::~plain_server_t () @@ -116,9 +116,9 @@ int zmq::plain_server_t::process_hello (msg_t *msg_) { int rc = check_basic_command_structure (msg_); if (rc == -1) - return -1; + return -1; - const unsigned char *ptr = static_cast (msg_->data ()); + const unsigned char *ptr = static_cast (msg_->data ()); size_t bytes_left = msg_->size (); if (bytes_left < 6 || memcmp (ptr, "\x05HELLO", 6)) { @@ -133,7 +133,8 @@ int zmq::plain_server_t::process_hello (msg_t *msg_) if (bytes_left < 1) { // PLAIN I: invalid PLAIN client, did not send username session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); + session->get_endpoint (), + ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } @@ -143,7 +144,8 @@ int zmq::plain_server_t::process_hello (msg_t *msg_) if (bytes_left < username_length) { // PLAIN I: invalid PLAIN client, sent malformed username session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); + session->get_endpoint (), + ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } @@ -153,7 +155,8 @@ int zmq::plain_server_t::process_hello (msg_t *msg_) if (bytes_left < 1) { // PLAIN I: invalid PLAIN client, did not send password session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); + session->get_endpoint (), + ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } @@ -163,7 +166,8 @@ int zmq::plain_server_t::process_hello (msg_t *msg_) if (bytes_left < password_length) { // PLAIN I: invalid PLAIN client, sent malformed password session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); + session->get_endpoint (), + ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } @@ -174,7 +178,8 @@ int zmq::plain_server_t::process_hello (msg_t *msg_) if (bytes_left > 0) { // PLAIN I: invalid PLAIN client, sent extraneous data session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); + session->get_endpoint (), + ZMQ_PROTOCOL_ERROR_ZMTP_MALFORMED_COMMAND_HELLO); errno = EPROTO; return -1; } @@ -190,9 +195,9 @@ int zmq::plain_server_t::process_hello (msg_t *msg_) send_zap_request (username, password); state = waiting_for_zap_reply; - // TODO actually, it is quite unlikely that we can read the ZAP + // TODO actually, it is quite unlikely that we can read the ZAP // reply already, but removing this has some strange side-effect - // (probably because the pipe's in_active flag is true until a read + // (probably because the pipe's in_active flag is true until a read // is attempted) return receive_and_process_zap_reply () == -1 ? -1 : 0; } @@ -207,7 +212,7 @@ int zmq::plain_server_t::produce_welcome (msg_t *msg_) const int zmq::plain_server_t::process_initiate (msg_t *msg_) { - const unsigned char *ptr = static_cast (msg_->data ()); + const unsigned char *ptr = static_cast (msg_->data ()); const size_t bytes_left = msg_->size (); if (bytes_left < 9 || memcmp (ptr, "\x08INITIATE", 9)) { @@ -234,9 +239,9 @@ int zmq::plain_server_t::produce_error (msg_t *msg_) const zmq_assert (status_code.length () == 3); const int rc = msg_->init_size (6 + 1 + status_code.length ()); zmq_assert (rc == 0); - char *msg_data = static_cast (msg_->data ()); + char *msg_data = static_cast (msg_->data ()); memcpy (msg_data, "\5ERROR", 6); - msg_data [6] = (char) status_code.length (); + msg_data[6] = (char) status_code.length (); memcpy (msg_data + 7, status_code.c_str (), status_code.length ()); return 0; } diff --git a/src/plain_server.hpp b/src/plain_server.hpp index 7033944f1a..c9352ab6c1 100644 --- a/src/plain_server.hpp +++ b/src/plain_server.hpp @@ -36,36 +36,32 @@ namespace zmq { +class msg_t; +class session_base_t; - class msg_t; - class session_base_t; - - class plain_server_t : public zap_client_common_handshake_t - { - public: - - plain_server_t (session_base_t *session_, - const std::string &peer_address_, - const options_t &options_); - virtual ~plain_server_t (); - - // mechanism implementation - virtual int next_handshake_command (msg_t *msg_); - virtual int process_handshake_command (msg_t *msg_); - - private: - - int produce_welcome (msg_t *msg_) const; - int produce_ready (msg_t *msg_) const; - int produce_error (msg_t *msg_) const; - - int process_hello (msg_t *msg_); - int process_initiate (msg_t *msg_); - - void send_zap_request (const std::string &username, - const std::string &password); - }; - +class plain_server_t : public zap_client_common_handshake_t +{ + public: + plain_server_t (session_base_t *session_, + const std::string &peer_address_, + const options_t &options_); + virtual ~plain_server_t (); + + // mechanism implementation + virtual int next_handshake_command (msg_t *msg_); + virtual int process_handshake_command (msg_t *msg_); + + private: + int produce_welcome (msg_t *msg_) const; + int produce_ready (msg_t *msg_) const; + int produce_error (msg_t *msg_) const; + + int process_hello (msg_t *msg_); + int process_initiate (msg_t *msg_); + + void send_zap_request (const std::string &username, + const std::string &password); +}; } #endif diff --git a/src/poll.cpp b/src/poll.cpp index 2ba5d84e3b..608ddec55a 100644 --- a/src/poll.cpp +++ b/src/poll.cpp @@ -44,7 +44,7 @@ #include "i_poll_events.hpp" zmq::poll_t::poll_t (const zmq::ctx_t &ctx_) : - ctx(ctx_), + ctx (ctx_), retired (false), stopping (false) { @@ -64,17 +64,17 @@ zmq::poll_t::handle_t zmq::poll_t::add_fd (fd_t fd_, i_poll_events *events_) if (sz <= (fd_table_t::size_type) fd_) { fd_table.resize (fd_ + 1); while (sz != (fd_table_t::size_type) (fd_ + 1)) { - fd_table [sz].index = retired_fd; + fd_table[sz].index = retired_fd; ++sz; } } pollfd pfd = {fd_, 0, 0}; pollset.push_back (pfd); - zmq_assert (fd_table [fd_].index == retired_fd); + zmq_assert (fd_table[fd_].index == retired_fd); - fd_table [fd_].index = pollset.size() - 1; - fd_table [fd_].events = events_; + fd_table[fd_].index = pollset.size () - 1; + fd_table[fd_].events = events_; // Increase the load metric of the thread. adjust_load (1); @@ -84,12 +84,12 @@ zmq::poll_t::handle_t zmq::poll_t::add_fd (fd_t fd_, i_poll_events *events_) void zmq::poll_t::rm_fd (handle_t handle_) { - fd_t index = fd_table [handle_].index; + fd_t index = fd_table[handle_].index; zmq_assert (index != retired_fd); // Mark the fd as unused. - pollset [index].fd = retired_fd; - fd_table [handle_].index = retired_fd; + pollset[index].fd = retired_fd; + fd_table[handle_].index = retired_fd; retired = true; // Decrease the load metric of the thread. @@ -98,26 +98,26 @@ void zmq::poll_t::rm_fd (handle_t handle_) void zmq::poll_t::set_pollin (handle_t handle_) { - fd_t index = fd_table [handle_].index; - pollset [index].events |= POLLIN; + fd_t index = fd_table[handle_].index; + pollset[index].events |= POLLIN; } void zmq::poll_t::reset_pollin (handle_t handle_) { - fd_t index = fd_table [handle_].index; - pollset [index].events &= ~((short) POLLIN); + fd_t index = fd_table[handle_].index; + pollset[index].events &= ~((short) POLLIN); } void zmq::poll_t::set_pollout (handle_t handle_) { - fd_t index = fd_table [handle_].index; - pollset [index].events |= POLLOUT; + fd_t index = fd_table[handle_].index; + pollset[index].events |= POLLOUT; } void zmq::poll_t::reset_pollout (handle_t handle_) { - fd_t index = fd_table [handle_].index; - pollset [index].events &= ~((short) POLLOUT); + fd_t index = fd_table[handle_].index; + pollset[index].events &= ~((short) POLLOUT); } void zmq::poll_t::start () @@ -138,12 +138,11 @@ int zmq::poll_t::max_fds () void zmq::poll_t::loop () { while (!stopping) { - // Execute any due timers. int timeout = (int) execute_timers (); // Wait for events. - int rc = poll (&pollset [0], pollset.size (), timeout ? timeout : -1); + int rc = poll (&pollset[0], pollset.size (), timeout ? timeout : -1); if (rc == -1) { errno_assert (errno == EINTR); continue; @@ -155,31 +154,30 @@ void zmq::poll_t::loop () continue; for (pollset_t::size_type i = 0; i != pollset.size (); i++) { - - zmq_assert (!(pollset [i].revents & POLLNVAL)); - if (pollset [i].fd == retired_fd) - continue; - if (pollset [i].revents & (POLLERR | POLLHUP)) - fd_table [pollset [i].fd].events->in_event (); - if (pollset [i].fd == retired_fd) - continue; - if (pollset [i].revents & POLLOUT) - fd_table [pollset [i].fd].events->out_event (); - if (pollset [i].fd == retired_fd) - continue; - if (pollset [i].revents & POLLIN) - fd_table [pollset [i].fd].events->in_event (); + zmq_assert (!(pollset[i].revents & POLLNVAL)); + if (pollset[i].fd == retired_fd) + continue; + if (pollset[i].revents & (POLLERR | POLLHUP)) + fd_table[pollset[i].fd].events->in_event (); + if (pollset[i].fd == retired_fd) + continue; + if (pollset[i].revents & POLLOUT) + fd_table[pollset[i].fd].events->out_event (); + if (pollset[i].fd == retired_fd) + continue; + if (pollset[i].revents & POLLIN) + fd_table[pollset[i].fd].events->in_event (); } // Clean up the pollset and update the fd_table accordingly. if (retired) { pollset_t::size_type i = 0; while (i < pollset.size ()) { - if (pollset [i].fd == retired_fd) + if (pollset[i].fd == retired_fd) pollset.erase (pollset.begin () + i); else { - fd_table [pollset [i].fd].index = i; - i ++; + fd_table[pollset[i].fd].index = i; + i++; } } retired = false; @@ -189,7 +187,7 @@ void zmq::poll_t::loop () void zmq::poll_t::worker_routine (void *arg_) { - ((poll_t*) arg_)->loop (); + ((poll_t *) arg_)->loop (); } #endif diff --git a/src/poll.hpp b/src/poll.hpp index 8481805509..08c6b5445c 100644 --- a/src/poll.hpp +++ b/src/poll.hpp @@ -47,73 +47,69 @@ namespace zmq { +struct i_poll_events; - struct i_poll_events; +// Implements socket polling mechanism using the POSIX.1-2001 +// poll() system call. - // Implements socket polling mechanism using the POSIX.1-2001 - // poll() system call. - - class poll_t : public poller_base_t - { - public: - - typedef fd_t handle_t; - - poll_t (const ctx_t &ctx_); - ~poll_t (); - - // "poller" concept. - handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); - void rm_fd (handle_t handle_); - void set_pollin (handle_t handle_); - void reset_pollin (handle_t handle_); - void set_pollout (handle_t handle_); - void reset_pollout (handle_t handle_); - void start (); - void stop (); +class poll_t : public poller_base_t +{ + public: + typedef fd_t handle_t; - static int max_fds (); + poll_t (const ctx_t &ctx_); + ~poll_t (); - private: + // "poller" concept. + handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); + void rm_fd (handle_t handle_); + void set_pollin (handle_t handle_); + void reset_pollin (handle_t handle_); + void set_pollout (handle_t handle_); + void reset_pollout (handle_t handle_); + void start (); + void stop (); - // Main worker thread routine. - static void worker_routine (void *arg_); + static int max_fds (); - // Main event loop. - void loop (); + private: + // Main worker thread routine. + static void worker_routine (void *arg_); - // Reference to ZMQ context. - const ctx_t &ctx; + // Main event loop. + void loop (); - struct fd_entry_t - { - fd_t index; - zmq::i_poll_events *events; - }; + // Reference to ZMQ context. + const ctx_t &ctx; - // This table stores data for registered descriptors. - typedef std::vector fd_table_t; - fd_table_t fd_table; + struct fd_entry_t + { + fd_t index; + zmq::i_poll_events *events; + }; - // Pollset to pass to the poll function. - typedef std::vector pollset_t; - pollset_t pollset; + // This table stores data for registered descriptors. + typedef std::vector fd_table_t; + fd_table_t fd_table; - // If true, there's at least one retired event source. - bool retired; + // Pollset to pass to the poll function. + typedef std::vector pollset_t; + pollset_t pollset; - // If true, thread is in the process of shutting down. - bool stopping; + // If true, there's at least one retired event source. + bool retired; - // Handle of the physical thread doing the I/O work. - thread_t worker; + // If true, thread is in the process of shutting down. + bool stopping; - poll_t (const poll_t&); - const poll_t &operator = (const poll_t&); - }; + // Handle of the physical thread doing the I/O work. + thread_t worker; - typedef poll_t poller_t; + poll_t (const poll_t &); + const poll_t &operator= (const poll_t &); +}; +typedef poll_t poller_t; } #endif diff --git a/src/poller.hpp b/src/poller.hpp index 42c6db411d..5b0d19df4a 100644 --- a/src/poller.hpp +++ b/src/poller.hpp @@ -30,29 +30,29 @@ #ifndef __ZMQ_POLLER_HPP_INCLUDED__ #define __ZMQ_POLLER_HPP_INCLUDED__ -#if defined ZMQ_USE_KQUEUE + defined ZMQ_USE_EPOLL \ - + defined ZMQ_USE_DEVPOLL + defined ZMQ_USE_POLLSET \ - + defined ZMQ_USE_POLL + defined ZMQ_USE_SELECT > 1 +#if defined ZMQ_USE_KQUEUE + defined ZMQ_USE_EPOLL + defined ZMQ_USE_DEVPOLL \ + + defined ZMQ_USE_POLLSET + defined ZMQ_USE_POLL + defined ZMQ_USE_SELECT \ + > 1 #error More than one of the ZMQ_USE_* macros defined #endif #if defined ZMQ_USE_KQUEUE -# include "kqueue.hpp" +#include "kqueue.hpp" #elif defined ZMQ_USE_EPOLL -# include "epoll.hpp" +#include "epoll.hpp" #elif defined ZMQ_USE_DEVPOLL -# include "devpoll.hpp" +#include "devpoll.hpp" #elif defined ZMQ_USE_POLLSET -# include "pollset.hpp" +#include "pollset.hpp" #elif defined ZMQ_USE_POLL -# include "poll.hpp" +#include "poll.hpp" #elif defined ZMQ_USE_SELECT -# include "select.hpp" +#include "select.hpp" #elif defined ZMQ_HAVE_GNU -# define ZMQ_USE_POLL -# include "poll.hpp" +#define ZMQ_USE_POLL +#include "poll.hpp" #else -# error None of the ZMQ_USE_* macros defined +#error None of the ZMQ_USE_* macros defined #endif #if defined ZMQ_USE_SELECT diff --git a/src/poller_base.cpp b/src/poller_base.cpp index 50c540c302..463095baba 100644 --- a/src/poller_base.cpp +++ b/src/poller_base.cpp @@ -51,8 +51,7 @@ void zmq::poller_base_t::adjust_load (int amount_) { if (amount_ > 0) load.add (amount_); - else - if (amount_ < 0) + else if (amount_ < 0) load.sub (-amount_); } @@ -88,7 +87,6 @@ uint64_t zmq::poller_base_t::execute_timers () // Execute the timers that are already due. timers_t::iterator it = timers.begin (); while (it != timers.end ()) { - // If we have to wait to execute the item, same will be true about // all the following items (multimap is sorted). Thus we can stop // checking the subsequent timers and return the time to wait for diff --git a/src/poller_base.hpp b/src/poller_base.hpp index 4f1195c368..a5ec664bba 100644 --- a/src/poller_base.hpp +++ b/src/poller_base.hpp @@ -37,59 +37,54 @@ namespace zmq { +struct i_poll_events; - struct i_poll_events; - - class poller_base_t - { - public: - - poller_base_t (); - virtual ~poller_base_t (); - - // Returns load of the poller. Note that this function can be - // invoked from a different thread! - int get_load (); - - // Add a timeout to expire in timeout_ milliseconds. After the - // expiration timer_event on sink_ object will be called with - // argument set to id_. - void add_timer (int timeout_, zmq::i_poll_events *sink_, int id_); - - // Cancel the timer created by sink_ object with ID equal to id_. - void cancel_timer (zmq::i_poll_events *sink_, int id_); - - protected: +class poller_base_t +{ + public: + poller_base_t (); + virtual ~poller_base_t (); - // Called by individual poller implementations to manage the load. - void adjust_load (int amount_); + // Returns load of the poller. Note that this function can be + // invoked from a different thread! + int get_load (); - // Executes any timers that are due. Returns number of milliseconds - // to wait to match the next timer or 0 meaning "no timers". - uint64_t execute_timers (); + // Add a timeout to expire in timeout_ milliseconds. After the + // expiration timer_event on sink_ object will be called with + // argument set to id_. + void add_timer (int timeout_, zmq::i_poll_events *sink_, int id_); - private: + // Cancel the timer created by sink_ object with ID equal to id_. + void cancel_timer (zmq::i_poll_events *sink_, int id_); - // Clock instance private to this I/O thread. - clock_t clock; + protected: + // Called by individual poller implementations to manage the load. + void adjust_load (int amount_); - // List of active timers. - struct timer_info_t - { - zmq::i_poll_events *sink; - int id; - }; - typedef std::multimap timers_t; - timers_t timers; + // Executes any timers that are due. Returns number of milliseconds + // to wait to match the next timer or 0 meaning "no timers". + uint64_t execute_timers (); - // Load of the poller. Currently the number of file descriptors - // registered. - atomic_counter_t load; + private: + // Clock instance private to this I/O thread. + clock_t clock; - poller_base_t (const poller_base_t&); - const poller_base_t &operator = (const poller_base_t&); + // List of active timers. + struct timer_info_t + { + zmq::i_poll_events *sink; + int id; }; + typedef std::multimap timers_t; + timers_t timers; + + // Load of the poller. Currently the number of file descriptors + // registered. + atomic_counter_t load; + poller_base_t (const poller_base_t &); + const poller_base_t &operator= (const poller_base_t &); +}; } #endif diff --git a/src/pollset.cpp b/src/pollset.cpp index f08b34b44e..f164e40910 100644 --- a/src/pollset.cpp +++ b/src/pollset.cpp @@ -43,7 +43,7 @@ #include "i_poll_events.hpp" zmq::pollset_t::pollset_t (const zmq::ctx_t &ctx_) : - ctx(ctx_), + ctx (ctx_), stopping (false) { pollset_fd = pollset_create (-1); @@ -57,22 +57,23 @@ zmq::pollset_t::~pollset_t () pollset_destroy (pollset_fd); for (retired_t::iterator it = retired.begin (); it != retired.end (); ++it) - LIBZMQ_DELETE(*it); + LIBZMQ_DELETE (*it); } -zmq::pollset_t::handle_t zmq::pollset_t::add_fd (fd_t fd_, i_poll_events *events_) +zmq::pollset_t::handle_t zmq::pollset_t::add_fd (fd_t fd_, + i_poll_events *events_) { poll_entry_t *pe = new (std::nothrow) poll_entry_t; alloc_assert (pe); - pe->fd = fd_; - pe->flag_pollin = false; + pe->fd = fd_; + pe->flag_pollin = false; pe->flag_pollout = false; - pe->events = events_; + pe->events = events_; struct poll_ctl pc; - pc.fd = fd_; - pc.cmd = PS_ADD; + pc.fd = fd_; + pc.cmd = PS_ADD; pc.events = 0; int rc = pollset_ctl (pollset_fd, &pc, 1); @@ -82,15 +83,15 @@ zmq::pollset_t::handle_t zmq::pollset_t::add_fd (fd_t fd_, i_poll_events *events adjust_load (1); if (fd_ >= fd_table.size ()) { - fd_table.resize(fd_ + 1, NULL); + fd_table.resize (fd_ + 1, NULL); } - fd_table [fd_] = pe; + fd_table[fd_] = pe; return pe; } void zmq::pollset_t::rm_fd (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; struct poll_ctl pc; pc.fd = pe->fd; @@ -98,7 +99,7 @@ void zmq::pollset_t::rm_fd (handle_t handle_) pc.events = 0; pollset_ctl (pollset_fd, &pc, 1); - fd_table [pe->fd] = NULL; + fd_table[pe->fd] = NULL; pe->fd = retired_fd; retired.push_back (pe); @@ -109,37 +110,37 @@ void zmq::pollset_t::rm_fd (handle_t handle_) void zmq::pollset_t::set_pollin (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; if (likely (!pe->flag_pollin)) { struct poll_ctl pc; - pc.fd = pe->fd; - pc.cmd = PS_MOD; + pc.fd = pe->fd; + pc.cmd = PS_MOD; pc.events = POLLIN; const int rc = pollset_ctl (pollset_fd, &pc, 1); errno_assert (rc != -1); - - pe->flag_pollin = true; + + pe->flag_pollin = true; } } void zmq::pollset_t::reset_pollin (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; - if (unlikely(!pe->flag_pollin)) { + poll_entry_t *pe = (poll_entry_t *) handle_; + if (unlikely (!pe->flag_pollin)) { return; } struct poll_ctl pc; - pc.fd = pe->fd; + pc.fd = pe->fd; pc.events = 0; pc.cmd = PS_DELETE; int rc = pollset_ctl (pollset_fd, &pc, 1); - + if (pe->flag_pollout) { pc.events = POLLOUT; - pc.cmd = PS_MOD; + pc.cmd = PS_MOD; rc = pollset_ctl (pollset_fd, &pc, 1); errno_assert (rc != -1); } @@ -149,37 +150,37 @@ void zmq::pollset_t::reset_pollin (handle_t handle_) void zmq::pollset_t::set_pollout (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; + poll_entry_t *pe = (poll_entry_t *) handle_; if (likely (!pe->flag_pollout)) { struct poll_ctl pc; - pc.fd = pe->fd; - pc.cmd = PS_MOD; + pc.fd = pe->fd; + pc.cmd = PS_MOD; pc.events = POLLOUT; const int rc = pollset_ctl (pollset_fd, &pc, 1); errno_assert (rc != -1); - pe->flag_pollout = true; + pe->flag_pollout = true; } } void zmq::pollset_t::reset_pollout (handle_t handle_) { - poll_entry_t *pe = (poll_entry_t*) handle_; - if (unlikely(!pe->flag_pollout)) { + poll_entry_t *pe = (poll_entry_t *) handle_; + if (unlikely (!pe->flag_pollout)) { return; } struct poll_ctl pc; - pc.fd = pe->fd; + pc.fd = pe->fd; pc.events = 0; pc.cmd = PS_DELETE; int rc = pollset_ctl (pollset_fd, &pc, 1); errno_assert (rc != -1); - + if (pe->flag_pollin) { - pc.cmd = PS_MOD; + pc.cmd = PS_MOD; pc.events = POLLIN; rc = pollset_ctl (pollset_fd, &pc, 1); errno_assert (rc != -1); @@ -207,48 +208,47 @@ void zmq::pollset_t::loop () struct pollfd polldata_array[max_io_events]; while (!stopping) { - // Execute any due timers. int timeout = (int) execute_timers (); // Wait for events. - int n = pollset_poll(pollset_fd, polldata_array, max_io_events, - timeout ? timeout : -1); + int n = pollset_poll (pollset_fd, polldata_array, max_io_events, + timeout ? timeout : -1); if (n == -1) { errno_assert (errno == EINTR); continue; } - for (int i = 0; i < n; i ++) { - poll_entry_t *pe = fd_table [polldata_array [i].fd]; + for (int i = 0; i < n; i++) { + poll_entry_t *pe = fd_table[polldata_array[i].fd]; if (!pe) continue; if (pe->fd == retired_fd) continue; - if (polldata_array [i].revents & (POLLERR | POLLHUP)) + if (polldata_array[i].revents & (POLLERR | POLLHUP)) pe->events->in_event (); if (pe->fd == retired_fd) - continue; - if (polldata_array [i].revents & POLLOUT) + continue; + if (polldata_array[i].revents & POLLOUT) pe->events->out_event (); if (pe->fd == retired_fd) continue; - if (polldata_array [i].revents & POLLIN) + if (polldata_array[i].revents & POLLIN) pe->events->in_event (); } // Destroy retired event sources. for (retired_t::iterator it = retired.begin (); it != retired.end (); - ++it) - LIBZMQ_DELETE(*it); + ++it) + LIBZMQ_DELETE (*it); retired.clear (); } } void zmq::pollset_t::worker_routine (void *arg_) { - ((pollset_t*) arg_)->loop (); + ((pollset_t *) arg_)->loop (); } #endif diff --git a/src/pollset.hpp b/src/pollset.hpp index 9ce333caeb..84d75688a1 100644 --- a/src/pollset.hpp +++ b/src/pollset.hpp @@ -45,75 +45,71 @@ namespace zmq { +struct i_poll_events; - struct i_poll_events; +// This class implements socket polling mechanism using the AIX-specific +// pollset mechanism. - // This class implements socket polling mechanism using the AIX-specific - // pollset mechanism. - - class pollset_t : public poller_base_t - { - public: - - typedef void* handle_t; - - pollset_t (const ctx_t &ctx_); - ~pollset_t (); - - // "poller" concept. - handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); - void rm_fd (handle_t handle_); - void set_pollin (handle_t handle_); - void reset_pollin (handle_t handle_); - void set_pollout (handle_t handle_); - void reset_pollout (handle_t handle_); - void start (); - void stop (); +class pollset_t : public poller_base_t +{ + public: + typedef void *handle_t; - static int max_fds (); + pollset_t (const ctx_t &ctx_); + ~pollset_t (); - private: + // "poller" concept. + handle_t add_fd (fd_t fd_, zmq::i_poll_events *events_); + void rm_fd (handle_t handle_); + void set_pollin (handle_t handle_); + void reset_pollin (handle_t handle_); + void set_pollout (handle_t handle_); + void reset_pollout (handle_t handle_); + void start (); + void stop (); - // Main worker thread routine. - static void worker_routine (void *arg_); + static int max_fds (); - // Main event loop. - void loop (); + private: + // Main worker thread routine. + static void worker_routine (void *arg_); - // Reference to ZMQ context. - const ctx_t &ctx; + // Main event loop. + void loop (); - // Main pollset file descriptor - ::pollset_t pollset_fd; + // Reference to ZMQ context. + const ctx_t &ctx; - struct poll_entry_t - { - fd_t fd; - bool flag_pollin; - bool flag_pollout; - zmq::i_poll_events *events; - }; + // Main pollset file descriptor + ::pollset_t pollset_fd; - // List of retired event sources. - typedef std::vector retired_t; - retired_t retired; + struct poll_entry_t + { + fd_t fd; + bool flag_pollin; + bool flag_pollout; + zmq::i_poll_events *events; + }; - // This table stores data for registered descriptors. - typedef std::vector fd_table_t; - fd_table_t fd_table; + // List of retired event sources. + typedef std::vector retired_t; + retired_t retired; - // If true, thread is in the process of shutting down. - bool stopping; + // This table stores data for registered descriptors. + typedef std::vector fd_table_t; + fd_table_t fd_table; - // Handle of the physical thread doing the I/O work. - thread_t worker; + // If true, thread is in the process of shutting down. + bool stopping; - pollset_t (const pollset_t&); - const pollset_t &operator = (const pollset_t&); - }; + // Handle of the physical thread doing the I/O work. + thread_t worker; - typedef pollset_t poller_t; + pollset_t (const pollset_t &); + const pollset_t &operator= (const pollset_t &); +}; +typedef pollset_t poller_t; } #endif diff --git a/src/precompiled.hpp b/src/precompiled.hpp index 7d901052fe..d7818d0a9a 100644 --- a/src/precompiled.hpp +++ b/src/precompiled.hpp @@ -32,7 +32,7 @@ #include "platform.hpp" -#define __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS // This must be included before any windows headers are compiled. #if defined ZMQ_HAVE_WINDOWS diff --git a/src/proxy.cpp b/src/proxy.cpp index 32ff9cfd43..f2f94e7f6b 100644 --- a/src/proxy.cpp +++ b/src/proxy.cpp @@ -43,7 +43,8 @@ #include "proxy.hpp" #include "likely.hpp" -#if defined ZMQ_POLL_BASED_ON_POLL && !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_AIX +#if defined ZMQ_POLL_BASED_ON_POLL && !defined ZMQ_HAVE_WINDOWS \ + && !defined ZMQ_HAVE_AIX #include #endif @@ -59,25 +60,25 @@ // Macros for repetitive code. // PROXY_CLEANUP() must not be used before these variables are initialized. -#define PROXY_CLEANUP()\ - do {\ - delete poller_all;\ - delete poller_in;\ - delete poller_control;\ - delete poller_receive_blocked;\ - delete poller_send_blocked;\ - delete poller_both_blocked;\ - delete poller_frontend_only;\ - delete poller_backend_only;\ +#define PROXY_CLEANUP() \ + do { \ + delete poller_all; \ + delete poller_in; \ + delete poller_control; \ + delete poller_receive_blocked; \ + delete poller_send_blocked; \ + delete poller_both_blocked; \ + delete poller_frontend_only; \ + delete poller_backend_only; \ } while (false) -#define CHECK_RC_EXIT_ON_FAILURE()\ - do {\ - if (rc < 0) {\ - PROXY_CLEANUP();\ - return close_and_return (&msg, -1);\ - }\ +#define CHECK_RC_EXIT_ON_FAILURE() \ + do { \ + if (rc < 0) { \ + PROXY_CLEANUP (); \ + return close_and_return (&msg, -1); \ + } \ } while (false) #endif // ZMQ_HAVE_POLLER @@ -94,13 +95,11 @@ typedef struct } zmq_socket_stats_t; - // Utility functions -int capture ( - class zmq::socket_base_t *capture_, - zmq::msg_t& msg_, - int more_ = 0) +int capture (class zmq::socket_base_t *capture_, + zmq::msg_t &msg_, + int more_ = 0) { // Copy message to capture socket if any if (capture_) { @@ -118,11 +117,12 @@ int capture ( return 0; } -int forward ( - class zmq::socket_base_t *from_, zmq_socket_stats_t* from_stats, - class zmq::socket_base_t *to_, zmq_socket_stats_t* to_stats, - class zmq::socket_base_t *capture_, - zmq::msg_t& msg_) +int forward (class zmq::socket_base_t *from_, + zmq_socket_stats_t *from_stats, + class zmq::socket_base_t *to_, + zmq_socket_stats_t *to_stats, + class zmq::socket_base_t *capture_, + zmq::msg_t &msg_) { int more; size_t moresz; @@ -132,7 +132,7 @@ int forward ( if (unlikely (rc < 0)) return -1; - complete_msg_size += msg_.size(); + complete_msg_size += msg_.size (); moresz = sizeof more; rc = from_->getsockopt (ZMQ_RCVMORE, &more, &moresz); @@ -162,14 +162,16 @@ int forward ( } static int loop_and_send_multipart_stat (zmq::socket_base_t *control_, - uint64_t stat, bool first, bool more) + uint64_t stat, + bool first, + bool more) { int rc; zmq::msg_t msg; // VSM of 8 bytes can't fail to init msg.init_size (sizeof (uint64_t)); - memcpy (msg.data (), (const void *)&stat, sizeof (uint64_t)); + memcpy (msg.data (), (const void *) &stat, sizeof (uint64_t)); // if the first message is handed to the pipe successfully then the HWM // is not full, which means failures are due to interrupts (on Windows pipes @@ -181,24 +183,31 @@ static int loop_and_send_multipart_stat (zmq::socket_base_t *control_, return rc; } -int reply_stats( - class zmq::socket_base_t *control_, - zmq_socket_stats_t* frontend_stats, - zmq_socket_stats_t* backend_stats) +int reply_stats (class zmq::socket_base_t *control_, + zmq_socket_stats_t *frontend_stats, + zmq_socket_stats_t *backend_stats) { // first part: frontend stats - the first send might fail due to HWM - if (loop_and_send_multipart_stat (control_, frontend_stats->msg_in, true, true) != 0) + if (loop_and_send_multipart_stat (control_, frontend_stats->msg_in, true, + true) + != 0) return -1; - loop_and_send_multipart_stat (control_, frontend_stats->bytes_in, false, true); - loop_and_send_multipart_stat (control_, frontend_stats->msg_out, false, true); - loop_and_send_multipart_stat (control_, frontend_stats->bytes_out, false, true); + loop_and_send_multipart_stat (control_, frontend_stats->bytes_in, false, + true); + loop_and_send_multipart_stat (control_, frontend_stats->msg_out, false, + true); + loop_and_send_multipart_stat (control_, frontend_stats->bytes_out, false, + true); // second part: backend stats loop_and_send_multipart_stat (control_, backend_stats->msg_in, false, true); - loop_and_send_multipart_stat (control_, backend_stats->bytes_in, false, true); - loop_and_send_multipart_stat (control_, backend_stats->msg_out, false, true); - loop_and_send_multipart_stat (control_, backend_stats->bytes_out, false, false); + loop_and_send_multipart_stat (control_, backend_stats->bytes_in, false, + true); + loop_and_send_multipart_stat (control_, backend_stats->msg_out, false, + true); + loop_and_send_multipart_stat (control_, backend_stats->bytes_out, false, + false); return 0; } @@ -206,11 +215,10 @@ int reply_stats( #ifdef ZMQ_HAVE_POLLER -int zmq::proxy ( - class socket_base_t *frontend_, - class socket_base_t *backend_, - class socket_base_t *capture_, - class socket_base_t *control_) +int zmq::proxy (class socket_base_t *frontend_, + class socket_base_t *backend_, + class socket_base_t *capture_, + class socket_base_t *control_) { msg_t msg; int rc = msg.init (); @@ -224,7 +232,8 @@ int zmq::proxy ( size_t moresz = sizeof (more); // Proxy can be in these three states - enum { + enum + { active, paused, terminated @@ -236,50 +245,66 @@ int zmq::proxy ( bool backend_in = false; bool backend_out = false; bool control_in = false; - zmq::socket_poller_t::event_t events [3]; + zmq::socket_poller_t::event_t events[3]; zmq_socket_stats_t frontend_stats; zmq_socket_stats_t backend_stats; - memset(&frontend_stats, 0, sizeof(frontend_stats)); - memset(&backend_stats, 0, sizeof(backend_stats)); + memset (&frontend_stats, 0, sizeof (frontend_stats)); + memset (&backend_stats, 0, sizeof (backend_stats)); // Don't allocate these pollers from stack because they will take more than 900 kB of stack! // On Windows this blows up default stack of 1 MB and aborts the program. // I wanted to use std::shared_ptr here as the best solution but that requires C++11... - zmq::socket_poller_t *poller_all = new (std::nothrow) zmq::socket_poller_t; // Poll for everything. - zmq::socket_poller_t *poller_in = new (std::nothrow) zmq::socket_poller_t; // Poll only 'ZMQ_POLLIN' on all sockets. Initial blocking poll in loop. - zmq::socket_poller_t *poller_control = new (std::nothrow) zmq::socket_poller_t; // Poll only for 'ZMQ_POLLIN' on 'control_', when proxy is paused. - zmq::socket_poller_t *poller_receive_blocked = new (std::nothrow) zmq::socket_poller_t; // All except 'ZMQ_POLLIN' on 'frontend_'. + zmq::socket_poller_t *poller_all = + new (std::nothrow) zmq::socket_poller_t; // Poll for everything. + zmq::socket_poller_t *poller_in = new (std::nothrow) zmq:: + socket_poller_t; // Poll only 'ZMQ_POLLIN' on all sockets. Initial blocking poll in loop. + zmq::socket_poller_t *poller_control = new (std::nothrow) zmq:: + socket_poller_t; // Poll only for 'ZMQ_POLLIN' on 'control_', when proxy is paused. + zmq::socket_poller_t *poller_receive_blocked = new (std::nothrow) + zmq::socket_poller_t; // All except 'ZMQ_POLLIN' on 'frontend_'. // If frontend_==backend_ 'poller_send_blocked' and 'poller_receive_blocked' are the same, 'ZMQ_POLLIN' is ignored. // In that case 'poller_send_blocked' is not used. We need only 'poller_receive_blocked'. // We also don't need 'poller_both_blocked', 'poller_backend_only' nor 'poller_frontend_only' no need to initialize it. // We save some RAM and time for initialization. - zmq::socket_poller_t *poller_send_blocked = NULL; // All except 'ZMQ_POLLIN' on 'backend_'. - zmq::socket_poller_t *poller_both_blocked = NULL; // All except 'ZMQ_POLLIN' on both 'frontend_' and 'backend_'. - zmq::socket_poller_t *poller_frontend_only = NULL; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'frontend_'. - zmq::socket_poller_t *poller_backend_only = NULL; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'backend_'. + zmq::socket_poller_t *poller_send_blocked = + NULL; // All except 'ZMQ_POLLIN' on 'backend_'. + zmq::socket_poller_t *poller_both_blocked = + NULL; // All except 'ZMQ_POLLIN' on both 'frontend_' and 'backend_'. + zmq::socket_poller_t *poller_frontend_only = + NULL; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'frontend_'. + zmq::socket_poller_t *poller_backend_only = + NULL; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'backend_'. if (frontend_ != backend_) { - poller_send_blocked = new (std::nothrow) zmq::socket_poller_t; // All except 'ZMQ_POLLIN' on 'backend_'. - poller_both_blocked = new (std::nothrow) zmq::socket_poller_t; // All except 'ZMQ_POLLIN' on both 'frontend_' and 'backend_'. - poller_frontend_only = new (std::nothrow) zmq::socket_poller_t; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'frontend_'. - poller_backend_only = new (std::nothrow) zmq::socket_poller_t; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'backend_'. + poller_send_blocked = new (std::nothrow) + zmq::socket_poller_t; // All except 'ZMQ_POLLIN' on 'backend_'. + poller_both_blocked = new (std::nothrow) zmq:: + socket_poller_t; // All except 'ZMQ_POLLIN' on both 'frontend_' and 'backend_'. + poller_frontend_only = new (std::nothrow) zmq:: + socket_poller_t; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'frontend_'. + poller_backend_only = new (std::nothrow) zmq:: + socket_poller_t; // Only 'ZMQ_POLLIN' and 'ZMQ_POLLOUT' on 'backend_'. frontend_equal_to_backend = false; } else frontend_equal_to_backend = true; - if (poller_all == NULL || poller_in == NULL || poller_control == NULL || poller_receive_blocked == NULL - || ((poller_send_blocked == NULL || poller_both_blocked == NULL) && !frontend_equal_to_backend)) { + if (poller_all == NULL || poller_in == NULL || poller_control == NULL + || poller_receive_blocked == NULL + || ((poller_send_blocked == NULL || poller_both_blocked == NULL) + && !frontend_equal_to_backend)) { PROXY_CLEANUP (); return close_and_return (&msg, -1); } - zmq::socket_poller_t *poller_wait = poller_in; // Poller for blocking wait, initially all 'ZMQ_POLLIN'. + zmq::socket_poller_t *poller_wait = + poller_in; // Poller for blocking wait, initially all 'ZMQ_POLLIN'. - // Register 'frontend_' and 'backend_' with pollers. - rc = poller_all->add (frontend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT); // Everything. + // Register 'frontend_' and 'backend_' with pollers. + rc = poller_all->add (frontend_, NULL, + ZMQ_POLLIN | ZMQ_POLLOUT); // Everything. CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_in->add (frontend_, NULL, ZMQ_POLLIN); // All 'ZMQ_POLLIN's. + rc = poller_in->add (frontend_, NULL, ZMQ_POLLIN); // All 'ZMQ_POLLIN's. CHECK_RC_EXIT_ON_FAILURE (); if (frontend_equal_to_backend) { @@ -289,25 +314,38 @@ int zmq::proxy ( rc = poller_receive_blocked->add (frontend_, NULL, ZMQ_POLLOUT); CHECK_RC_EXIT_ON_FAILURE (); } else { - rc = poller_all->add (backend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT); // Everything. + rc = poller_all->add (backend_, NULL, + ZMQ_POLLIN | ZMQ_POLLOUT); // Everything. CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_in->add (backend_, NULL, ZMQ_POLLIN); // All 'ZMQ_POLLIN's. + rc = poller_in->add (backend_, NULL, ZMQ_POLLIN); // All 'ZMQ_POLLIN's. CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_both_blocked->add (frontend_, NULL, ZMQ_POLLOUT); // Waiting only for 'ZMQ_POLLOUT'. + rc = poller_both_blocked->add ( + frontend_, NULL, ZMQ_POLLOUT); // Waiting only for 'ZMQ_POLLOUT'. CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_both_blocked->add (backend_, NULL, ZMQ_POLLOUT); // Waiting only for 'ZMQ_POLLOUT'. + rc = poller_both_blocked->add ( + backend_, NULL, ZMQ_POLLOUT); // Waiting only for 'ZMQ_POLLOUT'. CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_send_blocked->add (backend_, NULL, ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'backend_'. + rc = poller_send_blocked->add ( + backend_, NULL, + ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'backend_'. CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_send_blocked->add (frontend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'backend_'. + rc = poller_send_blocked->add ( + frontend_, NULL, + ZMQ_POLLIN | ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'backend_'. CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_receive_blocked->add (frontend_, NULL, ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'frontend_'. + rc = poller_receive_blocked->add ( + frontend_, NULL, + ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'frontend_'. CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_receive_blocked->add (backend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'frontend_'. + rc = poller_receive_blocked->add ( + backend_, NULL, + ZMQ_POLLIN | ZMQ_POLLOUT); // All except 'ZMQ_POLLIN' on 'frontend_'. CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_frontend_only->add (frontend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT); + rc = + poller_frontend_only->add (frontend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT); CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_backend_only->add (backend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT); + rc = + poller_backend_only->add (backend_, NULL, ZMQ_POLLIN | ZMQ_POLLOUT); CHECK_RC_EXIT_ON_FAILURE (); } @@ -317,7 +355,9 @@ int zmq::proxy ( CHECK_RC_EXIT_ON_FAILURE (); rc = poller_in->add (control_, NULL, ZMQ_POLLIN); CHECK_RC_EXIT_ON_FAILURE (); - rc = poller_control->add (control_, NULL, ZMQ_POLLIN); // When proxy is paused we wait only for ZMQ_POLLIN on 'control_' socket. + rc = poller_control->add ( + control_, NULL, + ZMQ_POLLIN); // When proxy is paused we wait only for ZMQ_POLLIN on 'control_' socket. CHECK_RC_EXIT_ON_FAILURE (); rc = poller_receive_blocked->add (control_, NULL, ZMQ_POLLIN); CHECK_RC_EXIT_ON_FAILURE (); @@ -339,7 +379,6 @@ int zmq::proxy ( while (state != terminated) { - // Blocking wait initially only for 'ZMQ_POLLIN' - 'poller_wait' points to 'poller_in'. // If one of receiving end's queue is full ('ZMQ_POLLOUT' not available), // 'poller_wait' is pointed to 'poller_receive_blocked', 'poller_send_blocked' or 'poller_both_blocked'. @@ -356,18 +395,17 @@ int zmq::proxy ( // Process events. for (i = 0; i < rc; i++) { - if (events [i].socket == frontend_) { - frontend_in = (events [i].events & ZMQ_POLLIN) != 0; - frontend_out = (events [i].events & ZMQ_POLLOUT) != 0; + if (events[i].socket == frontend_) { + frontend_in = (events[i].events & ZMQ_POLLIN) != 0; + frontend_out = (events[i].events & ZMQ_POLLOUT) != 0; } else - // This 'if' needs to be after check for 'frontend_' in order never - // to be reached in case frontend_==backend_, so we ensure backend_in=false in that case. - if (events [i].socket == backend_) { - backend_in = (events [i].events & ZMQ_POLLIN) != 0; - backend_out = (events [i].events & ZMQ_POLLOUT) != 0; - } else - if (events [i].socket == control_) - control_in = (events [i].events & ZMQ_POLLIN) != 0; + // This 'if' needs to be after check for 'frontend_' in order never + // to be reached in case frontend_==backend_, so we ensure backend_in=false in that case. + if (events[i].socket == backend_) { + backend_in = (events[i].events & ZMQ_POLLIN) != 0; + backend_out = (events[i].events & ZMQ_POLLOUT) != 0; + } else if (events[i].socket == control_) + control_in = (events[i].events & ZMQ_POLLIN) != 0; } @@ -388,72 +426,76 @@ int zmq::proxy ( if (msg.size () == 5 && memcmp (msg.data (), "PAUSE", 5) == 0) { state = paused; poller_wait = poller_control; - } else - if (msg.size () == 6 && memcmp (msg.data (), "RESUME", 6) == 0) { - state = active; - poller_wait = poller_in; - } else { - if (msg.size () == 9 && memcmp (msg.data (), "TERMINATE", 9) == 0) - state = terminated; - else { + } else if (msg.size () == 6 + && memcmp (msg.data (), "RESUME", 6) == 0) { + state = active; + poller_wait = poller_in; + } else { + if (msg.size () == 9 + && memcmp (msg.data (), "TERMINATE", 9) == 0) + state = terminated; + else { #ifdef ZMQ_BUILD_DRAFT_API - if (msg.size () == 10 && memcmp (msg.data (), "STATISTICS", 10) == 0) - { - rc = reply_stats(control_, &frontend_stats, &backend_stats); - CHECK_RC_EXIT_ON_FAILURE (); - } - else { + if (msg.size () == 10 + && memcmp (msg.data (), "STATISTICS", 10) == 0) { + rc = reply_stats (control_, &frontend_stats, + &backend_stats); + CHECK_RC_EXIT_ON_FAILURE (); + } else { #endif - // This is an API error, we assert - puts ("E: invalid command sent to proxy"); - zmq_assert (false); + // This is an API error, we assert + puts ("E: invalid command sent to proxy"); + zmq_assert (false); #ifdef ZMQ_BUILD_DRAFT_API - } -#endif } +#endif } + } control_in = false; } if (state == active) { - // Process a request, 'ZMQ_POLLIN' on 'frontend_' and 'ZMQ_POLLOUT' on 'backend_'. // In case of frontend_==backend_ there's no 'ZMQ_POLLOUT' event. if (frontend_in && (backend_out || frontend_equal_to_backend)) { - rc = forward (frontend_, &frontend_stats, backend_, &backend_stats, capture_, msg); + rc = forward (frontend_, &frontend_stats, backend_, + &backend_stats, capture_, msg); CHECK_RC_EXIT_ON_FAILURE (); request_processed = true; frontend_in = backend_out = false; - } else request_processed = false; + } else + request_processed = false; // Process a reply, 'ZMQ_POLLIN' on 'backend_' and 'ZMQ_POLLOUT' on 'frontend_'. - // If 'frontend_' and 'backend_' are the same this is not needed because previous processing + // If 'frontend_' and 'backend_' are the same this is not needed because previous processing // covers all of the cases. 'backend_in' is always false if frontend_==backend_ due to // design in 'for' event processing loop. if (backend_in && frontend_out) { - rc = forward (backend_, &backend_stats, frontend_, &frontend_stats, capture_, msg); + rc = forward (backend_, &backend_stats, frontend_, + &frontend_stats, capture_, msg); CHECK_RC_EXIT_ON_FAILURE (); reply_processed = true; backend_in = frontend_out = false; - } else reply_processed = false; + } else + reply_processed = false; if (request_processed || reply_processed) { // If request/reply is processed that means we had at least one 'ZMQ_POLLOUT' event. // Enable corresponding 'ZMQ_POLLIN' for blocking wait if any was disabled. if (poller_wait != poller_in) { - if (request_processed) { // 'frontend_' -> 'backend_' + if (request_processed) { // 'frontend_' -> 'backend_' if (poller_wait == poller_both_blocked) poller_wait = poller_send_blocked; - else - if (poller_wait == poller_receive_blocked || poller_wait == poller_frontend_only) - poller_wait = poller_in; + else if (poller_wait == poller_receive_blocked + || poller_wait == poller_frontend_only) + poller_wait = poller_in; } - if (reply_processed) { // 'backend_' -> 'frontend_' + if (reply_processed) { // 'backend_' -> 'frontend_' if (poller_wait == poller_both_blocked) poller_wait = poller_receive_blocked; - else - if (poller_wait == poller_send_blocked || poller_wait == poller_backend_only) - poller_wait = poller_in; + else if (poller_wait == poller_send_blocked + || poller_wait == poller_backend_only) + poller_wait = poller_in; } } } else { @@ -470,9 +512,8 @@ int zmq::proxy ( else { if (poller_wait == poller_send_blocked) poller_wait = poller_both_blocked; - else - if (poller_wait == poller_in) - poller_wait = poller_receive_blocked; + else if (poller_wait == poller_in) + poller_wait = poller_receive_blocked; } } if (backend_in) { @@ -485,13 +526,11 @@ int zmq::proxy ( else { if (poller_wait == poller_receive_blocked) poller_wait = poller_both_blocked; - else - if (poller_wait == poller_in) - poller_wait = poller_send_blocked; + else if (poller_wait == poller_in) + poller_wait = poller_send_blocked; } } } - } } PROXY_CLEANUP (); @@ -500,11 +539,10 @@ int zmq::proxy ( #else // ZMQ_HAVE_POLLER -int zmq::proxy ( - class socket_base_t *frontend_, - class socket_base_t *backend_, - class socket_base_t *capture_, - class socket_base_t *control_) +int zmq::proxy (class socket_base_t *frontend_, + class socket_base_t *backend_, + class socket_base_t *capture_, + class socket_base_t *control_) { msg_t msg; int rc = msg.init (); @@ -516,24 +554,21 @@ int zmq::proxy ( int more; size_t moresz; - zmq_pollitem_t items [] = { - { frontend_, 0, ZMQ_POLLIN, 0 }, - { backend_, 0, ZMQ_POLLIN, 0 }, - { control_, 0, ZMQ_POLLIN, 0 } - }; + zmq_pollitem_t items[] = {{frontend_, 0, ZMQ_POLLIN, 0}, + {backend_, 0, ZMQ_POLLIN, 0}, + {control_, 0, ZMQ_POLLIN, 0}}; int qt_poll_items = (control_ ? 3 : 2); - zmq_pollitem_t itemsout [] = { - { frontend_, 0, ZMQ_POLLOUT, 0 }, - { backend_, 0, ZMQ_POLLOUT, 0 } - }; + zmq_pollitem_t itemsout[] = {{frontend_, 0, ZMQ_POLLOUT, 0}, + {backend_, 0, ZMQ_POLLOUT, 0}}; zmq_socket_stats_t frontend_stats; - memset(&frontend_stats, 0, sizeof(frontend_stats)); + memset (&frontend_stats, 0, sizeof (frontend_stats)); zmq_socket_stats_t backend_stats; - memset(&backend_stats, 0, sizeof(backend_stats)); + memset (&backend_stats, 0, sizeof (backend_stats)); // Proxy can be in these three states - enum { + enum + { active, paused, terminated @@ -541,7 +576,7 @@ int zmq::proxy ( while (state != terminated) { // Wait while there are either requests or replies to process. - rc = zmq_poll (&items [0], qt_poll_items, -1); + rc = zmq_poll (&items[0], qt_poll_items, -1); if (unlikely (rc < 0)) return close_and_return (&msg, -1); @@ -549,14 +584,14 @@ int zmq::proxy ( // because pollout shall most of the time return directly. // POLLOUT is only checked when frontend and backend sockets are not the same. if (frontend_ != backend_) { - rc = zmq_poll (&itemsout [0], 2, 0); + rc = zmq_poll (&itemsout[0], 2, 0); if (unlikely (rc < 0)) { return close_and_return (&msg, -1); } } // Process a control command if any - if (control_ && items [2].revents & ZMQ_POLLIN) { + if (control_ && items[2].revents & ZMQ_POLLIN) { rc = control_->recv (&msg, 0); if (unlikely (rc < 0)) return close_and_return (&msg, -1); @@ -573,44 +608,43 @@ int zmq::proxy ( if (msg.size () == 5 && memcmp (msg.data (), "PAUSE", 5) == 0) state = paused; - else - if (msg.size () == 6 && memcmp (msg.data (), "RESUME", 6) == 0) - state = active; - else - if (msg.size () == 9 && memcmp (msg.data (), "TERMINATE", 9) == 0) - state = terminated; - else { + else if (msg.size () == 6 && memcmp (msg.data (), "RESUME", 6) == 0) + state = active; + else if (msg.size () == 9 + && memcmp (msg.data (), "TERMINATE", 9) == 0) + state = terminated; + else { #ifdef ZMQ_BUILD_DRAFT_API - if (msg.size () == 10 && memcmp (msg.data (), "STATISTICS", 10) == 0) - { - rc = reply_stats(control_, &frontend_stats, &backend_stats); - if (unlikely (rc < 0)) - return close_and_return (&msg, -1); - } - else { + if (msg.size () == 10 + && memcmp (msg.data (), "STATISTICS", 10) == 0) { + rc = + reply_stats (control_, &frontend_stats, &backend_stats); + if (unlikely (rc < 0)) + return close_and_return (&msg, -1); + } else { #endif - // This is an API error, we assert - puts ("E: invalid command sent to proxy"); - zmq_assert (false); + // This is an API error, we assert + puts ("E: invalid command sent to proxy"); + zmq_assert (false); #ifdef ZMQ_BUILD_DRAFT_API - } + } #endif - } + } } // Process a request - if (state == active - && items [0].revents & ZMQ_POLLIN - && (frontend_ == backend_ || itemsout [1].revents & ZMQ_POLLOUT)) { - rc = forward (frontend_, &frontend_stats, backend_, &backend_stats, capture_, msg); + if (state == active && items[0].revents & ZMQ_POLLIN + && (frontend_ == backend_ || itemsout[1].revents & ZMQ_POLLOUT)) { + rc = forward (frontend_, &frontend_stats, backend_, &backend_stats, + capture_, msg); if (unlikely (rc < 0)) return close_and_return (&msg, -1); } // Process a reply - if (state == active - && frontend_ != backend_ - && items [1].revents & ZMQ_POLLIN - && itemsout [0].revents & ZMQ_POLLOUT) { - rc = forward (backend_, &backend_stats, frontend_, &frontend_stats, capture_, msg); + if (state == active && frontend_ != backend_ + && items[1].revents & ZMQ_POLLIN + && itemsout[0].revents & ZMQ_POLLOUT) { + rc = forward (backend_, &backend_stats, frontend_, &frontend_stats, + capture_, msg); if (unlikely (rc < 0)) return close_and_return (&msg, -1); } diff --git a/src/proxy.hpp b/src/proxy.hpp index de9416edd8..f078c6ae59 100644 --- a/src/proxy.hpp +++ b/src/proxy.hpp @@ -32,11 +32,11 @@ namespace zmq { - int proxy ( - class socket_base_t *frontend_, - class socket_base_t *backend_, - class socket_base_t *capture_, - class socket_base_t *control_ = NULL); // backward compatibility without this argument +int proxy (class socket_base_t *frontend_, + class socket_base_t *backend_, + class socket_base_t *capture_, + class socket_base_t *control_ = + NULL); // backward compatibility without this argument } #endif diff --git a/src/pub.hpp b/src/pub.hpp index 2ba81134fa..8ca28896df 100644 --- a/src/pub.hpp +++ b/src/pub.hpp @@ -34,30 +34,26 @@ namespace zmq { +class ctx_t; +class io_thread_t; +class socket_base_t; +class msg_t; - class ctx_t; - class io_thread_t; - class socket_base_t; - class msg_t; - - class pub_t : public xpub_t - { - public: - - pub_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~pub_t (); - - // Implementations of virtual functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_ = false); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - - private: - - pub_t (const pub_t&); - const pub_t &operator = (const pub_t&); - }; - +class pub_t : public xpub_t +{ + public: + pub_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~pub_t (); + + // Implementations of virtual functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_ = false); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + + private: + pub_t (const pub_t &); + const pub_t &operator= (const pub_t &); +}; } #endif diff --git a/src/pull.hpp b/src/pull.hpp index 5677ed9800..154c0d34f9 100644 --- a/src/pull.hpp +++ b/src/pull.hpp @@ -36,40 +36,33 @@ namespace zmq { +class ctx_t; +class pipe_t; +class msg_t; +class io_thread_t; - class ctx_t; - class pipe_t; - class msg_t; - class io_thread_t; - - class pull_t : - public socket_base_t - { - public: - - pull_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~pull_t (); - - protected: - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - const blob_t &get_credential () const; - void xread_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - - // Fair queueing object for inbound pipes. - fq_t fq; - - pull_t (const pull_t&); - const pull_t &operator = (const pull_t&); - - }; - +class pull_t : public socket_base_t +{ + public: + pull_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~pull_t (); + + protected: + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + const blob_t &get_credential () const; + void xread_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + // Fair queueing object for inbound pipes. + fq_t fq; + + pull_t (const pull_t &); + const pull_t &operator= (const pull_t &); +}; } #endif diff --git a/src/push.hpp b/src/push.hpp index d6289dfab3..7f20f863e9 100644 --- a/src/push.hpp +++ b/src/push.hpp @@ -36,38 +36,32 @@ namespace zmq { +class ctx_t; +class pipe_t; +class msg_t; +class io_thread_t; - class ctx_t; - class pipe_t; - class msg_t; - class io_thread_t; - - class push_t : - public socket_base_t - { - public: - - push_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~push_t (); - - protected: - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsend (zmq::msg_t *msg_); - bool xhas_out (); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - - // Load balancer managing the outbound pipes. - lb_t lb; - - push_t (const push_t&); - const push_t &operator = (const push_t&); - }; - +class push_t : public socket_base_t +{ + public: + push_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~push_t (); + + protected: + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsend (zmq::msg_t *msg_); + bool xhas_out (); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + // Load balancer managing the outbound pipes. + lb_t lb; + + push_t (const push_t &); + const push_t &operator= (const push_t &); +}; } #endif diff --git a/src/radio.cpp b/src/radio.cpp index 3e2d192982..e22fbdfa43 100644 --- a/src/radio.cpp +++ b/src/radio.cpp @@ -76,12 +76,14 @@ void zmq::radio_t::xread_activated (pipe_t *pipe_) std::string group = std::string (msg.group ()); if (msg.is_join ()) - subscriptions.ZMQ_MAP_INSERT_OR_EMPLACE (ZMQ_MOVE(group), pipe_); + subscriptions.ZMQ_MAP_INSERT_OR_EMPLACE (ZMQ_MOVE (group), + pipe_); else { - std::pair range = - subscriptions.equal_range (group); + std::pair + range = subscriptions.equal_range (group); - for (subscriptions_t::iterator it = range.first; it != range.second; ++it) { + for (subscriptions_t::iterator it = range.first; + it != range.second; ++it) { if (it->second == pipe_) { subscriptions.erase (it); break; @@ -102,7 +104,8 @@ void zmq::radio_t::xpipe_terminated (pipe_t *pipe_) { // NOTE: erase invalidates an iterator, and that's why it's not incrementing in post-loop // read-after-free caught by Valgrind, see https://github.com/zeromq/libzmq/pull/1771 - for (subscriptions_t::iterator it = subscriptions.begin (); it != subscriptions.end (); ) { + for (subscriptions_t::iterator it = subscriptions.begin (); + it != subscriptions.end ();) { if (it->second == pipe_) { subscriptions.erase (it++); } else { @@ -110,8 +113,8 @@ void zmq::radio_t::xpipe_terminated (pipe_t *pipe_) } } - udp_pipes_t::iterator it = std::find(udp_pipes.begin(), - udp_pipes.end (), pipe_); + udp_pipes_t::iterator it = + std::find (udp_pipes.begin (), udp_pipes.end (), pipe_); if (it != udp_pipes.end ()) udp_pipes.erase (it); @@ -129,12 +132,13 @@ int zmq::radio_t::xsend (msg_t *msg_) dist.unmatch (); std::pair range = - subscriptions.equal_range (std::string(msg_->group ())); + subscriptions.equal_range (std::string (msg_->group ())); for (subscriptions_t::iterator it = range.first; it != range.second; ++it) - dist.match (it-> second); + dist.match (it->second); - for (udp_pipes_t::iterator it = udp_pipes.begin (); it != udp_pipes.end (); ++it) + for (udp_pipes_t::iterator it = udp_pipes.begin (); it != udp_pipes.end (); + ++it) dist.match (*it); int rc = dist.send_to_matching (msg_); @@ -160,9 +164,11 @@ bool zmq::radio_t::xhas_in () return false; } -zmq::radio_session_t::radio_session_t (io_thread_t *io_thread_, bool connect_, - socket_base_t *socket_, const options_t &options_, - address_t *addr_) : +zmq::radio_session_t::radio_session_t (io_thread_t *io_thread_, + bool connect_, + socket_base_t *socket_, + const options_t &options_, + address_t *addr_) : session_base_t (io_thread_, connect_, socket_, options_, addr_), state (group) { @@ -174,13 +180,12 @@ zmq::radio_session_t::~radio_session_t () int zmq::radio_session_t::push_msg (msg_t *msg_) { - if (msg_->flags() & msg_t::command) { - char *command_data = - static_cast (msg_->data ()); + if (msg_->flags () & msg_t::command) { + char *command_data = static_cast (msg_->data ()); const size_t data_size = msg_->size (); int group_length; - char * group; + char *group; msg_t join_leave_msg; int rc; @@ -190,8 +195,7 @@ int zmq::radio_session_t::push_msg (msg_t *msg_) group_length = (int) data_size - 5; group = command_data + 5; rc = join_leave_msg.init_join (); - } - else if (data_size >= 6 && memcmp (command_data, "\5LEAVE", 6) == 0) { + } else if (data_size >= 6 && memcmp (command_data, "\5LEAVE", 6) == 0) { group_length = (int) data_size - 6; group = command_data + 6; rc = join_leave_msg.init_leave (); @@ -213,8 +217,7 @@ int zmq::radio_session_t::push_msg (msg_t *msg_) // Push the join or leave command *msg_ = join_leave_msg; return session_base_t::push_msg (msg_); - } - else + } else return session_base_t::push_msg (msg_); } @@ -230,15 +233,14 @@ int zmq::radio_session_t::pull_msg (msg_t *msg_) // First frame is the group rc = msg_->init_size (length); - errno_assert(rc == 0); - msg_->set_flags(msg_t::more); + errno_assert (rc == 0); + msg_->set_flags (msg_t::more); memcpy (msg_->data (), group, length); // Next status is the body state = body; return 0; - } - else { + } else { *msg_ = pending_msg; state = group; return 0; diff --git a/src/radio.hpp b/src/radio.hpp index eb0dbf58fc..a5d80ab61f 100644 --- a/src/radio.hpp +++ b/src/radio.hpp @@ -42,71 +42,70 @@ namespace zmq { +class ctx_t; +class msg_t; +class pipe_t; +class io_thread_t; - class ctx_t; - class msg_t; - class pipe_t; - class io_thread_t; - - class radio_t : - public socket_base_t - { - public: - - radio_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~radio_t (); - - // Implementations of virtual functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_ = false); - int xsend (zmq::msg_t *msg_); - bool xhas_out (); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - // List of all subscriptions mapped to corresponding pipes. - typedef std::multimap subscriptions_t; - subscriptions_t subscriptions; - - // List of udp pipes - typedef std::vector udp_pipes_t; - udp_pipes_t udp_pipes; - - // Distributor of messages holding the list of outbound pipes. - dist_t dist; - - radio_t (const radio_t&); - const radio_t &operator = (const radio_t&); - }; - - class radio_session_t : public session_base_t +class radio_t : public socket_base_t +{ + public: + radio_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~radio_t (); + + // Implementations of virtual functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_ = false); + int xsend (zmq::msg_t *msg_); + bool xhas_out (); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + // List of all subscriptions mapped to corresponding pipes. + typedef std::multimap subscriptions_t; + subscriptions_t subscriptions; + + // List of udp pipes + typedef std::vector udp_pipes_t; + udp_pipes_t udp_pipes; + + // Distributor of messages holding the list of outbound pipes. + dist_t dist; + + radio_t (const radio_t &); + const radio_t &operator= (const radio_t &); +}; + +class radio_session_t : public session_base_t +{ + public: + radio_session_t (zmq::io_thread_t *io_thread_, + bool connect_, + zmq::socket_base_t *socket_, + const options_t &options_, + address_t *addr_); + ~radio_session_t (); + + // Overrides of the functions from session_base_t. + int push_msg (msg_t *msg_); + int pull_msg (msg_t *msg_); + void reset (); + + private: + enum { - public: - - radio_session_t (zmq::io_thread_t *io_thread_, bool connect_, - zmq::socket_base_t *socket_, const options_t &options_, - address_t *addr_); - ~radio_session_t (); - - // Overrides of the functions from session_base_t. - int push_msg (msg_t *msg_); - int pull_msg (msg_t *msg_); - void reset (); - private: - - enum { - group, - body - } state; + group, + body + } state; - msg_t pending_msg; + msg_t pending_msg; - radio_session_t (const radio_session_t&); - const radio_session_t &operator = (const radio_session_t&); - }; + radio_session_t (const radio_session_t &); + const radio_session_t &operator= (const radio_session_t &); +}; } #endif diff --git a/src/random.cpp b/src/random.cpp index 12fe33ce3c..7b2c6319e2 100644 --- a/src/random.cpp +++ b/src/random.cpp @@ -40,9 +40,9 @@ #include "mutex.hpp" #include "macros.hpp" -#if defined (ZMQ_USE_TWEETNACL) +#if defined(ZMQ_USE_TWEETNACL) #include "tweetnacl.h" -#elif defined (ZMQ_USE_LIBSODIUM) +#elif defined(ZMQ_USE_LIBSODIUM) #include "sodium.h" #endif @@ -88,8 +88,9 @@ static zmq::mutex_t random_sync; void zmq::random_open (void) { -#if defined (ZMQ_USE_LIBSODIUM) || \ - (defined (ZMQ_USE_TWEETNACL) && !defined (ZMQ_HAVE_WINDOWS) && !defined (ZMQ_HAVE_GETRANDOM)) +#if defined(ZMQ_USE_LIBSODIUM) \ + || (defined(ZMQ_USE_TWEETNACL) && !defined(ZMQ_HAVE_WINDOWS) \ + && !defined(ZMQ_HAVE_GETRANDOM)) scoped_lock_t locker (random_sync); if (random_refcount == 0) { @@ -105,8 +106,9 @@ void zmq::random_open (void) void zmq::random_close (void) { -#if defined (ZMQ_USE_LIBSODIUM) || \ - (defined (ZMQ_USE_TWEETNACL) && !defined (ZMQ_HAVE_WINDOWS) && !defined (ZMQ_HAVE_GETRANDOM)) +#if defined(ZMQ_USE_LIBSODIUM) \ + || (defined(ZMQ_USE_TWEETNACL) && !defined(ZMQ_HAVE_WINDOWS) \ + && !defined(ZMQ_HAVE_GETRANDOM)) scoped_lock_t locker (random_sync); --random_refcount; @@ -115,4 +117,3 @@ void zmq::random_close (void) } #endif } - diff --git a/src/random.hpp b/src/random.hpp index 11d9cedb77..0b57adb961 100644 --- a/src/random.hpp +++ b/src/random.hpp @@ -34,19 +34,18 @@ namespace zmq { - - // Seeds the random number generator. - void seed_random (); - - // Generates random value. - uint32_t generate_random (); - - // [De-]Initialise crypto library, if needed. - // Serialised and refcounted, so that it can be called - // from multiple threads, each with its own context, and from - // the various zmq_utils curve functions safely. - void random_open (); - void random_close (); +// Seeds the random number generator. +void seed_random (); + +// Generates random value. +uint32_t generate_random (); + +// [De-]Initialise crypto library, if needed. +// Serialised and refcounted, so that it can be called +// from multiple threads, each with its own context, and from +// the various zmq_utils curve functions safely. +void random_open (); +void random_close (); } #endif diff --git a/src/raw_decoder.cpp b/src/raw_decoder.cpp index b9a8d5c386..7cb2e67ebc 100644 --- a/src/raw_decoder.cpp +++ b/src/raw_decoder.cpp @@ -34,8 +34,7 @@ #include "raw_decoder.hpp" #include "err.hpp" -zmq::raw_decoder_t::raw_decoder_t (size_t bufsize_) : - allocator( bufsize_, 1 ) +zmq::raw_decoder_t::raw_decoder_t (size_t bufsize_) : allocator (bufsize_, 1) { int rc = in_progress.init (); errno_assert (rc == 0); @@ -49,23 +48,24 @@ zmq::raw_decoder_t::~raw_decoder_t () void zmq::raw_decoder_t::get_buffer (unsigned char **data_, size_t *size_) { - *data_ = allocator.allocate(); - *size_ = allocator.size(); + *data_ = allocator.allocate (); + *size_ = allocator.size (); } -int zmq::raw_decoder_t::decode (const uint8_t *data_, size_t size_, +int zmq::raw_decoder_t::decode (const uint8_t *data_, + size_t size_, size_t &bytes_used_) { - int rc = in_progress.init ((unsigned char*)data_, size_, - shared_message_memory_allocator::call_dec_ref, - allocator.buffer (), - allocator.provide_content ()); + int rc = + in_progress.init ((unsigned char *) data_, size_, + shared_message_memory_allocator::call_dec_ref, + allocator.buffer (), allocator.provide_content ()); // if the buffer serves as memory for a zero-copy message, release it // and allocate a new buffer in get_buffer for the next decode if (in_progress.is_zcmsg ()) { - allocator.advance_content(); - allocator.release(); + allocator.advance_content (); + allocator.release (); } errno_assert (rc != -1); diff --git a/src/raw_decoder.hpp b/src/raw_decoder.hpp index 5f08572eb3..81759b223c 100644 --- a/src/raw_decoder.hpp +++ b/src/raw_decoder.hpp @@ -38,37 +38,33 @@ namespace zmq { +// Decoder for 0MQ v1 framing protocol. Converts data stream into messages. - // Decoder for 0MQ v1 framing protocol. Converts data stream into messages. - - class raw_decoder_t : public i_decoder - { - public: - - raw_decoder_t (size_t bufsize_); - virtual ~raw_decoder_t (); - - // i_decoder interface. +class raw_decoder_t : public i_decoder +{ + public: + raw_decoder_t (size_t bufsize_); + virtual ~raw_decoder_t (); - virtual void get_buffer (unsigned char **data_, size_t *size_); + // i_decoder interface. - virtual int decode (const unsigned char *data_, size_t size_, - size_t &processed); + virtual void get_buffer (unsigned char **data_, size_t *size_); - virtual msg_t *msg () { return &in_progress; } + virtual int + decode (const unsigned char *data_, size_t size_, size_t &processed); - virtual void resize_buffer(size_t) {} + virtual msg_t *msg () { return &in_progress; } - private: - msg_t in_progress; + virtual void resize_buffer (size_t) {} - shared_message_memory_allocator allocator; + private: + msg_t in_progress; - raw_decoder_t (const raw_decoder_t&); - void operator = (const raw_decoder_t&); - }; + shared_message_memory_allocator allocator; + raw_decoder_t (const raw_decoder_t &); + void operator= (const raw_decoder_t &); +}; } #endif - diff --git a/src/raw_encoder.cpp b/src/raw_encoder.cpp index ae35cb53de..2c0c58c0e7 100644 --- a/src/raw_encoder.cpp +++ b/src/raw_encoder.cpp @@ -34,7 +34,7 @@ #include "wire.hpp" zmq::raw_encoder_t::raw_encoder_t (size_t bufsize_) : - encoder_base_t (bufsize_) + encoder_base_t (bufsize_) { // Write 0 bytes to the batch and go to message_ready state. next_step (NULL, 0, &raw_encoder_t::raw_message_ready, true); @@ -47,5 +47,5 @@ zmq::raw_encoder_t::~raw_encoder_t () void zmq::raw_encoder_t::raw_message_ready () { next_step (in_progress->data (), in_progress->size (), - &raw_encoder_t::raw_message_ready, true); + &raw_encoder_t::raw_message_ready, true); } diff --git a/src/raw_encoder.hpp b/src/raw_encoder.hpp index f55e131c7b..8606ea61e5 100644 --- a/src/raw_encoder.hpp +++ b/src/raw_encoder.hpp @@ -41,24 +41,20 @@ namespace zmq { +// Encoder for 0MQ framing protocol. Converts messages into data batches. - // Encoder for 0MQ framing protocol. Converts messages into data batches. - - class raw_encoder_t : public encoder_base_t - { - public: - - raw_encoder_t (size_t bufsize_); - ~raw_encoder_t (); - - private: +class raw_encoder_t : public encoder_base_t +{ + public: + raw_encoder_t (size_t bufsize_); + ~raw_encoder_t (); - void raw_message_ready (); + private: + void raw_message_ready (); - raw_encoder_t (const raw_encoder_t&); - const raw_encoder_t &operator = (const raw_encoder_t&); - }; + raw_encoder_t (const raw_encoder_t &); + const raw_encoder_t &operator= (const raw_encoder_t &); +}; } #endif - diff --git a/src/reaper.cpp b/src/reaper.cpp index 5c53e1d06b..5dcf14a74a 100644 --- a/src/reaper.cpp +++ b/src/reaper.cpp @@ -35,7 +35,7 @@ zmq::reaper_t::reaper_t (class ctx_t *ctx_, uint32_t tid_) : object_t (ctx_, tid_), - mailbox_handle((poller_t::handle_t)NULL), + mailbox_handle ((poller_t::handle_t) NULL), poller (NULL), sockets (0), terminating (false) @@ -52,13 +52,13 @@ zmq::reaper_t::reaper_t (class ctx_t *ctx_, uint32_t tid_) : } #ifdef HAVE_FORK - pid = getpid(); + pid = getpid (); #endif } zmq::reaper_t::~reaper_t () { - LIBZMQ_DELETE(poller); + LIBZMQ_DELETE (poller); } zmq::mailbox_t *zmq::reaper_t::get_mailbox () @@ -85,8 +85,7 @@ void zmq::reaper_t::in_event () { while (true) { #ifdef HAVE_FORK - if (unlikely(pid != getpid())) - { + if (unlikely (pid != getpid ())) { //printf("zmq::reaper_t::in_event return in child process %d\n", (int)getpid()); return; } diff --git a/src/reaper.hpp b/src/reaper.hpp index a1fbbc2271..1d4f127334 100644 --- a/src/reaper.hpp +++ b/src/reaper.hpp @@ -37,58 +37,54 @@ namespace zmq { +class ctx_t; +class socket_base_t; - class ctx_t; - class socket_base_t; - - class reaper_t : public object_t, public i_poll_events - { - public: - - reaper_t (zmq::ctx_t *ctx_, uint32_t tid_); - ~reaper_t (); - - mailbox_t *get_mailbox (); +class reaper_t : public object_t, public i_poll_events +{ + public: + reaper_t (zmq::ctx_t *ctx_, uint32_t tid_); + ~reaper_t (); - void start (); - void stop (); + mailbox_t *get_mailbox (); - // i_poll_events implementation. - void in_event (); - void out_event (); - void timer_event (int id_); + void start (); + void stop (); - private: + // i_poll_events implementation. + void in_event (); + void out_event (); + void timer_event (int id_); - // Command handlers. - void process_stop (); - void process_reap (zmq::socket_base_t *socket_); - void process_reaped (); + private: + // Command handlers. + void process_stop (); + void process_reap (zmq::socket_base_t *socket_); + void process_reaped (); - // Reaper thread accesses incoming commands via this mailbox. - mailbox_t mailbox; + // Reaper thread accesses incoming commands via this mailbox. + mailbox_t mailbox; - // Handle associated with mailbox' file descriptor. - poller_t::handle_t mailbox_handle; + // Handle associated with mailbox' file descriptor. + poller_t::handle_t mailbox_handle; - // I/O multiplexing is performed using a poller object. - poller_t *poller; + // I/O multiplexing is performed using a poller object. + poller_t *poller; - // Number of sockets being reaped at the moment. - int sockets; + // Number of sockets being reaped at the moment. + int sockets; - // If true, we were already asked to terminate. - bool terminating; + // If true, we were already asked to terminate. + bool terminating; - reaper_t (const reaper_t&); - const reaper_t &operator = (const reaper_t&); + reaper_t (const reaper_t &); + const reaper_t &operator= (const reaper_t &); #ifdef HAVE_FORK - // the process that created this context. Used to detect forking. - pid_t pid; + // the process that created this context. Used to detect forking. + pid_t pid; #endif - }; - +}; } #endif diff --git a/src/rep.cpp b/src/rep.cpp index b3a41bfabb..1193a0989a 100644 --- a/src/rep.cpp +++ b/src/rep.cpp @@ -92,8 +92,7 @@ int zmq::rep_t::xrecv (msg_t *msg_) if (bottom) break; - } - else { + } else { // If the traceback stack is malformed, discard anything // already sent to pipe (we're at end of invalid message). rc = router_t::rollback (); @@ -106,7 +105,7 @@ int zmq::rep_t::xrecv (msg_t *msg_) // Get next message part to return to the user. int rc = router_t::xrecv (msg_); if (rc != 0) - return rc; + return rc; // If whole request is read, flip the FSM to reply-sending state. if (!(msg_->flags () & msg_t::more)) { diff --git a/src/rep.hpp b/src/rep.hpp index 9874af909c..0985612f34 100644 --- a/src/rep.hpp +++ b/src/rep.hpp @@ -34,40 +34,35 @@ namespace zmq { +class ctx_t; +class msg_t; +class io_thread_t; +class socket_base_t; - class ctx_t; - class msg_t; - class io_thread_t; - class socket_base_t; - - class rep_t : public router_t - { - public: - - rep_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); - ~rep_t (); - - // Overrides of functions from socket_base_t. - int xsend (zmq::msg_t *msg_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - bool xhas_out (); - - private: - - // If true, we are in process of sending the reply. If false we are - // in process of receiving a request. - bool sending_reply; - - // If true, we are starting to receive a request. The beginning - // of the request is the backtrace stack. - bool request_begins; - - rep_t (const rep_t&); - const rep_t &operator = (const rep_t&); - - }; - +class rep_t : public router_t +{ + public: + rep_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); + ~rep_t (); + + // Overrides of functions from socket_base_t. + int xsend (zmq::msg_t *msg_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + bool xhas_out (); + + private: + // If true, we are in process of sending the reply. If false we are + // in process of receiving a request. + bool sending_reply; + + // If true, we are starting to receive a request. The beginning + // of the request is the backtrace stack. + bool request_begins; + + rep_t (const rep_t &); + const rep_t &operator= (const rep_t &); +}; } #endif diff --git a/src/req.cpp b/src/req.cpp index 8889b0ff7f..4342048dd9 100644 --- a/src/req.cpp +++ b/src/req.cpp @@ -36,13 +36,12 @@ #include "random.hpp" #include "likely.hpp" -extern "C" +extern "C" { +static void free_id (void *data, void *hint) { - static void free_id (void *data, void *hint) - { - LIBZMQ_UNUSED (hint); - free (data); - } + LIBZMQ_UNUSED (hint); + free (data); +} } zmq::req_t::req_t (class ctx_t *parent_, uint32_t tid_, int sid_) : @@ -89,8 +88,8 @@ int zmq::req_t::xsend (msg_t *msg_) *request_id_copy = request_id; msg_t id; - int rc = id.init_data (request_id_copy, sizeof (uint32_t), - free_id, NULL); + int rc = + id.init_data (request_id_copy, sizeof (uint32_t), free_id, NULL); errno_assert (rc == 0); id.set_flags (msg_t::more); @@ -158,9 +157,10 @@ int zmq::req_t::xrecv (msg_t *msg_) if (rc != 0) return rc; - if (unlikely (!(msg_->flags () & msg_t::more) || - msg_->size () != sizeof (request_id) || - *static_cast (msg_->data ()) != request_id)) { + if (unlikely (!(msg_->flags () & msg_t::more) + || msg_->size () != sizeof (request_id) + || *static_cast (msg_->data ()) + != request_id)) { // Skip the remaining frames and try the next message while (msg_->flags () & msg_t::more) { rc = recv_reply_pipe (msg_); @@ -219,7 +219,9 @@ bool zmq::req_t::xhas_out () return dealer_t::xhas_out (); } -int zmq::req_t::xsetsockopt (int option_, const void *optval_, size_t optvallen_) +int zmq::req_t::xsetsockopt (int option_, + const void *optval_, + size_t optvallen_) { bool is_int = (optvallen_ == sizeof (int)); int value = 0; @@ -267,9 +269,11 @@ int zmq::req_t::recv_reply_pipe (msg_t *msg_) } } -zmq::req_session_t::req_session_t (io_thread_t *io_thread_, bool connect_, - socket_base_t *socket_, const options_t &options_, - address_t *addr_) : +zmq::req_session_t::req_session_t (io_thread_t *io_thread_, + bool connect_, + socket_base_t *socket_, + const options_t &options_, + address_t *addr_) : session_base_t (io_thread_, connect_, socket_, options_, addr_), state (bottom) { @@ -282,35 +286,34 @@ zmq::req_session_t::~req_session_t () int zmq::req_session_t::push_msg (msg_t *msg_) { switch (state) { - case bottom: - if (msg_->flags () == msg_t::more) { - // In case option ZMQ_CORRELATE is on, allow request_id to be - // transfered as first frame (would be too cumbersome to check - // whether the option is actually on or not). - if (msg_->size () == sizeof (uint32_t)) { - state = request_id; - return session_base_t::push_msg (msg_); + case bottom: + if (msg_->flags () == msg_t::more) { + // In case option ZMQ_CORRELATE is on, allow request_id to be + // transfered as first frame (would be too cumbersome to check + // whether the option is actually on or not). + if (msg_->size () == sizeof (uint32_t)) { + state = request_id; + return session_base_t::push_msg (msg_); + } else if (msg_->size () == 0) { + state = body; + return session_base_t::push_msg (msg_); + } } - else if (msg_->size () == 0) { + break; + case request_id: + if (msg_->flags () == msg_t::more && msg_->size () == 0) { state = body; return session_base_t::push_msg (msg_); } - } - break; - case request_id: - if (msg_->flags () == msg_t::more && msg_->size () == 0) { - state = body; - return session_base_t::push_msg (msg_); - } - break; - case body: - if (msg_->flags () == msg_t::more) - return session_base_t::push_msg (msg_); - if (msg_->flags () == 0) { - state = bottom; - return session_base_t::push_msg (msg_); - } - break; + break; + case body: + if (msg_->flags () == msg_t::more) + return session_base_t::push_msg (msg_); + if (msg_->flags () == 0) { + state = bottom; + return session_base_t::push_msg (msg_); + } + break; } errno = EFAULT; return -1; diff --git a/src/req.hpp b/src/req.hpp index db3f011d40..226d42b7cd 100644 --- a/src/req.hpp +++ b/src/req.hpp @@ -35,87 +35,83 @@ namespace zmq { +class ctx_t; +class msg_t; +class io_thread_t; +class socket_base_t; - class ctx_t; - class msg_t; - class io_thread_t; - class socket_base_t; - - class req_t : public dealer_t - { - public: - - req_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~req_t (); - - // Overrides of functions from socket_base_t. - int xsend (zmq::msg_t *msg_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - bool xhas_out (); - int xsetsockopt (int option_, const void *optval_, size_t optvallen_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - protected: - - // Receive only from the pipe the request was sent to, discarding - // frames from other pipes. - int recv_reply_pipe (zmq::msg_t *msg_); - - private: - - // If true, request was already sent and reply wasn't received yet or - // was received partially. - bool receiving_reply; - - // If true, we are starting to send/recv a message. The first part - // of the message must be empty message part (backtrace stack bottom). - bool message_begins; - - // The pipe the request was sent to and where the reply is expected. - zmq::pipe_t *reply_pipe; - - // Whether request id frames shall be sent and expected. - bool request_id_frames_enabled; - - // The current request id. It is incremented every time before a new - // request is sent. - uint32_t request_id; - - // If false, send() will reset its internal state and terminate the - // reply_pipe's connection instead of failing if a previous request is - // still pending. - bool strict; - - req_t (const req_t&); - const req_t &operator = (const req_t&); - }; - - class req_session_t : public session_base_t +class req_t : public dealer_t +{ + public: + req_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~req_t (); + + // Overrides of functions from socket_base_t. + int xsend (zmq::msg_t *msg_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + bool xhas_out (); + int xsetsockopt (int option_, const void *optval_, size_t optvallen_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + protected: + // Receive only from the pipe the request was sent to, discarding + // frames from other pipes. + int recv_reply_pipe (zmq::msg_t *msg_); + + private: + // If true, request was already sent and reply wasn't received yet or + // was received partially. + bool receiving_reply; + + // If true, we are starting to send/recv a message. The first part + // of the message must be empty message part (backtrace stack bottom). + bool message_begins; + + // The pipe the request was sent to and where the reply is expected. + zmq::pipe_t *reply_pipe; + + // Whether request id frames shall be sent and expected. + bool request_id_frames_enabled; + + // The current request id. It is incremented every time before a new + // request is sent. + uint32_t request_id; + + // If false, send() will reset its internal state and terminate the + // reply_pipe's connection instead of failing if a previous request is + // still pending. + bool strict; + + req_t (const req_t &); + const req_t &operator= (const req_t &); +}; + +class req_session_t : public session_base_t +{ + public: + req_session_t (zmq::io_thread_t *io_thread_, + bool connect_, + zmq::socket_base_t *socket_, + const options_t &options_, + address_t *addr_); + ~req_session_t (); + + // Overrides of the functions from session_base_t. + int push_msg (msg_t *msg_); + void reset (); + + private: + enum { - public: - - req_session_t (zmq::io_thread_t *io_thread_, bool connect_, - zmq::socket_base_t *socket_, const options_t &options_, - address_t *addr_); - ~req_session_t (); - - // Overrides of the functions from session_base_t. - int push_msg (msg_t *msg_); - void reset (); - - private: - - enum { - bottom, - request_id, - body - } state; - - req_session_t (const req_session_t&); - const req_session_t &operator = (const req_session_t&); - }; - + bottom, + request_id, + body + } state; + + req_session_t (const req_session_t &); + const req_session_t &operator= (const req_session_t &); +}; } #endif diff --git a/src/router.cpp b/src/router.cpp index 3e7106bd14..f31c921ee3 100644 --- a/src/router.cpp +++ b/src/router.cpp @@ -62,7 +62,8 @@ zmq::router_t::router_t (class ctx_t *parent_, uint32_t tid_, int sid_) : zmq::router_t::~router_t () { - zmq_assert (anonymous_pipes.empty ());; + zmq_assert (anonymous_pipes.empty ()); + ; zmq_assert (outpipes.empty ()); prefetched_id.close (); prefetched_msg.close (); @@ -94,12 +95,14 @@ void zmq::router_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_) anonymous_pipes.insert (pipe_); } -int zmq::router_t::xsetsockopt (int option_, const void *optval_, - size_t optvallen_) +int zmq::router_t::xsetsockopt (int option_, + const void *optval_, + size_t optvallen_) { bool is_int = (optvallen_ == sizeof (int)); int value = 0; - if (is_int) memcpy(&value, optval_, sizeof (int)); + if (is_int) + memcpy (&value, optval_, sizeof (int)); switch (option_) { case ZMQ_CONNECT_ROUTING_ID: @@ -151,7 +154,7 @@ int zmq::router_t::xsetsockopt (int option_, const void *optval_, void zmq::router_t::xpipe_terminated (pipe_t *pipe_) { - std::set ::iterator it = anonymous_pipes.find (pipe_); + std::set::iterator it = anonymous_pipes.find (pipe_); if (it != anonymous_pipes.end ()) anonymous_pipes.erase (it); else { @@ -167,7 +170,7 @@ void zmq::router_t::xpipe_terminated (pipe_t *pipe_) void zmq::router_t::xread_activated (pipe_t *pipe_) { - std::set ::iterator it = anonymous_pipes.find (pipe_); + std::set::iterator it = anonymous_pipes.find (pipe_); if (it == anonymous_pipes.end ()) fq.activated (pipe_); else { @@ -202,21 +205,20 @@ int zmq::router_t::xsend (msg_t *msg_) // then just silently ignore it. // TODO: The connections should be killed instead. if (msg_->flags () & msg_t::more) { - more_out = true; // Find the pipe associated with the routing id stored in the prefix. // If there's no such pipe just silently ignore the message, unless // router_mandatory is set. - blob_t routing_id ((unsigned char*) msg_->data (), msg_->size (), - zmq::reference_tag_t()); + blob_t routing_id ((unsigned char *) msg_->data (), msg_->size (), + zmq::reference_tag_t ()); outpipes_t::iterator it = outpipes.find (routing_id); if (it != outpipes.end ()) { current_out = it->second.pipe; // Check whether pipe is closed or not - if (!current_out->check_write()) { + if (!current_out->check_write ()) { // Check whether pipe is full or not bool pipe_full = !current_out->check_hwm (); it->second.active = false; @@ -231,9 +233,7 @@ int zmq::router_t::xsend (msg_t *msg_) return -1; } } - } - else - if (mandatory) { + } else if (mandatory) { more_out = false; errno = EHOSTUNREACH; return -1; @@ -256,11 +256,10 @@ int zmq::router_t::xsend (msg_t *msg_) // Push the message into the pipe. If there's no out pipe, just drop it. if (current_out) { - // Close the remote connection if user has asked to do so // by sending zero length message. // Pending messages in the pipe will be dropped (on receiving term- ack) - if (raw_socket && msg_->size() == 0) { + if (raw_socket && msg_->size () == 0) { current_out->terminate (false); int rc = msg_->close (); errno_assert (rc == 0); @@ -280,13 +279,12 @@ int zmq::router_t::xsend (msg_t *msg_) current_out->rollback (); current_out = NULL; } else { - if (!more_out) { - current_out->flush (); - current_out = NULL; - } + if (!more_out) { + current_out->flush (); + current_out = NULL; + } } - } - else { + } else { int rc = msg_->close (); errno_assert (rc == 0); } @@ -305,8 +303,7 @@ int zmq::router_t::xrecv (msg_t *msg_) int rc = msg_->move (prefetched_id); errno_assert (rc == 0); routing_id_sent = true; - } - else { + } else { int rc = msg_->move (prefetched_msg); errno_assert (rc == 0); prefetched = false; @@ -348,8 +345,7 @@ int zmq::router_t::xrecv (msg_t *msg_) } current_in = NULL; } - } - else { + } else { // We are at the beginning of a message. // Keep the message part we have in the prefetch buffer // and return the ID of the peer instead. @@ -363,8 +359,8 @@ int zmq::router_t::xrecv (msg_t *msg_) errno_assert (rc == 0); memcpy (msg_->data (), routing_id.data (), routing_id.size ()); msg_->set_flags (msg_t::more); - if (prefetched_msg.metadata()) - msg_->set_metadata(prefetched_msg.metadata()); + if (prefetched_msg.metadata ()) + msg_->set_metadata (prefetched_msg.metadata ()); routing_id_sent = true; } @@ -428,13 +424,13 @@ bool zmq::router_t::xhas_out () // MANDATORY is set). Whether actual attempt to write succeeds depends // on whitch pipe the message is going to be routed to. - if(!mandatory) + if (!mandatory) return true; bool has_out = false; outpipes_t::iterator it; for (it = outpipes.begin (); it != outpipes.end (); ++it) - has_out |= it->second.pipe->check_hwm(); + has_out |= it->second.pipe->check_hwm (); return has_out; } @@ -471,23 +467,21 @@ bool zmq::router_t::identify_peer (pipe_t *pipe_) bool ok; blob_t routing_id; - if (connect_routing_id.length()) { - routing_id.set ((unsigned char*)connect_routing_id.c_str(), - connect_routing_id.length()); - connect_routing_id.clear(); - outpipes_t::iterator it = outpipes.find(routing_id); - if (it != outpipes.end()) - zmq_assert(false); // Not allowed to duplicate an existing rid - } - else - if (options.raw_socket) { // Always assign an integral routing id for raw-socket - unsigned char buf [5]; - buf [0] = 0; + if (connect_routing_id.length ()) { + routing_id.set ((unsigned char *) connect_routing_id.c_str (), + connect_routing_id.length ()); + connect_routing_id.clear (); + outpipes_t::iterator it = outpipes.find (routing_id); + if (it != outpipes.end ()) + zmq_assert (false); // Not allowed to duplicate an existing rid + } else if ( + options + .raw_socket) { // Always assign an integral routing id for raw-socket + unsigned char buf[5]; + buf[0] = 0; put_uint32 (buf + 1, next_integral_routing_id++); routing_id.set (buf, sizeof buf); - } - else - if (!options.raw_socket) { + } else if (!options.raw_socket) { // Pick up handshake cases and also case where next integral routing id is set msg.init (); ok = pipe_->read (&msg); @@ -496,14 +490,13 @@ bool zmq::router_t::identify_peer (pipe_t *pipe_) if (msg.size () == 0) { // Fall back on the auto-generation - unsigned char buf [5]; - buf [0] = 0; + unsigned char buf[5]; + buf[0] = 0; put_uint32 (buf + 1, next_integral_routing_id++); routing_id.set (buf, sizeof buf); msg.close (); - } - else { - routing_id.set ((unsigned char*) msg.data (), msg.size ()); + } else { + routing_id.set ((unsigned char *) msg.data (), msg.size ()); outpipes_t::iterator it = outpipes.find (routing_id); msg.close (); @@ -515,17 +508,20 @@ bool zmq::router_t::identify_peer (pipe_t *pipe_) // We will allow the new connection to take over this // routing id. Temporarily assign a new routing id to the // existing pipe so we can terminate it asynchronously. - unsigned char buf [5]; - buf [0] = 0; + unsigned char buf[5]; + buf[0] = 0; put_uint32 (buf + 1, next_integral_routing_id++); blob_t new_routing_id (buf, sizeof buf); - it->second.pipe->set_router_socket_routing_id (new_routing_id); - outpipe_t existing_outpipe = - {it->second.pipe, it->second.active}; + it->second.pipe->set_router_socket_routing_id ( + new_routing_id); + outpipe_t existing_outpipe = {it->second.pipe, + it->second.active}; - ok = outpipes.ZMQ_MAP_INSERT_OR_EMPLACE ( - ZMQ_MOVE(new_routing_id), existing_outpipe).second; + ok = outpipes + .ZMQ_MAP_INSERT_OR_EMPLACE ( + ZMQ_MOVE (new_routing_id), existing_outpipe) + .second; zmq_assert (ok); // Remove the existing routing id entry to allow the new @@ -544,7 +540,8 @@ bool zmq::router_t::identify_peer (pipe_t *pipe_) pipe_->set_router_socket_routing_id (routing_id); // Add the record into output pipes lookup table outpipe_t outpipe = {pipe_, true}; - ok = outpipes.ZMQ_MAP_INSERT_OR_EMPLACE (ZMQ_MOVE(routing_id), outpipe).second; + ok = outpipes.ZMQ_MAP_INSERT_OR_EMPLACE (ZMQ_MOVE (routing_id), outpipe) + .second; zmq_assert (ok); return true; diff --git a/src/router.hpp b/src/router.hpp index 1a7bfcd6b7..7e8ce29445 100644 --- a/src/router.hpp +++ b/src/router.hpp @@ -41,107 +41,101 @@ namespace zmq { +class ctx_t; +class pipe_t; - class ctx_t; - class pipe_t; - - // TODO: This class uses O(n) scheduling. Rewrite it to use O(1) algorithm. - class router_t : - public socket_base_t - { - public: - - router_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); - ~router_t (); - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsetsockopt (int option_, const void *optval_, size_t optvallen_); - int xsend (zmq::msg_t *msg_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - bool xhas_out (); - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - int get_peer_state (const void *identity, size_t identity_size) const; - - protected: - - // Rollback any message parts that were sent but not yet flushed. - int rollback (); - const blob_t &get_credential () const; +// TODO: This class uses O(n) scheduling. Rewrite it to use O(1) algorithm. +class router_t : public socket_base_t +{ + public: + router_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); + ~router_t (); - private: + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsetsockopt (int option_, const void *optval_, size_t optvallen_); + int xsend (zmq::msg_t *msg_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + bool xhas_out (); + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + int get_peer_state (const void *identity, size_t identity_size) const; - // Receive peer id and update lookup map - bool identify_peer (pipe_t *pipe_); + protected: + // Rollback any message parts that were sent but not yet flushed. + int rollback (); + const blob_t &get_credential () const; - // Fair queueing object for inbound pipes. - fq_t fq; + private: + // Receive peer id and update lookup map + bool identify_peer (pipe_t *pipe_); - // True iff there is a message held in the pre-fetch buffer. - bool prefetched; + // Fair queueing object for inbound pipes. + fq_t fq; - // If true, the receiver got the message part with - // the peer's identity. - bool routing_id_sent; + // True iff there is a message held in the pre-fetch buffer. + bool prefetched; - // Holds the prefetched identity. - msg_t prefetched_id; + // If true, the receiver got the message part with + // the peer's identity. + bool routing_id_sent; - // Holds the prefetched message. - msg_t prefetched_msg; + // Holds the prefetched identity. + msg_t prefetched_id; - // The pipe we are currently reading from - zmq::pipe_t *current_in; + // Holds the prefetched message. + msg_t prefetched_msg; - // Should current_in should be terminate after all parts received? - bool terminate_current_in; + // The pipe we are currently reading from + zmq::pipe_t *current_in; - // If true, more incoming message parts are expected. - bool more_in; + // Should current_in should be terminate after all parts received? + bool terminate_current_in; - struct outpipe_t - { - zmq::pipe_t *pipe; - bool active; - }; + // If true, more incoming message parts are expected. + bool more_in; - // We keep a set of pipes that have not been identified yet. - std::set anonymous_pipes; + struct outpipe_t + { + zmq::pipe_t *pipe; + bool active; + }; - // Outbound pipes indexed by the peer IDs. - typedef std::map outpipes_t; - outpipes_t outpipes; + // We keep a set of pipes that have not been identified yet. + std::set anonymous_pipes; - // The pipe we are currently writing to. - zmq::pipe_t *current_out; + // Outbound pipes indexed by the peer IDs. + typedef std::map outpipes_t; + outpipes_t outpipes; - // If true, more outgoing message parts are expected. - bool more_out; + // The pipe we are currently writing to. + zmq::pipe_t *current_out; - // Routing IDs are generated. It's a simple increment and wrap-over - // algorithm. This value is the next ID to use (if not used already). - uint32_t next_integral_routing_id; + // If true, more outgoing message parts are expected. + bool more_out; - // If true, report EAGAIN to the caller instead of silently dropping - // the message targeting an unknown peer. - bool mandatory; - bool raw_socket; + // Routing IDs are generated. It's a simple increment and wrap-over + // algorithm. This value is the next ID to use (if not used already). + uint32_t next_integral_routing_id; - // if true, send an empty message to every connected router peer - bool probe_router; + // If true, report EAGAIN to the caller instead of silently dropping + // the message targeting an unknown peer. + bool mandatory; + bool raw_socket; - // If true, the router will reassign an identity upon encountering a - // name collision. The new pipe will take the identity, the old pipe - // will be terminated. - bool handover; + // if true, send an empty message to every connected router peer + bool probe_router; - router_t (const router_t&); - const router_t &operator = (const router_t&); - }; + // If true, the router will reassign an identity upon encountering a + // name collision. The new pipe will take the identity, the old pipe + // will be terminated. + bool handover; + router_t (const router_t &); + const router_t &operator= (const router_t &); +}; } #endif diff --git a/src/scatter.hpp b/src/scatter.hpp index 8c65148092..2227920588 100644 --- a/src/scatter.hpp +++ b/src/scatter.hpp @@ -36,38 +36,32 @@ namespace zmq { +class ctx_t; +class pipe_t; +class msg_t; +class io_thread_t; - class ctx_t; - class pipe_t; - class msg_t; - class io_thread_t; - - class scatter_t : - public socket_base_t - { - public: - - scatter_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~scatter_t (); - - protected: - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsend (zmq::msg_t *msg_); - bool xhas_out (); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - - // Load balancer managing the outbound pipes. - lb_t lb; - - scatter_t (const scatter_t&); - const scatter_t &operator = (const scatter_t&); - }; - +class scatter_t : public socket_base_t +{ + public: + scatter_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~scatter_t (); + + protected: + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsend (zmq::msg_t *msg_); + bool xhas_out (); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + // Load balancer managing the outbound pipes. + lb_t lb; + + scatter_t (const scatter_t &); + const scatter_t &operator= (const scatter_t &); +}; } #endif diff --git a/src/select.cpp b/src/select.cpp index 1e09728e0d..c15ba05b81 100644 --- a/src/select.cpp +++ b/src/select.cpp @@ -60,7 +60,7 @@ zmq::select_t::select_t (const zmq::ctx_t &ctx_) : { #if defined ZMQ_HAVE_WINDOWS for (size_t i = 0; i < fd_family_cache_size; ++i) - fd_family_cache [i] = std::make_pair (retired_fd, 0); + fd_family_cache[i] = std::make_pair (retired_fd, 0); #endif } @@ -81,7 +81,7 @@ zmq::select_t::handle_t zmq::select_t::add_fd (fd_t fd_, i_poll_events *events_) #if defined ZMQ_HAVE_WINDOWS u_short family = get_fd_family (fd_); wsa_assert (family != AF_UNSPEC); - family_entry_t &family_entry = family_entries [family]; + family_entry_t &family_entry = family_entries[family]; #endif family_entry.fd_entries.push_back (fd_entry); FD_SET (fd_, &family_entry.fds_set.error); @@ -116,7 +116,7 @@ void zmq::select_t::trigger_events (const fd_entries_t &fd_entries_, // Size is cached to avoid iteration through recently added descriptors. for (fd_entries_t::size_type i = 0, size = fd_entries_.size (); i < size && event_count_ > 0; ++i) { - const fd_entry_t ¤t_fd_entry = fd_entries_ [i]; + const fd_entry_t ¤t_fd_entry = fd_entries_[i]; if (is_retired_fd (current_fd_entry)) continue; @@ -223,7 +223,7 @@ void zmq::select_t::set_pollin (handle_t handle_) #if defined ZMQ_HAVE_WINDOWS u_short family = get_fd_family (handle_); wsa_assert (family != AF_UNSPEC); - family_entry_t &family_entry = family_entries [family]; + family_entry_t &family_entry = family_entries[family]; #endif FD_SET (handle_, &family_entry.fds_set.read); } @@ -233,7 +233,7 @@ void zmq::select_t::reset_pollin (handle_t handle_) #if defined ZMQ_HAVE_WINDOWS u_short family = get_fd_family (handle_); wsa_assert (family != AF_UNSPEC); - family_entry_t &family_entry = family_entries [family]; + family_entry_t &family_entry = family_entries[family]; #endif FD_CLR (handle_, &family_entry.fds_set.read); } @@ -243,7 +243,7 @@ void zmq::select_t::set_pollout (handle_t handle_) #if defined ZMQ_HAVE_WINDOWS u_short family = get_fd_family (handle_); wsa_assert (family != AF_UNSPEC); - family_entry_t &family_entry = family_entries [family]; + family_entry_t &family_entry = family_entries[family]; #endif FD_SET (handle_, &family_entry.fds_set.write); } @@ -253,7 +253,7 @@ void zmq::select_t::reset_pollout (handle_t handle_) #if defined ZMQ_HAVE_WINDOWS u_short family = get_fd_family (handle_); wsa_assert (family != AF_UNSPEC); - family_entry_t &family_entry = family_entries [family]; + family_entry_t &family_entry = family_entries[family]; #endif FD_CLR (handle_, &family_entry.fds_set.write); } @@ -332,18 +332,18 @@ void zmq::select_t::loop () if (FD_ISSET (fd, &family_entry.fds_set.read) && FD_ISSET (fd, &family_entry.fds_set.write)) rc = - WSAEventSelect (fd, wsa_events.events [3], + WSAEventSelect (fd, wsa_events.events[3], FD_READ | FD_ACCEPT | FD_CLOSE | FD_WRITE | FD_CONNECT | FD_OOB); else if (FD_ISSET (fd, &family_entry.fds_set.read)) - rc = WSAEventSelect (fd, wsa_events.events [0], + rc = WSAEventSelect (fd, wsa_events.events[0], FD_READ | FD_ACCEPT | FD_CLOSE | FD_OOB); else if (FD_ISSET (fd, &family_entry.fds_set.write)) - rc = WSAEventSelect (fd, wsa_events.events [1], + rc = WSAEventSelect (fd, wsa_events.events[1], FD_WRITE | FD_CONNECT | FD_OOB); else if (FD_ISSET (fd, &family_entry.fds_set.error)) - rc = WSAEventSelect (fd, wsa_events.events [2], FD_OOB); + rc = WSAEventSelect (fd, wsa_events.events[2], FD_OOB); else rc = 0; @@ -494,7 +494,7 @@ u_short zmq::select_t::get_fd_family (fd_t fd_) // for the same sockets, and determine_fd_family is expensive size_t i; for (i = 0; i < fd_family_cache_size; ++i) { - const std::pair &entry = fd_family_cache [i]; + const std::pair &entry = fd_family_cache[i]; if (entry.first == fd_) { return entry.second; } @@ -505,11 +505,11 @@ u_short zmq::select_t::get_fd_family (fd_t fd_) std::pair res = std::make_pair (fd_, determine_fd_family (fd_)); if (i < fd_family_cache_size) { - fd_family_cache [i] = res; + fd_family_cache[i] = res; } else { // just overwrite a random entry // could be optimized by some LRU strategy - fd_family_cache [rand () % fd_family_cache_size] = res; + fd_family_cache[rand () % fd_family_cache_size] = res; } return res.second; @@ -550,22 +550,22 @@ zmq::select_t::family_entry_t::family_entry_t () : retired (false) zmq::select_t::wsa_events_t::wsa_events_t () { - events [0] = WSACreateEvent (); - wsa_assert (events [0] != WSA_INVALID_EVENT); - events [1] = WSACreateEvent (); - wsa_assert (events [1] != WSA_INVALID_EVENT); - events [2] = WSACreateEvent (); - wsa_assert (events [2] != WSA_INVALID_EVENT); - events [3] = WSACreateEvent (); - wsa_assert (events [3] != WSA_INVALID_EVENT); + events[0] = WSACreateEvent (); + wsa_assert (events[0] != WSA_INVALID_EVENT); + events[1] = WSACreateEvent (); + wsa_assert (events[1] != WSA_INVALID_EVENT); + events[2] = WSACreateEvent (); + wsa_assert (events[2] != WSA_INVALID_EVENT); + events[3] = WSACreateEvent (); + wsa_assert (events[3] != WSA_INVALID_EVENT); } zmq::select_t::wsa_events_t::~wsa_events_t () { - wsa_assert (WSACloseEvent (events [0])); - wsa_assert (WSACloseEvent (events [1])); - wsa_assert (WSACloseEvent (events [2])); - wsa_assert (WSACloseEvent (events [3])); + wsa_assert (WSACloseEvent (events[0])); + wsa_assert (WSACloseEvent (events[1])); + wsa_assert (WSACloseEvent (events[2])); + wsa_assert (WSACloseEvent (events[3])); } #endif diff --git a/src/select.hpp b/src/select.hpp index 949868a24f..a410dab804 100644 --- a/src/select.hpp +++ b/src/select.hpp @@ -136,7 +136,7 @@ class select_t : public poller_base_t ~wsa_events_t (); // read, write, error and readwrite - WSAEVENT events [4]; + WSAEVENT events[4]; }; family_entries_t family_entries; @@ -147,7 +147,7 @@ class select_t : public poller_base_t zmq::fd_t &handle_); static const size_t fd_family_cache_size = 8; - std::pair fd_family_cache [fd_family_cache_size]; + std::pair fd_family_cache[fd_family_cache_size]; u_short get_fd_family (fd_t fd_); diff --git a/src/server.cpp b/src/server.cpp index 3cfecb7707..319edd30d9 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -56,7 +56,7 @@ void zmq::server_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_) uint32_t routing_id = next_routing_id++; if (!routing_id) - routing_id = next_routing_id++; // Never use Routing ID zero + routing_id = next_routing_id++; // Never use Routing ID zero pipe_->set_server_socket_routing_id (routing_id); // Add the record into output pipes lookup table @@ -69,7 +69,8 @@ void zmq::server_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_) void zmq::server_t::xpipe_terminated (pipe_t *pipe_) { - outpipes_t::iterator it = outpipes.find (pipe_->get_server_socket_routing_id ()); + outpipes_t::iterator it = + outpipes.find (pipe_->get_server_socket_routing_id ()); zmq_assert (it != outpipes.end ()); outpipes.erase (it); fq.pipe_terminated (pipe_); @@ -109,8 +110,7 @@ int zmq::server_t::xsend (msg_t *msg_) errno = EAGAIN; return -1; } - } - else { + } else { errno = EHOSTUNREACH; return -1; } @@ -124,8 +124,7 @@ int zmq::server_t::xsend (msg_t *msg_) // Message failed to send - we must close it ourselves. rc = msg_->close (); errno_assert (rc == 0); - } - else + } else it->second.pipe->flush (); // Detach the message from the data buffer. @@ -142,7 +141,6 @@ int zmq::server_t::xrecv (msg_t *msg_) // Drop any messages with more flag while (rc == 0 && msg_->flags () & msg_t::more) { - // drop all frames of the current multi-frame message rc = fq.recvpipe (msg_, NULL); diff --git a/src/server.hpp b/src/server.hpp index 5e1919b75a..c4125de9f1 100644 --- a/src/server.hpp +++ b/src/server.hpp @@ -41,56 +41,50 @@ namespace zmq { +class ctx_t; +class pipe_t; - class ctx_t; - class pipe_t; - - // TODO: This class uses O(n) scheduling. Rewrite it to use O(1) algorithm. - class server_t : - public socket_base_t +// TODO: This class uses O(n) scheduling. Rewrite it to use O(1) algorithm. +class server_t : public socket_base_t +{ + public: + server_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); + ~server_t (); + + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsend (zmq::msg_t *msg_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + bool xhas_out (); + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + protected: + const blob_t &get_credential () const; + + private: + // Fair queueing object for inbound pipes. + fq_t fq; + + struct outpipe_t { - public: - - server_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); - ~server_t (); - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsend (zmq::msg_t *msg_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - bool xhas_out (); - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - protected: - - const blob_t &get_credential () const; - - private: - - // Fair queueing object for inbound pipes. - fq_t fq; - - struct outpipe_t - { - zmq::pipe_t *pipe; - bool active; - }; - - // Outbound pipes indexed by the peer IDs. - typedef std::map outpipes_t; - outpipes_t outpipes; + zmq::pipe_t *pipe; + bool active; + }; - // Routing IDs are generated. It's a simple increment and wrap-over - // algorithm. This value is the next ID to use (if not used already). - uint32_t next_routing_id; + // Outbound pipes indexed by the peer IDs. + typedef std::map outpipes_t; + outpipes_t outpipes; - server_t (const server_t&); - const server_t &operator = (const server_t&); - }; + // Routing IDs are generated. It's a simple increment and wrap-over + // algorithm. This value is the next ID to use (if not used already). + uint32_t next_routing_id; + server_t (const server_t &); + const server_t &operator= (const server_t &); +}; } #endif diff --git a/src/session_base.cpp b/src/session_base.cpp index 84212361c4..87a08772cd 100644 --- a/src/session_base.cpp +++ b/src/session_base.cpp @@ -51,53 +51,57 @@ #include "dish.hpp" zmq::session_base_t *zmq::session_base_t::create (class io_thread_t *io_thread_, - bool active_, class socket_base_t *socket_, const options_t &options_, - address_t *addr_) + bool active_, + class socket_base_t *socket_, + const options_t &options_, + address_t *addr_) { session_base_t *s = NULL; switch (options_.type) { - case ZMQ_REQ: - s = new (std::nothrow) req_session_t (io_thread_, active_, - socket_, options_, addr_); - break; - case ZMQ_RADIO: - s = new (std::nothrow) radio_session_t (io_thread_, active_, - socket_, options_, addr_); - break; - case ZMQ_DISH: - s = new (std::nothrow) dish_session_t (io_thread_, active_, - socket_, options_, addr_); + case ZMQ_REQ: + s = new (std::nothrow) + req_session_t (io_thread_, active_, socket_, options_, addr_); break; - case ZMQ_DEALER: - case ZMQ_REP: - case ZMQ_ROUTER: - case ZMQ_PUB: - case ZMQ_XPUB: - case ZMQ_SUB: - case ZMQ_XSUB: - case ZMQ_PUSH: - case ZMQ_PULL: - case ZMQ_PAIR: - case ZMQ_STREAM: - case ZMQ_SERVER: - case ZMQ_CLIENT: - case ZMQ_GATHER: - case ZMQ_SCATTER: - case ZMQ_DGRAM: - s = new (std::nothrow) session_base_t (io_thread_, active_, - socket_, options_, addr_); - break; - default: - errno = EINVAL; - return NULL; + case ZMQ_RADIO: + s = new (std::nothrow) + radio_session_t (io_thread_, active_, socket_, options_, addr_); + break; + case ZMQ_DISH: + s = new (std::nothrow) + dish_session_t (io_thread_, active_, socket_, options_, addr_); + break; + case ZMQ_DEALER: + case ZMQ_REP: + case ZMQ_ROUTER: + case ZMQ_PUB: + case ZMQ_XPUB: + case ZMQ_SUB: + case ZMQ_XSUB: + case ZMQ_PUSH: + case ZMQ_PULL: + case ZMQ_PAIR: + case ZMQ_STREAM: + case ZMQ_SERVER: + case ZMQ_CLIENT: + case ZMQ_GATHER: + case ZMQ_SCATTER: + case ZMQ_DGRAM: + s = new (std::nothrow) + session_base_t (io_thread_, active_, socket_, options_, addr_); + break; + default: + errno = EINVAL; + return NULL; } alloc_assert (s); return s; } zmq::session_base_t::session_base_t (class io_thread_t *io_thread_, - bool active_, class socket_base_t *socket_, const options_t &options_, - address_t *addr_) : + bool active_, + class socket_base_t *socket_, + const options_t &options_, + address_t *addr_) : own_t (io_thread_, options_), io_object_t (io_thread_), active (active_), @@ -133,7 +137,7 @@ zmq::session_base_t::~session_base_t () if (engine) engine->terminate (); - LIBZMQ_DELETE(addr); + LIBZMQ_DELETE (addr); } void zmq::session_base_t::attach_pipe (pipe_t *pipe_) @@ -159,7 +163,7 @@ int zmq::session_base_t::pull_msg (msg_t *msg_) int zmq::session_base_t::push_msg (msg_t *msg_) { - if(msg_->flags() & msg_t::command) + if (msg_->flags () & msg_t::command) return 0; if (pipe && pipe->write (msg_)) { int rc = msg_->init (); @@ -235,9 +239,8 @@ void zmq::session_base_t::clean_pipes () void zmq::session_base_t::pipe_terminated (pipe_t *pipe_) { // Drop the reference to the deallocated pipe if required. - zmq_assert (pipe_ == pipe - || pipe_ == zap_pipe - || terminating_pipes.count (pipe_) == 1); + zmq_assert (pipe_ == pipe || pipe_ == zap_pipe + || terminating_pipes.count (pipe_) == 1); if (pipe_ == pipe) { // If this is our current pipe, remove it @@ -246,9 +249,7 @@ void zmq::session_base_t::pipe_terminated (pipe_t *pipe_) cancel_timer (linger_timer_id); has_linger_timer = false; } - } - else - if (pipe_ == zap_pipe) + } else if (pipe_ == zap_pipe) zap_pipe = NULL; else // Remove the pipe from the detached pipes set @@ -338,25 +339,24 @@ int zmq::session_base_t::zap_connect () errno = ECONNREFUSED; return -1; } - zmq_assert (peer.options.type == ZMQ_REP || - peer.options.type == ZMQ_ROUTER || - peer.options.type == ZMQ_SERVER); + zmq_assert (peer.options.type == ZMQ_REP || peer.options.type == ZMQ_ROUTER + || peer.options.type == ZMQ_SERVER); // Create a bi-directional pipe that will connect // session with zap socket. - object_t *parents [2] = {this, peer.socket}; - pipe_t *new_pipes [2] = {NULL, NULL}; - int hwms [2] = {0, 0}; - bool conflates [2] = {false, false}; + object_t *parents[2] = {this, peer.socket}; + pipe_t *new_pipes[2] = {NULL, NULL}; + int hwms[2] = {0, 0}; + bool conflates[2] = {false, false}; int rc = pipepair (parents, new_pipes, hwms, conflates); errno_assert (rc == 0); // Attach local end of the pipe to this socket object. - zap_pipe = new_pipes [0]; + zap_pipe = new_pipes[0]; zap_pipe->set_nodelay (); zap_pipe->set_event_sink (this); - send_bind (peer.socket, new_pipes [1], false); + send_bind (peer.socket, new_pipes[1], false); // Send empty routing id if required by the peer. if (peer.options.recv_routing_id) { @@ -374,10 +374,7 @@ int zmq::session_base_t::zap_connect () bool zmq::session_base_t::zap_enabled () { - return ( - options.mechanism != ZMQ_NULL || - !options.zap_domain.empty() - ); + return (options.mechanism != ZMQ_NULL || !options.zap_domain.empty ()); } void zmq::session_base_t::process_attach (i_engine *engine_) @@ -386,31 +383,30 @@ void zmq::session_base_t::process_attach (i_engine *engine_) // Create the pipe if it does not exist yet. if (!pipe && !is_terminating ()) { - object_t *parents [2] = {this, socket}; - pipe_t *pipes [2] = {NULL, NULL}; - - bool conflate = options.conflate && - (options.type == ZMQ_DEALER || - options.type == ZMQ_PULL || - options.type == ZMQ_PUSH || - options.type == ZMQ_PUB || - options.type == ZMQ_SUB); - - int hwms [2] = {conflate? -1 : options.rcvhwm, - conflate? -1 : options.sndhwm}; - bool conflates [2] = {conflate, conflate}; + object_t *parents[2] = {this, socket}; + pipe_t *pipes[2] = {NULL, NULL}; + + bool conflate = + options.conflate + && (options.type == ZMQ_DEALER || options.type == ZMQ_PULL + || options.type == ZMQ_PUSH || options.type == ZMQ_PUB + || options.type == ZMQ_SUB); + + int hwms[2] = {conflate ? -1 : options.rcvhwm, + conflate ? -1 : options.sndhwm}; + bool conflates[2] = {conflate, conflate}; int rc = pipepair (parents, pipes, hwms, conflates); errno_assert (rc == 0); // Plug the local end of the pipe. - pipes [0]->set_event_sink (this); + pipes[0]->set_event_sink (this); // Remember the local end of the pipe. zmq_assert (!pipe); - pipe = pipes [0]; + pipe = pipes[0]; // Ask socket to plug into the remote end of the pipe. - send_bind (socket, pipes [1]); + send_bind (socket, pipes[1]); } // Plug in the engine. @@ -420,7 +416,7 @@ void zmq::session_base_t::process_attach (i_engine *engine_) } void zmq::session_base_t::engine_error ( - zmq::stream_engine_t::error_reason_t reason) + zmq::stream_engine_t::error_reason_t reason) { // Engine is dead. Let's forget about it. engine = NULL; @@ -430,8 +426,8 @@ void zmq::session_base_t::engine_error ( clean_pipes (); zmq_assert (reason == stream_engine_t::connection_error - || reason == stream_engine_t::timeout_error - || reason == stream_engine_t::protocol_error); + || reason == stream_engine_t::timeout_error + || reason == stream_engine_t::protocol_error); switch (reason) { case stream_engine_t::timeout_error: @@ -517,9 +513,9 @@ void zmq::session_base_t::reconnect () { // For delayed connect situations, terminate the pipe // and reestablish later on - if (pipe && options.immediate == 1 - && addr->protocol != "pgm" && addr->protocol != "epgm" - && addr->protocol != "norm" && addr->protocol != "udp") { + if (pipe && options.immediate == 1 && addr->protocol != "pgm" + && addr->protocol != "epgm" && addr->protocol != "norm" + && addr->protocol != "udp") { pipe->hiccup (); pipe->terminate (false); terminating_pipes.insert (pipe); @@ -544,7 +540,9 @@ void zmq::session_base_t::reconnect () // For subscriber sockets we hiccup the inbound pipe, which will cause // the socket object to resend all the subscriptions. - if (pipe && (options.type == ZMQ_SUB || options.type == ZMQ_XSUB || options.type == ZMQ_DISH)) + if (pipe + && (options.type == ZMQ_SUB || options.type == ZMQ_XSUB + || options.type == ZMQ_DISH)) pipe->hiccup (); } @@ -560,19 +558,18 @@ void zmq::session_base_t::start_connecting (bool wait_) // Create the connecter object. if (addr->protocol == "tcp") { - if (!options.socks_proxy_address.empty()) { + if (!options.socks_proxy_address.empty ()) { address_t *proxy_address = new (std::nothrow) - address_t ("tcp", options.socks_proxy_address, this->get_ctx ()); + address_t ("tcp", options.socks_proxy_address, this->get_ctx ()); alloc_assert (proxy_address); socks_connecter_t *connecter = - new (std::nothrow) socks_connecter_t ( - io_thread, this, options, addr, proxy_address, wait_); + new (std::nothrow) socks_connecter_t (io_thread, this, options, + addr, proxy_address, wait_); alloc_assert (connecter); launch_child (connecter); - } - else { + } else { tcp_connecter_t *connecter = new (std::nothrow) - tcp_connecter_t (io_thread, this, options, addr, wait_); + tcp_connecter_t (io_thread, this, options, addr, wait_); alloc_assert (connecter); launch_child (connecter); } @@ -581,8 +578,8 @@ void zmq::session_base_t::start_connecting (bool wait_) #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS if (addr->protocol == "ipc") { - ipc_connecter_t *connecter = new (std::nothrow) ipc_connecter_t ( - io_thread, this, options, addr, wait_); + ipc_connecter_t *connecter = new (std::nothrow) + ipc_connecter_t (io_thread, this, options, addr, wait_); alloc_assert (connecter); launch_child (connecter); return; @@ -590,8 +587,8 @@ void zmq::session_base_t::start_connecting (bool wait_) #endif #if defined ZMQ_HAVE_TIPC if (addr->protocol == "tipc") { - tipc_connecter_t *connecter = new (std::nothrow) tipc_connecter_t ( - io_thread, this, options, addr, wait_); + tipc_connecter_t *connecter = new (std::nothrow) + tipc_connecter_t (io_thread, this, options, addr, wait_); alloc_assert (connecter); launch_child (connecter); return; @@ -599,9 +596,10 @@ void zmq::session_base_t::start_connecting (bool wait_) #endif if (addr->protocol == "udp") { - zmq_assert (options.type == ZMQ_DISH || options.type == ZMQ_RADIO || options.type == ZMQ_DGRAM); + zmq_assert (options.type == ZMQ_DISH || options.type == ZMQ_RADIO + || options.type == ZMQ_DGRAM); - udp_engine_t* engine = new (std::nothrow) udp_engine_t (options); + udp_engine_t *engine = new (std::nothrow) udp_engine_t (options); alloc_assert (engine); bool recv = false; @@ -610,12 +608,10 @@ void zmq::session_base_t::start_connecting (bool wait_) if (options.type == ZMQ_RADIO) { send = true; recv = false; - } - else if (options.type == ZMQ_DISH) { + } else if (options.type == ZMQ_DISH) { send = false; recv = true; - } - else if (options.type == ZMQ_DGRAM) { + } else if (options.type == ZMQ_DGRAM) { send = true; recv = true; } @@ -632,9 +628,8 @@ void zmq::session_base_t::start_connecting (bool wait_) // Both PGM and EPGM transports are using the same infrastructure. if (addr->protocol == "pgm" || addr->protocol == "epgm") { - zmq_assert (options.type == ZMQ_PUB || options.type == ZMQ_XPUB - || options.type == ZMQ_SUB || options.type == ZMQ_XSUB); + || options.type == ZMQ_SUB || options.type == ZMQ_XSUB); // For EPGM transport with UDP encapsulation of PGM is used. bool const udp_encapsulation = addr->protocol == "epgm"; @@ -643,25 +638,24 @@ void zmq::session_base_t::start_connecting (bool wait_) // away. There's no point in delaying it as no concept of 'connect' // exists with PGM anyway. if (options.type == ZMQ_PUB || options.type == ZMQ_XPUB) { - // PGM sender. - pgm_sender_t *pgm_sender = new (std::nothrow) pgm_sender_t ( - io_thread, options); + pgm_sender_t *pgm_sender = + new (std::nothrow) pgm_sender_t (io_thread, options); alloc_assert (pgm_sender); - int rc = pgm_sender->init (udp_encapsulation, addr->address.c_str ()); + int rc = + pgm_sender->init (udp_encapsulation, addr->address.c_str ()); errno_assert (rc == 0); send_attach (this, pgm_sender); - } - else { - + } else { // PGM receiver. - pgm_receiver_t *pgm_receiver = new (std::nothrow) pgm_receiver_t ( - io_thread, options); + pgm_receiver_t *pgm_receiver = + new (std::nothrow) pgm_receiver_t (io_thread, options); alloc_assert (pgm_receiver); - int rc = pgm_receiver->init (udp_encapsulation, addr->address.c_str ()); + int rc = + pgm_receiver->init (udp_encapsulation, addr->address.c_str ()); errno_assert (rc == 0); send_attach (this, pgm_receiver); @@ -677,20 +671,20 @@ void zmq::session_base_t::start_connecting (bool wait_) // away. There's no point in delaying it as no concept of 'connect' // exists with NORM anyway. if (options.type == ZMQ_PUB || options.type == ZMQ_XPUB) { - // NORM sender. - norm_engine_t* norm_sender = new (std::nothrow) norm_engine_t(io_thread, options); + norm_engine_t *norm_sender = + new (std::nothrow) norm_engine_t (io_thread, options); alloc_assert (norm_sender); int rc = norm_sender->init (addr->address.c_str (), true, false); errno_assert (rc == 0); send_attach (this, norm_sender); - } - else { // ZMQ_SUB or ZMQ_XSUB + } else { // ZMQ_SUB or ZMQ_XSUB // NORM receiver. - norm_engine_t* norm_receiver = new (std::nothrow) norm_engine_t (io_thread, options); + norm_engine_t *norm_receiver = + new (std::nothrow) norm_engine_t (io_thread, options); alloc_assert (norm_receiver); int rc = norm_receiver->init (addr->address.c_str (), false, true); @@ -704,8 +698,8 @@ void zmq::session_base_t::start_connecting (bool wait_) #if defined ZMQ_HAVE_VMCI if (addr->protocol == "vmci") { - vmci_connecter_t *connecter = new (std::nothrow) vmci_connecter_t ( - io_thread, this, options, addr, wait_); + vmci_connecter_t *connecter = new (std::nothrow) + vmci_connecter_t (io_thread, this, options, addr, wait_); alloc_assert (connecter); launch_child (connecter); return; diff --git a/src/session_base.hpp b/src/session_base.hpp index be92a67ccb..ae9f3a710d 100644 --- a/src/session_base.hpp +++ b/src/session_base.hpp @@ -41,133 +41,132 @@ namespace zmq { +class pipe_t; +class io_thread_t; +class socket_base_t; +struct i_engine; +struct address_t; - class pipe_t; - class io_thread_t; - class socket_base_t; - struct i_engine; - struct address_t; +class session_base_t : public own_t, public io_object_t, public i_pipe_events +{ + public: + // Create a session of the particular type. + static session_base_t *create (zmq::io_thread_t *io_thread_, + bool active_, + zmq::socket_base_t *socket_, + const options_t &options_, + address_t *addr_); + + // To be used once only, when creating the session. + void attach_pipe (zmq::pipe_t *pipe_); + + // Following functions are the interface exposed towards the engine. + virtual void reset (); + void flush (); + void engine_error (zmq::stream_engine_t::error_reason_t reason); + + // i_pipe_events interface implementation. + void read_activated (zmq::pipe_t *pipe_); + void write_activated (zmq::pipe_t *pipe_); + void hiccuped (zmq::pipe_t *pipe_); + void pipe_terminated (zmq::pipe_t *pipe_); + + // Delivers a message. Returns 0 if successful; -1 otherwise. + // The function takes ownership of the message. + virtual int push_msg (msg_t *msg_); + + int zap_connect (); + bool zap_enabled (); + + // Fetches a message. Returns 0 if successful; -1 otherwise. + // The caller is responsible for freeing the message when no + // longer used. + virtual int pull_msg (msg_t *msg_); + + // Receives message from ZAP socket. + // Returns 0 on success; -1 otherwise. + // The caller is responsible for freeing the message. + int read_zap_msg (msg_t *msg_); + + // Sends message to ZAP socket. + // Returns 0 on success; -1 otherwise. + // The function takes ownership of the message. + int write_zap_msg (msg_t *msg_); + + socket_base_t *get_socket (); + const char *get_endpoint () const; + + protected: + session_base_t (zmq::io_thread_t *io_thread_, + bool active_, + zmq::socket_base_t *socket_, + const options_t &options_, + address_t *addr_); + virtual ~session_base_t (); + + private: + void start_connecting (bool wait_); + + void reconnect (); + + // Handlers for incoming commands. + void process_plug (); + void process_attach (zmq::i_engine *engine_); + void process_term (int linger_); + + // i_poll_events handlers. + void timer_event (int id_); + + // Remove any half processed messages. Flush unflushed messages. + // Call this function when engine disconnect to get rid of leftovers. + void clean_pipes (); + + // If true, this session (re)connects to the peer. Otherwise, it's + // a transient session created by the listener. + const bool active; + + // Pipe connecting the session to its socket. + zmq::pipe_t *pipe; + + // Pipe used to exchange messages with ZAP socket. + zmq::pipe_t *zap_pipe; + + // This set is added to with pipes we are disconnecting, but haven't yet completed + std::set terminating_pipes; + + // This flag is true if the remainder of the message being processed + // is still in the in pipe. + bool incomplete_in; + + // True if termination have been suspended to push the pending + // messages to the network. + bool pending; + + // The protocol I/O engine connected to the session. + zmq::i_engine *engine; + + // The socket the session belongs to. + zmq::socket_base_t *socket; + + // I/O thread the session is living in. It will be used to plug in + // the engines into the same thread. + zmq::io_thread_t *io_thread; - class session_base_t : - public own_t, - public io_object_t, - public i_pipe_events + // ID of the linger timer + enum { - public: - - // Create a session of the particular type. - static session_base_t *create (zmq::io_thread_t *io_thread_, - bool active_, zmq::socket_base_t *socket_, - const options_t &options_, address_t *addr_); - - // To be used once only, when creating the session. - void attach_pipe (zmq::pipe_t *pipe_); - - // Following functions are the interface exposed towards the engine. - virtual void reset (); - void flush (); - void engine_error (zmq::stream_engine_t::error_reason_t reason); - - // i_pipe_events interface implementation. - void read_activated (zmq::pipe_t *pipe_); - void write_activated (zmq::pipe_t *pipe_); - void hiccuped (zmq::pipe_t *pipe_); - void pipe_terminated (zmq::pipe_t *pipe_); - - // Delivers a message. Returns 0 if successful; -1 otherwise. - // The function takes ownership of the message. - virtual int push_msg (msg_t *msg_); - - int zap_connect (); - bool zap_enabled (); - - // Fetches a message. Returns 0 if successful; -1 otherwise. - // The caller is responsible for freeing the message when no - // longer used. - virtual int pull_msg (msg_t *msg_); - - // Receives message from ZAP socket. - // Returns 0 on success; -1 otherwise. - // The caller is responsible for freeing the message. - int read_zap_msg (msg_t *msg_); - - // Sends message to ZAP socket. - // Returns 0 on success; -1 otherwise. - // The function takes ownership of the message. - int write_zap_msg (msg_t *msg_); - - socket_base_t *get_socket (); - const char *get_endpoint () const; - - protected: - - session_base_t (zmq::io_thread_t *io_thread_, bool active_, - zmq::socket_base_t *socket_, const options_t &options_, - address_t *addr_); - virtual ~session_base_t (); - - private: - - void start_connecting (bool wait_); - - void reconnect (); - - // Handlers for incoming commands. - void process_plug (); - void process_attach (zmq::i_engine *engine_); - void process_term (int linger_); - - // i_poll_events handlers. - void timer_event (int id_); - - // Remove any half processed messages. Flush unflushed messages. - // Call this function when engine disconnect to get rid of leftovers. - void clean_pipes (); - - // If true, this session (re)connects to the peer. Otherwise, it's - // a transient session created by the listener. - const bool active; - - // Pipe connecting the session to its socket. - zmq::pipe_t *pipe; - - // Pipe used to exchange messages with ZAP socket. - zmq::pipe_t *zap_pipe; - - // This set is added to with pipes we are disconnecting, but haven't yet completed - std::set terminating_pipes; - - // This flag is true if the remainder of the message being processed - // is still in the in pipe. - bool incomplete_in; - - // True if termination have been suspended to push the pending - // messages to the network. - bool pending; - - // The protocol I/O engine connected to the session. - zmq::i_engine *engine; - - // The socket the session belongs to. - zmq::socket_base_t *socket; - - // I/O thread the session is living in. It will be used to plug in - // the engines into the same thread. - zmq::io_thread_t *io_thread; - - // ID of the linger timer - enum {linger_timer_id = 0x20}; - - // True is linger timer is running. - bool has_linger_timer; + linger_timer_id = 0x20 + }; - // Protocol and address to use when connecting. - address_t *addr; + // True is linger timer is running. + bool has_linger_timer; - session_base_t (const session_base_t&); - const session_base_t &operator = (const session_base_t&); - }; + // Protocol and address to use when connecting. + address_t *addr; + session_base_t (const session_base_t &); + const session_base_t &operator= (const session_base_t &); +}; } #endif diff --git a/src/signaler.cpp b/src/signaler.cpp index 8f4c292384..e02660eb9a 100644 --- a/src/signaler.cpp +++ b/src/signaler.cpp @@ -77,7 +77,7 @@ #include #endif -#if !defined (ZMQ_HAVE_WINDOWS) +#if !defined(ZMQ_HAVE_WINDOWS) // Helper to sleep for specific number of milliseconds (or until signal) // static int sleep_ms (unsigned int ms_) @@ -102,13 +102,13 @@ static int sleep_ms (unsigned int ms_) static int close_wait_ms (int fd_, unsigned int max_ms_ = 2000) { unsigned int ms_so_far = 0; - unsigned int step_ms = max_ms_ / 10; + unsigned int step_ms = max_ms_ / 10; if (step_ms < 1) step_ms = 1; if (step_ms > 100) step_ms = 100; - int rc = 0; // do not sleep on first attempt + int rc = 0; // do not sleep on first attempt do { if (rc == -1 && errno == EAGAIN) { sleep_ms (step_ms); @@ -138,20 +138,22 @@ zmq::signaler_t::signaler_t () zmq::signaler_t::~signaler_t () { #if defined ZMQ_HAVE_EVENTFD - if (r == retired_fd) return; + if (r == retired_fd) + return; int rc = close_wait_ms (r); errno_assert (rc == 0); #elif defined ZMQ_HAVE_WINDOWS if (w != retired_fd) { - const struct linger so_linger = { 1, 0 }; + const struct linger so_linger = {1, 0}; int rc = setsockopt (w, SOL_SOCKET, SO_LINGER, - (const char *) &so_linger, sizeof so_linger); + (const char *) &so_linger, sizeof so_linger); // Only check shutdown if WSASTARTUP was previously done if (rc == 0 || WSAGetLastError () != WSANOTINITIALISED) { wsa_assert (rc != SOCKET_ERROR); rc = closesocket (w); wsa_assert (rc != SOCKET_ERROR); - if (r == retired_fd) return; + if (r == retired_fd) + return; rc = closesocket (r); wsa_assert (rc != SOCKET_ERROR); } @@ -188,7 +190,7 @@ void zmq::signaler_t::send () #elif defined ZMQ_HAVE_WINDOWS unsigned char dummy = 0; while (true) { - int nbytes = ::send (w, (char*) &dummy, sizeof (dummy), 0); + int nbytes = ::send (w, (char *) &dummy, sizeof (dummy), 0); wsa_assert (nbytes != SOCKET_ERROR); if (unlikely (nbytes == SOCKET_ERROR)) continue; @@ -234,15 +236,12 @@ int zmq::signaler_t::wait (int timeout_) if (unlikely (rc < 0)) { errno_assert (errno == EINTR); return -1; - } - else - if (unlikely (rc == 0)) { + } else if (unlikely (rc == 0)) { errno = EAGAIN; return -1; } #ifdef HAVE_FORK - else - if (unlikely (pid != getpid ())) { + else if (unlikely (pid != getpid ())) { // we have forked and the file descriptor is closed. Emulate an interrupt // response. //printf("Child process %d signaler_t::wait returning simulating interrupt #2\n", getpid()); @@ -265,12 +264,10 @@ int zmq::signaler_t::wait (int timeout_) timeout.tv_usec = timeout_ % 1000 * 1000; } #ifdef ZMQ_HAVE_WINDOWS - int rc = select (0, &fds, NULL, NULL, - timeout_ >= 0 ? &timeout : NULL); + int rc = select (0, &fds, NULL, NULL, timeout_ >= 0 ? &timeout : NULL); wsa_assert (rc != SOCKET_ERROR); #else - int rc = select (r + 1, &fds, NULL, NULL, - timeout_ >= 0 ? &timeout : NULL); + int rc = select (r + 1, &fds, NULL, NULL, timeout_ >= 0 ? &timeout : NULL); if (unlikely (rc < 0)) { errno_assert (errno == EINTR); return -1; @@ -290,7 +287,7 @@ int zmq::signaler_t::wait (int timeout_) void zmq::signaler_t::recv () { - // Attempt to read a signal. +// Attempt to read a signal. #if defined ZMQ_HAVE_EVENTFD uint64_t dummy; ssize_t sz = read (r, &dummy, sizeof (dummy)); @@ -322,15 +319,14 @@ void zmq::signaler_t::recv () int zmq::signaler_t::recv_failable () { - // Attempt to read a signal. +// Attempt to read a signal. #if defined ZMQ_HAVE_EVENTFD uint64_t dummy; ssize_t sz = read (r, &dummy, sizeof (dummy)); if (sz == -1) { errno_assert (errno == EAGAIN); return -1; - } - else { + } else { errno_assert (sz == sizeof (dummy)); // If we accidentally grabbed the next signal(s) along with the current @@ -349,7 +345,7 @@ int zmq::signaler_t::recv_failable () #if defined ZMQ_HAVE_WINDOWS int nbytes = ::recv (r, (char *) &dummy, sizeof (dummy), 0); if (nbytes == SOCKET_ERROR) { - const int last_error = WSAGetLastError(); + const int last_error = WSAGetLastError (); if (last_error == WSAEWOULDBLOCK) { errno = EAGAIN; return -1; @@ -363,7 +359,8 @@ int zmq::signaler_t::recv_failable () errno = EAGAIN; return -1; } - errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR); + errno_assert (errno == EAGAIN || errno == EWOULDBLOCK + || errno == EINTR); } #endif zmq_assert (nbytes == sizeof (dummy)); @@ -403,14 +400,13 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) errno_assert (errno == ENFILE || errno == EMFILE); *w_ = *r_ = -1; return -1; - } - else { + } else { *w_ = *r_ = fd; return 0; } #elif defined ZMQ_HAVE_WINDOWS -# if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP +#if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP // Windows CE does not manage security attributes SECURITY_DESCRIPTOR sd; SECURITY_ATTRIBUTES sa; @@ -422,7 +418,7 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) sa.nLength = sizeof (SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = &sd; -# endif +#endif // This function has to be in a system-wide critical section so that // two instances of the library don't accidentally create signaler @@ -439,31 +435,33 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) int event_signaler_port = 5905; if (signaler_port == event_signaler_port) { -# if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP - sync = CreateEventW (&sa, FALSE, TRUE, L"Global\\zmq-signaler-port-sync"); -# else - sync = CreateEventW (NULL, FALSE, TRUE, L"Global\\zmq-signaler-port-sync"); -# endif +#if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP + sync = + CreateEventW (&sa, FALSE, TRUE, L"Global\\zmq-signaler-port-sync"); +#else + sync = + CreateEventW (NULL, FALSE, TRUE, L"Global\\zmq-signaler-port-sync"); +#endif if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED) - sync = OpenEventW (SYNCHRONIZE | EVENT_MODIFY_STATE, - FALSE, L"Global\\zmq-signaler-port-sync"); + sync = OpenEventW (SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, + L"Global\\zmq-signaler-port-sync"); win_assert (sync != NULL); - } - else - if (signaler_port != 0) { - wchar_t mutex_name [MAX_PATH]; -# ifdef __MINGW32__ - _snwprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d", signaler_port); -# else - swprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d", signaler_port); -# endif - -# if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP + } else if (signaler_port != 0) { + wchar_t mutex_name[MAX_PATH]; +#ifdef __MINGW32__ + _snwprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d", + signaler_port); +#else + swprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d", + signaler_port); +#endif + +#if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP sync = CreateMutexW (&sa, FALSE, mutex_name); -# else +#else sync = CreateMutexW (NULL, FALSE, mutex_name); -# endif +#endif if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED) sync = OpenMutexW (SYNCHRONIZE, FALSE, mutex_name); @@ -483,11 +481,11 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) // Set SO_REUSEADDR and TCP_NODELAY on listening socket. BOOL so_reuseaddr = 1; int rc = setsockopt (listener, SOL_SOCKET, SO_REUSEADDR, - (char *) &so_reuseaddr, sizeof so_reuseaddr); + (char *) &so_reuseaddr, sizeof so_reuseaddr); wsa_assert (rc != SOCKET_ERROR); BOOL tcp_nodelay = 1; - rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, - (char *) &tcp_nodelay, sizeof tcp_nodelay); + rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, (char *) &tcp_nodelay, + sizeof tcp_nodelay); wsa_assert (rc != SOCKET_ERROR); // Init sockaddr to signaler port. @@ -502,8 +500,8 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) wsa_assert (*w_ != INVALID_SOCKET); // Set TCP_NODELAY on writer socket. - rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, - (char *) &tcp_nodelay, sizeof tcp_nodelay); + rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, (char *) &tcp_nodelay, + sizeof tcp_nodelay); wsa_assert (rc != SOCKET_ERROR); if (sync != NULL) { @@ -536,7 +534,8 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) // Send/receive large chunk to work around TCP slow start // This code is a workaround for #1608 if (*r_ != INVALID_SOCKET) { - size_t dummy_size = 1024 * 1024; // 1M to overload default receive buffer + size_t dummy_size = + 1024 * 1024; // 1M to overload default receive buffer unsigned char *dummy = (unsigned char *) malloc (dummy_size); wsa_assert (dummy); @@ -545,11 +544,14 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) while (still_to_send || still_to_recv) { int nbytes; if (still_to_send > 0) { - nbytes = ::send (*w_, (char *) (dummy + dummy_size - still_to_send), still_to_send, 0); + nbytes = + ::send (*w_, (char *) (dummy + dummy_size - still_to_send), + still_to_send, 0); wsa_assert (nbytes != SOCKET_ERROR); still_to_send -= nbytes; } - nbytes = ::recv (*r_, (char *) (dummy + dummy_size - still_to_recv), still_to_recv, 0); + nbytes = ::recv (*r_, (char *) (dummy + dummy_size - still_to_recv), + still_to_recv, 0); wsa_assert (nbytes != SOCKET_ERROR); still_to_recv -= nbytes; } @@ -563,7 +565,7 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) // We don't need the listening socket anymore. Close it. rc = closesocket (listener); - wsa_assert(rc != SOCKET_ERROR); + wsa_assert (rc != SOCKET_ERROR); if (sync != NULL) { // Exit the critical section. @@ -580,14 +582,13 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) } if (*r_ != INVALID_SOCKET) { -# if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP +#if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP // On Windows, preventing sockets to be inherited by child processes. BOOL brc = SetHandleInformation ((HANDLE) *r_, HANDLE_FLAG_INHERIT, 0); win_assert (brc); -# endif +#endif return 0; - } - else { + } else { // Cleanup writer if connection failed if (*w_ != INVALID_SOCKET) { rc = closesocket (*w_); @@ -655,7 +656,7 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) #else // All other implementations support socketpair() - int sv [2]; + int sv[2]; int type = SOCK_STREAM; // Setting this option result in sane behaviour when exec() functions // are used. Old sockets are closed and don't block TCP ports, avoid @@ -668,19 +669,18 @@ int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_) errno_assert (errno == ENFILE || errno == EMFILE); *w_ = *r_ = -1; return -1; - } - else { - // If there's no SOCK_CLOEXEC, let's try the second best option. Note that - // race condition can cause socket not to be closed (if fork happens - // between socket creation and this point). + } else { + // If there's no SOCK_CLOEXEC, let's try the second best option. Note that + // race condition can cause socket not to be closed (if fork happens + // between socket creation and this point). #if !defined ZMQ_HAVE_SOCK_CLOEXEC && defined FD_CLOEXEC - rc = fcntl (sv [0], F_SETFD, FD_CLOEXEC); + rc = fcntl (sv[0], F_SETFD, FD_CLOEXEC); errno_assert (rc != -1); - rc = fcntl (sv [1], F_SETFD, FD_CLOEXEC); + rc = fcntl (sv[1], F_SETFD, FD_CLOEXEC); errno_assert (rc != -1); #endif - *w_ = sv [0]; - *r_ = sv [1]; + *w_ = sv[0]; + *r_ = sv[1]; return 0; } #endif diff --git a/src/signaler.hpp b/src/signaler.hpp index ec9a727076..f44b7e2044 100644 --- a/src/signaler.hpp +++ b/src/signaler.hpp @@ -38,59 +38,56 @@ namespace zmq { +// This is a cross-platform equivalent to signal_fd. However, as opposed +// to signal_fd there can be at most one signal in the signaler at any +// given moment. Attempt to send a signal before receiving the previous +// one will result in undefined behaviour. - // This is a cross-platform equivalent to signal_fd. However, as opposed - // to signal_fd there can be at most one signal in the signaler at any - // given moment. Attempt to send a signal before receiving the previous - // one will result in undefined behaviour. - - class signaler_t - { - public: - - signaler_t (); - ~signaler_t (); +class signaler_t +{ + public: + signaler_t (); + ~signaler_t (); - // Returns the socket/file descriptor - // May return retired_fd if the signaler could not be initialized. - fd_t get_fd () const; - void send (); - int wait (int timeout_); - void recv (); - int recv_failable (); + // Returns the socket/file descriptor + // May return retired_fd if the signaler could not be initialized. + fd_t get_fd () const; + void send (); + int wait (int timeout_); + void recv (); + int recv_failable (); - bool valid () const; + bool valid () const; #ifdef HAVE_FORK - // close the file descriptors in a forked child process so that they - // do not interfere with the context in the parent process. - void forked (); + // close the file descriptors in a forked child process so that they + // do not interfere with the context in the parent process. + void forked (); #endif - private: - - // Creates a pair of file descriptors that will be used - // to pass the signals. - static int make_fdpair (fd_t *r_, fd_t *w_); + private: + // Creates a pair of file descriptors that will be used + // to pass the signals. + static int make_fdpair (fd_t *r_, fd_t *w_); - // Underlying write & read file descriptor - // Will be -1 if an error occurred during initialization, e.g. we - // exceeded the number of available handles - fd_t w; - fd_t r; + // Underlying write & read file descriptor + // Will be -1 if an error occurred during initialization, e.g. we + // exceeded the number of available handles + fd_t w; + fd_t r; - // Disable copying of signaler_t object. - signaler_t (const signaler_t&); - const signaler_t &operator = (const signaler_t&); + // Disable copying of signaler_t object. + signaler_t (const signaler_t &); + const signaler_t &operator= (const signaler_t &); #ifdef HAVE_FORK - // the process that created this context. Used to detect forking. - pid_t pid; - // idempotent close of file descriptors that is safe to use by destructor - // and forked(). - void close_internal (); + // the process that created this context. Used to detect forking. + pid_t pid; + // idempotent close of file descriptors that is safe to use by destructor + // and forked(). + void close_internal (); #endif - }; +}; } #endif diff --git a/src/socket_base.cpp b/src/socket_base.cpp index a0be9eb891..77f4bcd8cf 100644 --- a/src/socket_base.cpp +++ b/src/socket_base.cpp @@ -98,14 +98,15 @@ #include "dgram.hpp" - bool zmq::socket_base_t::check_tag () { return tag == 0xbaddecaf; } -zmq::socket_base_t *zmq::socket_base_t::create (int type_, class ctx_t *parent_, - uint32_t tid_, int sid_) +zmq::socket_base_t *zmq::socket_base_t::create (int type_, + class ctx_t *parent_, + uint32_t tid_, + int sid_) { socket_base_t *s = NULL; switch (type_) { @@ -175,20 +176,23 @@ zmq::socket_base_t *zmq::socket_base_t::create (int type_, class ctx_t *parent_, if (s->mailbox == NULL) { s->destroyed = true; - LIBZMQ_DELETE(s); + LIBZMQ_DELETE (s); return NULL; } return s; } -zmq::socket_base_t::socket_base_t (ctx_t *parent_, uint32_t tid_, int sid_, bool thread_safe_) : +zmq::socket_base_t::socket_base_t (ctx_t *parent_, + uint32_t tid_, + int sid_, + bool thread_safe_) : own_t (parent_, tid_), tag (0xbaddecaf), ctx_terminated (false), destroyed (false), - poller(NULL), - handle((poller_t::handle_t)NULL), + poller (NULL), + handle ((poller_t::handle_t) NULL), last_tsc (0), ticks (0), rcvmore (false), @@ -196,20 +200,18 @@ zmq::socket_base_t::socket_base_t (ctx_t *parent_, uint32_t tid_, int sid_, bool monitor_events (0), thread_safe (thread_safe_), reaper_signaler (NULL), - sync(), - monitor_sync() + sync (), + monitor_sync () { options.socket_id = sid_; options.ipv6 = (parent_->get (ZMQ_IPV6) != 0); - options.linger = parent_->get (ZMQ_BLOCKY)? -1: 0; + options.linger = parent_->get (ZMQ_BLOCKY) ? -1 : 0; - if (thread_safe) - { - mailbox = new (std::nothrow) mailbox_safe_t(&sync); + if (thread_safe) { + mailbox = new (std::nothrow) mailbox_safe_t (&sync); zmq_assert (mailbox); - } - else { - mailbox_t *m = new (std::nothrow) mailbox_t(); + } else { + mailbox_t *m = new (std::nothrow) mailbox_t (); zmq_assert (m); if (m->get_fd () != retired_fd) @@ -235,12 +237,12 @@ int zmq::socket_base_t::get_peer_state (const void *routing_id_, zmq::socket_base_t::~socket_base_t () { if (mailbox) - LIBZMQ_DELETE(mailbox); + LIBZMQ_DELETE (mailbox); if (reaper_signaler) - LIBZMQ_DELETE(reaper_signaler); + LIBZMQ_DELETE (reaper_signaler); - scoped_lock_t lock(monitor_sync); + scoped_lock_t lock (monitor_sync); stop_monitor (); zmq_assert (destroyed); @@ -261,7 +263,8 @@ void zmq::socket_base_t::stop () } int zmq::socket_base_t::parse_uri (const char *uri_, - std::string &protocol_, std::string &address_) + std::string &protocol_, + std::string &address_) { zmq_assert (uri_ != NULL); @@ -286,44 +289,44 @@ int zmq::socket_base_t::check_protocol (const std::string &protocol_) // First check out whether the protocol is something we are aware of. if (protocol_ != "inproc" #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS - && protocol_ != "ipc" + && protocol_ != "ipc" #endif - && protocol_ != "tcp" + && protocol_ != "tcp" #if defined ZMQ_HAVE_OPENPGM - // pgm/epgm transports only available if 0MQ is compiled with OpenPGM. - && protocol_ != "pgm" - && protocol_ != "epgm" + // pgm/epgm transports only available if 0MQ is compiled with OpenPGM. + && protocol_ != "pgm" + && protocol_ != "epgm" #endif #if defined ZMQ_HAVE_TIPC - // TIPC transport is only available on Linux. - && protocol_ != "tipc" + // TIPC transport is only available on Linux. + && protocol_ != "tipc" #endif #if defined ZMQ_HAVE_NORM - && protocol_ != "norm" + && protocol_ != "norm" #endif #if defined ZMQ_HAVE_VMCI - && protocol_ != "vmci" + && protocol_ != "vmci" #endif - && protocol_ != "udp") { + && protocol_ != "udp") { errno = EPROTONOSUPPORT; return -1; } - // Check whether socket type and transport protocol match. - // Specifically, multicast protocols can't be combined with - // bi-directional messaging patterns (socket types). + // Check whether socket type and transport protocol match. + // Specifically, multicast protocols can't be combined with + // bi-directional messaging patterns (socket types). #if defined ZMQ_HAVE_OPENPGM || defined ZMQ_HAVE_NORM - if ((protocol_ == "pgm" || protocol_ == "epgm" || protocol_ == "norm") && - options.type != ZMQ_PUB && options.type != ZMQ_SUB && - options.type != ZMQ_XPUB && options.type != ZMQ_XSUB) { + if ((protocol_ == "pgm" || protocol_ == "epgm" || protocol_ == "norm") + && options.type != ZMQ_PUB && options.type != ZMQ_SUB + && options.type != ZMQ_XPUB && options.type != ZMQ_XSUB) { errno = ENOCOMPATPROTO; return -1; } #endif - if (protocol_ == "udp" && (options.type != ZMQ_DISH && - options.type != ZMQ_RADIO && - options.type != ZMQ_DGRAM)) { + if (protocol_ == "udp" + && (options.type != ZMQ_DISH && options.type != ZMQ_RADIO + && options.type != ZMQ_DGRAM)) { errno = ENOCOMPATPROTO; return -1; } @@ -349,12 +352,13 @@ void zmq::socket_base_t::attach_pipe (pipe_t *pipe_, bool subscribe_to_all_) } } -int zmq::socket_base_t::setsockopt (int option_, const void *optval_, - size_t optvallen_) +int zmq::socket_base_t::setsockopt (int option_, + const void *optval_, + size_t optvallen_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); - if (!options.is_valid(option_)) { + if (!options.is_valid (option_)) { errno = EINVAL; return -1; } @@ -373,15 +377,16 @@ int zmq::socket_base_t::setsockopt (int option_, const void *optval_, // If the socket type doesn't support the option, pass it to // the generic option parser. rc = options.setsockopt (option_, optval_, optvallen_); - update_pipe_options(option_); + update_pipe_options (option_); return rc; } -int zmq::socket_base_t::getsockopt (int option_, void *optval_, - size_t *optvallen_) +int zmq::socket_base_t::getsockopt (int option_, + void *optval_, + size_t *optvallen_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); if (unlikely (ctx_terminated)) { errno = ETERM; @@ -393,8 +398,8 @@ int zmq::socket_base_t::getsockopt (int option_, void *optval_, errno = EINVAL; return -1; } - memset(optval_, 0, *optvallen_); - *((int*) optval_) = rcvmore ? 1 : 0; + memset (optval_, 0, *optvallen_); + *((int *) optval_) = rcvmore ? 1 : 0; *optvallen_ = sizeof (int); return 0; } @@ -411,8 +416,8 @@ int zmq::socket_base_t::getsockopt (int option_, void *optval_, return -1; } - *((fd_t*)optval_) = ((mailbox_t*)mailbox)->get_fd(); - *optvallen_ = sizeof(fd_t); + *((fd_t *) optval_) = ((mailbox_t *) mailbox)->get_fd (); + *optvallen_ = sizeof (fd_t); return 0; } @@ -427,11 +432,11 @@ int zmq::socket_base_t::getsockopt (int option_, void *optval_, return -1; } errno_assert (rc == 0); - *((int*) optval_) = 0; + *((int *) optval_) = 0; if (has_out ()) - *((int*) optval_) |= ZMQ_POLLOUT; + *((int *) optval_) |= ZMQ_POLLOUT; if (has_in ()) - *((int*) optval_) |= ZMQ_POLLIN; + *((int *) optval_) |= ZMQ_POLLIN; *optvallen_ = sizeof (int); return 0; } @@ -441,7 +446,8 @@ int zmq::socket_base_t::getsockopt (int option_, void *optval_, errno = EINVAL; return -1; } - strncpy(static_cast (optval_), last_endpoint.c_str(), last_endpoint.size() + 1); + strncpy (static_cast (optval_), last_endpoint.c_str (), + last_endpoint.size () + 1); *optvallen_ = last_endpoint.size () + 1; return 0; } @@ -451,8 +457,8 @@ int zmq::socket_base_t::getsockopt (int option_, void *optval_, errno = EINVAL; return -1; } - memset(optval_, 0, *optvallen_); - *((int*) optval_) = thread_safe ? 1 : 0; + memset (optval_, 0, *optvallen_); + *((int *) optval_) = thread_safe ? 1 : 0; *optvallen_ = sizeof (int); return 0; } @@ -461,9 +467,9 @@ int zmq::socket_base_t::getsockopt (int option_, void *optval_, return rc; } -int zmq::socket_base_t::join (const char* group_) +int zmq::socket_base_t::join (const char *group_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); int rc = xjoin (group_); @@ -471,9 +477,9 @@ int zmq::socket_base_t::join (const char* group_) return rc; } -int zmq::socket_base_t::leave (const char* group_) +int zmq::socket_base_t::leave (const char *group_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); int rc = xleave (group_); @@ -481,37 +487,37 @@ int zmq::socket_base_t::leave (const char* group_) return rc; } -int zmq::socket_base_t::add_signaler(signaler_t *s_) +int zmq::socket_base_t::add_signaler (signaler_t *s_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); if (!thread_safe) { errno = EINVAL; return -1; } - ((mailbox_safe_t*)mailbox)->add_signaler(s_); + ((mailbox_safe_t *) mailbox)->add_signaler (s_); return 0; } -int zmq::socket_base_t::remove_signaler(signaler_t *s_) +int zmq::socket_base_t::remove_signaler (signaler_t *s_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); if (!thread_safe) { errno = EINVAL; return -1; } - ((mailbox_safe_t*)mailbox)->remove_signaler(s_); + ((mailbox_safe_t *) mailbox)->remove_signaler (s_); return 0; } int zmq::socket_base_t::bind (const char *addr_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); if (unlikely (ctx_terminated)) { errno = ETERM; @@ -532,7 +538,7 @@ int zmq::socket_base_t::bind (const char *addr_) } if (protocol == "inproc") { - const endpoint_t endpoint = { this, options }; + const endpoint_t endpoint = {this, options}; rc = register_endpoint (addr_, endpoint); if (rc == 0) { connect_pending (addr_, this); @@ -564,38 +570,39 @@ int zmq::socket_base_t::bind (const char *addr_) return -1; } - address_t *paddr = new (std::nothrow) address_t (protocol, address, this->get_ctx ()); + address_t *paddr = + new (std::nothrow) address_t (protocol, address, this->get_ctx ()); alloc_assert (paddr); paddr->resolved.udp_addr = new (std::nothrow) udp_address_t (); alloc_assert (paddr->resolved.udp_addr); - rc = paddr->resolved.udp_addr->resolve (address.c_str(), true); + rc = paddr->resolved.udp_addr->resolve (address.c_str (), true); if (rc != 0) { - LIBZMQ_DELETE(paddr); + LIBZMQ_DELETE (paddr); return -1; } - session_base_t *session = session_base_t::create (io_thread, true, this, - options, paddr); + session_base_t *session = + session_base_t::create (io_thread, true, this, options, paddr); errno_assert (session); pipe_t *newpipe = NULL; // Create a bi-directional pipe. - object_t *parents [2] = {this, session}; - pipe_t *new_pipes [2] = {NULL, NULL}; + object_t *parents[2] = {this, session}; + pipe_t *new_pipes[2] = {NULL, NULL}; - int hwms [2] = {options.sndhwm, options.rcvhwm}; - bool conflates [2] = {false, false}; + int hwms[2] = {options.sndhwm, options.rcvhwm}; + bool conflates[2] = {false, false}; rc = pipepair (parents, new_pipes, hwms, conflates); errno_assert (rc == 0); // Attach local end of the pipe to the socket object. - attach_pipe (new_pipes [0], true); - newpipe = new_pipes [0]; + attach_pipe (new_pipes[0], true); + newpipe = new_pipes[0]; // Attach remote end of the pipe to the session object later on. - session->attach_pipe (new_pipes [1]); + session->attach_pipe (new_pipes[1]); // Save last endpoint URI paddr->to_string (last_endpoint); @@ -614,13 +621,13 @@ int zmq::socket_base_t::bind (const char *addr_) } if (protocol == "tcp") { - tcp_listener_t *listener = new (std::nothrow) tcp_listener_t ( - io_thread, this, options); + tcp_listener_t *listener = + new (std::nothrow) tcp_listener_t (io_thread, this, options); alloc_assert (listener); rc = listener->set_address (address.c_str ()); if (rc != 0) { - LIBZMQ_DELETE(listener); - event_bind_failed (address, zmq_errno()); + LIBZMQ_DELETE (listener); + event_bind_failed (address, zmq_errno ()); return -1; } @@ -634,13 +641,13 @@ int zmq::socket_base_t::bind (const char *addr_) #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS if (protocol == "ipc") { - ipc_listener_t *listener = new (std::nothrow) ipc_listener_t ( - io_thread, this, options); + ipc_listener_t *listener = + new (std::nothrow) ipc_listener_t (io_thread, this, options); alloc_assert (listener); int rc = listener->set_address (address.c_str ()); if (rc != 0) { - LIBZMQ_DELETE(listener); - event_bind_failed (address, zmq_errno()); + LIBZMQ_DELETE (listener); + event_bind_failed (address, zmq_errno ()); return -1; } @@ -654,15 +661,15 @@ int zmq::socket_base_t::bind (const char *addr_) #endif #if defined ZMQ_HAVE_TIPC if (protocol == "tipc") { - tipc_listener_t *listener = new (std::nothrow) tipc_listener_t ( - io_thread, this, options); - alloc_assert (listener); - int rc = listener->set_address (address.c_str ()); - if (rc != 0) { - LIBZMQ_DELETE(listener); - event_bind_failed (address, zmq_errno()); - return -1; - } + tipc_listener_t *listener = + new (std::nothrow) tipc_listener_t (io_thread, this, options); + alloc_assert (listener); + int rc = listener->set_address (address.c_str ()); + if (rc != 0) { + LIBZMQ_DELETE (listener); + event_bind_failed (address, zmq_errno ()); + return -1; + } // Save last endpoint URI listener->get_address (last_endpoint); @@ -674,19 +681,19 @@ int zmq::socket_base_t::bind (const char *addr_) #endif #if defined ZMQ_HAVE_VMCI if (protocol == "vmci") { - vmci_listener_t *listener = new (std::nothrow) vmci_listener_t ( - io_thread, this, options); + vmci_listener_t *listener = + new (std::nothrow) vmci_listener_t (io_thread, this, options); alloc_assert (listener); int rc = listener->set_address (address.c_str ()); if (rc != 0) { - LIBZMQ_DELETE(listener); + LIBZMQ_DELETE (listener); event_bind_failed (address, zmq_errno ()); return -1; } listener->get_address (last_endpoint); - add_endpoint (last_endpoint.c_str(), (own_t *) listener, NULL); + add_endpoint (last_endpoint.c_str (), (own_t *) listener, NULL); options.connected = true; return 0; } @@ -698,7 +705,7 @@ int zmq::socket_base_t::bind (const char *addr_) int zmq::socket_base_t::connect (const char *addr_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); if (unlikely (ctx_terminated)) { errno = ETERM; @@ -719,7 +726,6 @@ int zmq::socket_base_t::connect (const char *addr_) } if (protocol == "inproc") { - // TODO: inproc connect is specific with respect to creating pipes // as there's no 'reconnect' functionality implemented. Once that // is in place we should follow generic pipe creation algorithm. @@ -737,27 +743,26 @@ int zmq::socket_base_t::connect (const char *addr_) int rcvhwm = 0; if (peer.socket == NULL) rcvhwm = options.rcvhwm; - else - if (options.rcvhwm != 0 && peer.options.sndhwm != 0) + else if (options.rcvhwm != 0 && peer.options.sndhwm != 0) rcvhwm = options.rcvhwm + peer.options.sndhwm; // Create a bi-directional pipe to connect the peers. - object_t *parents [2] = {this, peer.socket == NULL ? this : peer.socket}; - pipe_t *new_pipes [2] = {NULL, NULL}; - - bool conflate = options.conflate && - (options.type == ZMQ_DEALER || - options.type == ZMQ_PULL || - options.type == ZMQ_PUSH || - options.type == ZMQ_PUB || - options.type == ZMQ_SUB); - - int hwms [2] = {conflate? -1 : sndhwm, conflate? -1 : rcvhwm}; - bool conflates [2] = {conflate, conflate}; + object_t *parents[2] = {this, peer.socket == NULL ? this : peer.socket}; + pipe_t *new_pipes[2] = {NULL, NULL}; + + bool conflate = + options.conflate + && (options.type == ZMQ_DEALER || options.type == ZMQ_PULL + || options.type == ZMQ_PUSH || options.type == ZMQ_PUB + || options.type == ZMQ_SUB); + + int hwms[2] = {conflate ? -1 : sndhwm, conflate ? -1 : rcvhwm}; + bool conflates[2] = {conflate, conflate}; rc = pipepair (parents, new_pipes, hwms, conflates); if (!conflate) { - new_pipes[0]->set_hwms_boost(peer.options.sndhwm, peer.options.rcvhwm); - new_pipes[1]->set_hwms_boost(options.sndhwm, options.rcvhwm); + new_pipes[0]->set_hwms_boost (peer.options.sndhwm, + peer.options.rcvhwm); + new_pipes[1]->set_hwms_boost (options.sndhwm, options.rcvhwm); } errno_assert (rc == 0); @@ -772,24 +777,24 @@ int zmq::socket_base_t::connect (const char *addr_) errno_assert (rc == 0); memcpy (id.data (), options.routing_id, options.routing_id_size); id.set_flags (msg_t::routing_id); - bool written = new_pipes [0]->write (&id); + bool written = new_pipes[0]->write (&id); zmq_assert (written); - new_pipes [0]->flush (); + new_pipes[0]->flush (); const endpoint_t endpoint = {this, options}; pend_connection (std::string (addr_), endpoint, new_pipes); - } - else { + } else { // If required, send the routing id of the local socket to the peer. if (peer.options.recv_routing_id) { msg_t id; rc = id.init_size (options.routing_id_size); errno_assert (rc == 0); - memcpy (id.data (), options.routing_id, options.routing_id_size); + memcpy (id.data (), options.routing_id, + options.routing_id_size); id.set_flags (msg_t::routing_id); - bool written = new_pipes [0]->write (&id); + bool written = new_pipes[0]->write (&id); zmq_assert (written); - new_pipes [0]->flush (); + new_pipes[0]->flush (); } // If required, send the routing id of the peer to the local socket. @@ -797,34 +802,35 @@ int zmq::socket_base_t::connect (const char *addr_) msg_t id; rc = id.init_size (peer.options.routing_id_size); errno_assert (rc == 0); - memcpy (id.data (), peer.options.routing_id, peer.options.routing_id_size); + memcpy (id.data (), peer.options.routing_id, + peer.options.routing_id_size); id.set_flags (msg_t::routing_id); - bool written = new_pipes [1]->write (&id); + bool written = new_pipes[1]->write (&id); zmq_assert (written); - new_pipes [1]->flush (); + new_pipes[1]->flush (); } // Attach remote end of the pipe to the peer socket. Note that peer's // seqnum was incremented in find_endpoint function. We don't need it // increased here. - send_bind (peer.socket, new_pipes [1], false); + send_bind (peer.socket, new_pipes[1], false); } // Attach local end of the pipe to this socket object. - attach_pipe (new_pipes [0]); + attach_pipe (new_pipes[0]); // Save last endpoint URI last_endpoint.assign (addr_); // remember inproc connections for disconnect - inprocs.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, new_pipes [0]); + inprocs.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, new_pipes[0]); options.connected = true; return 0; } - bool is_single_connect = (options.type == ZMQ_DEALER || - options.type == ZMQ_SUB || options.type == ZMQ_PUB || - options.type == ZMQ_REQ); + bool is_single_connect = + (options.type == ZMQ_DEALER || options.type == ZMQ_SUB + || options.type == ZMQ_PUB || options.type == ZMQ_REQ); if (unlikely (is_single_connect)) { const endpoints_t::iterator it = endpoints.find (addr_); if (it != endpoints.end ()) { @@ -842,7 +848,8 @@ int zmq::socket_base_t::connect (const char *addr_) return -1; } - address_t *paddr = new (std::nothrow) address_t (protocol, address, this->get_ctx ()); + address_t *paddr = + new (std::nothrow) address_t (protocol, address, this->get_ctx ()); alloc_assert (paddr); // Resolve address (if needed by the protocol) @@ -858,14 +865,13 @@ int zmq::socket_base_t::connect (const char *addr_) // Following code is quick and dirty check to catch obvious errors, // without trying to be fully accurate. const char *check = address.c_str (); - if (isalnum (*check) || isxdigit (*check) || *check == '[' || *check == ':') { + if (isalnum (*check) || isxdigit (*check) || *check == '[' + || *check == ':') { check++; - while (isalnum (*check) - || isxdigit (*check) - || *check == '.' || *check == '-' || *check == ':' || *check == '%' - || *check == ';' || *check == '[' || *check == ']' || *check == '_' - || *check == '*' - ) { + while (isalnum (*check) || isxdigit (*check) || *check == '.' + || *check == '-' || *check == ':' || *check == '%' + || *check == ';' || *check == '[' || *check == ']' + || *check == '_' || *check == '*') { check++; } } @@ -878,119 +884,118 @@ int zmq::socket_base_t::connect (const char *addr_) if (check) { check++; if (*check && (isdigit (*check))) - rc = 0; // Valid + rc = 0; // Valid } } if (rc == -1) { errno = EINVAL; - LIBZMQ_DELETE(paddr); + LIBZMQ_DELETE (paddr); return -1; } // Defer resolution until a socket is opened paddr->resolved.tcp_addr = NULL; } #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS - else - if (protocol == "ipc") { + else if (protocol == "ipc") { paddr->resolved.ipc_addr = new (std::nothrow) ipc_address_t (); alloc_assert (paddr->resolved.ipc_addr); int rc = paddr->resolved.ipc_addr->resolve (address.c_str ()); if (rc != 0) { - LIBZMQ_DELETE(paddr); + LIBZMQ_DELETE (paddr); return -1; } } #endif - if (protocol == "udp") { + if (protocol == "udp") { if (options.type != ZMQ_RADIO) { errno = ENOCOMPATPROTO; - LIBZMQ_DELETE(paddr); + LIBZMQ_DELETE (paddr); return -1; } paddr->resolved.udp_addr = new (std::nothrow) udp_address_t (); alloc_assert (paddr->resolved.udp_addr); - rc = paddr->resolved.udp_addr->resolve (address.c_str(), false); + rc = paddr->resolved.udp_addr->resolve (address.c_str (), false); if (rc != 0) { - LIBZMQ_DELETE(paddr); + LIBZMQ_DELETE (paddr); return -1; } } -// TBD - Should we check address for ZMQ_HAVE_NORM??? + // TBD - Should we check address for ZMQ_HAVE_NORM??? #ifdef ZMQ_HAVE_OPENPGM if (protocol == "pgm" || protocol == "epgm") { struct pgm_addrinfo_t *res = NULL; uint16_t port_number = 0; - int rc = pgm_socket_t::init_address(address.c_str(), &res, &port_number); + int rc = + pgm_socket_t::init_address (address.c_str (), &res, &port_number); if (res != NULL) pgm_freeaddrinfo (res); if (rc != 0 || port_number == 0) { - return -1; + return -1; } } #endif #if defined ZMQ_HAVE_TIPC - else - if (protocol == "tipc") { + else if (protocol == "tipc") { paddr->resolved.tipc_addr = new (std::nothrow) tipc_address_t (); alloc_assert (paddr->resolved.tipc_addr); - int rc = paddr->resolved.tipc_addr->resolve (address.c_str()); + int rc = paddr->resolved.tipc_addr->resolve (address.c_str ()); if (rc != 0) { - LIBZMQ_DELETE(paddr); + LIBZMQ_DELETE (paddr); return -1; } } #endif #if defined ZMQ_HAVE_VMCI - else - if (protocol == "vmci") { - paddr->resolved.vmci_addr = new (std::nothrow) vmci_address_t (this->get_ctx ()); + else if (protocol == "vmci") { + paddr->resolved.vmci_addr = + new (std::nothrow) vmci_address_t (this->get_ctx ()); alloc_assert (paddr->resolved.vmci_addr); int rc = paddr->resolved.vmci_addr->resolve (address.c_str ()); if (rc != 0) { - LIBZMQ_DELETE(paddr); + LIBZMQ_DELETE (paddr); return -1; } } #endif // Create session. - session_base_t *session = session_base_t::create (io_thread, true, this, - options, paddr); + session_base_t *session = + session_base_t::create (io_thread, true, this, options, paddr); errno_assert (session); // PGM does not support subscription forwarding; ask for all data to be // sent to this pipe. (same for NORM, currently?) - bool subscribe_to_all = protocol == "pgm" || protocol == "epgm" || protocol == "norm" || protocol == "udp"; + bool subscribe_to_all = protocol == "pgm" || protocol == "epgm" + || protocol == "norm" || protocol == "udp"; pipe_t *newpipe = NULL; if (options.immediate != 1 || subscribe_to_all) { // Create a bi-directional pipe. - object_t *parents [2] = {this, session}; - pipe_t *new_pipes [2] = {NULL, NULL}; - - bool conflate = options.conflate && - (options.type == ZMQ_DEALER || - options.type == ZMQ_PULL || - options.type == ZMQ_PUSH || - options.type == ZMQ_PUB || - options.type == ZMQ_SUB); - - int hwms [2] = {conflate? -1 : options.sndhwm, - conflate? -1 : options.rcvhwm}; - bool conflates [2] = {conflate, conflate}; + object_t *parents[2] = {this, session}; + pipe_t *new_pipes[2] = {NULL, NULL}; + + bool conflate = + options.conflate + && (options.type == ZMQ_DEALER || options.type == ZMQ_PULL + || options.type == ZMQ_PUSH || options.type == ZMQ_PUB + || options.type == ZMQ_SUB); + + int hwms[2] = {conflate ? -1 : options.sndhwm, + conflate ? -1 : options.rcvhwm}; + bool conflates[2] = {conflate, conflate}; rc = pipepair (parents, new_pipes, hwms, conflates); errno_assert (rc == 0); // Attach local end of the pipe to the socket object. - attach_pipe (new_pipes [0], subscribe_to_all); - newpipe = new_pipes [0]; + attach_pipe (new_pipes[0], subscribe_to_all); + newpipe = new_pipes[0]; // Attach remote end of the pipe to the session object later on. - session->attach_pipe (new_pipes [1]); + session->attach_pipe (new_pipes[1]); } // Save last endpoint URI @@ -1000,16 +1005,19 @@ int zmq::socket_base_t::connect (const char *addr_) return 0; } -void zmq::socket_base_t::add_endpoint (const char *addr_, own_t *endpoint_, pipe_t *pipe) +void zmq::socket_base_t::add_endpoint (const char *addr_, + own_t *endpoint_, + pipe_t *pipe) { // Activate the session. Make it a child of this socket. launch_child (endpoint_); - endpoints.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, endpoint_pipe_t (endpoint_, pipe)); + endpoints.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, + endpoint_pipe_t (endpoint_, pipe)); } int zmq::socket_base_t::term_endpoint (const char *addr_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); // Check whether the library haven't been shut down yet. if (unlikely (ctx_terminated)) { @@ -1026,23 +1034,24 @@ int zmq::socket_base_t::term_endpoint (const char *addr_) // Process pending commands, if any, since there could be pending unprocessed process_own()'s // (from launch_child() for example) we're asked to terminate now. int rc = process_commands (0, false); - if (unlikely(rc != 0)) { + if (unlikely (rc != 0)) { return -1; } // Parse addr_ string. std::string protocol; std::string address; - if (parse_uri(addr_, protocol, address) || check_protocol(protocol)) { + if (parse_uri (addr_, protocol, address) || check_protocol (protocol)) { return -1; } // Disconnect an inproc socket if (protocol == "inproc") { - if (unregister_endpoint (std::string(addr_), this) == 0) { + if (unregister_endpoint (std::string (addr_), this) == 0) { return 0; } - std::pair range = inprocs.equal_range (std::string (addr_)); + std::pair range = + inprocs.equal_range (std::string (addr_)); if (range.first == range.second) { errno = ENOENT; return -1; @@ -1055,7 +1064,7 @@ int zmq::socket_base_t::term_endpoint (const char *addr_) } std::string resolved_addr = std::string (addr_); - std::pair range; + std::pair range; // The resolved last_endpoint is used as a key in the endpoints map. // The address passed by the user might not match in the TCP case due to @@ -1074,13 +1083,14 @@ int zmq::socket_base_t::term_endpoint (const char *addr_) range = endpoints.equal_range (resolved_addr); if (range.first == range.second) { - rc = tcp_addr->resolve (address.c_str (), true, options.ipv6); + rc = + tcp_addr->resolve (address.c_str (), true, options.ipv6); if (rc == 0) { tcp_addr->to_string (resolved_addr); } } } - LIBZMQ_DELETE(tcp_addr); + LIBZMQ_DELETE (tcp_addr); } } @@ -1103,7 +1113,7 @@ int zmq::socket_base_t::term_endpoint (const char *addr_) int zmq::socket_base_t::send (msg_t *msg_, int flags_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); // Check whether the library haven't been shut down yet. if (unlikely (ctx_terminated)) { @@ -1179,7 +1189,7 @@ int zmq::socket_base_t::send (msg_t *msg_, int flags_) int zmq::socket_base_t::recv (msg_t *msg_, int flags_) { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); // Check whether the library haven't been shut down yet. if (unlikely (ctx_terminated)) { @@ -1275,11 +1285,11 @@ int zmq::socket_base_t::recv (msg_t *msg_, int flags_) int zmq::socket_base_t::close () { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); // Remove all existing signalers for thread safe sockets if (thread_safe) - ((mailbox_safe_t*)mailbox)->clear_signalers(); + ((mailbox_safe_t *) mailbox)->clear_signalers (); // Mark the socket as dead tag = 0xdeadbeef; @@ -1311,20 +1321,19 @@ void zmq::socket_base_t::start_reaping (poller_t *poller_) fd_t fd; if (!thread_safe) - fd = ((mailbox_t*)mailbox)->get_fd(); + fd = ((mailbox_t *) mailbox)->get_fd (); else { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); - reaper_signaler = new (std::nothrow) signaler_t(); + reaper_signaler = new (std::nothrow) signaler_t (); zmq_assert (reaper_signaler); // Add signaler to the safe mailbox - fd = reaper_signaler->get_fd(); - ((mailbox_safe_t*)mailbox)->add_signaler(reaper_signaler); + fd = reaper_signaler->get_fd (); + ((mailbox_safe_t *) mailbox)->add_signaler (reaper_signaler); // Send a signal to make sure reaper handle existing commands - reaper_signaler->send(); - + reaper_signaler->send (); } handle = poller->add_fd (fd, this); @@ -1341,12 +1350,9 @@ int zmq::socket_base_t::process_commands (int timeout_, bool throttle_) int rc; command_t cmd; if (timeout_ != 0) { - // If we are asked to wait, simply ask mailbox to wait. rc = mailbox->recv (&cmd, timeout_); - } - else { - + } else { // If we are asked not to wait, check whether we haven't processed // commands recently, so that we can throttle the new commands. @@ -1360,7 +1366,6 @@ int zmq::socket_base_t::process_commands (int timeout_, bool throttle_) // etc. The optimisation makes sense only on platforms where getting // a timestamp is a very cheap operation (tens of nanoseconds). if (tsc && throttle_) { - // Check whether TSC haven't jumped backwards (in case of migration // between CPU cores) and whether certain time have elapsed since // last command processing. If it didn't do nothing. @@ -1398,9 +1403,9 @@ void zmq::socket_base_t::process_stop () // We'll remember the fact so that any blocking call is interrupted and any // further attempt to use the socket will return ETERM. The user is still // responsible for calling zmq_close on the socket though! - scoped_lock_t lock(monitor_sync); + scoped_lock_t lock (monitor_sync); stop_monitor (); - + ctx_terminated = true; } @@ -1418,7 +1423,7 @@ void zmq::socket_base_t::process_term (int linger_) // Ask all attached pipes to terminate. for (pipes_t::size_type i = 0; i != pipes.size (); ++i) - pipes [i]->terminate (false); + pipes[i]->terminate (false); register_term_acks ((int) pipes.size ()); // Continue the termination process immediately. @@ -1427,21 +1432,18 @@ void zmq::socket_base_t::process_term (int linger_) void zmq::socket_base_t::process_term_endpoint (std::string *endpoint_) { - term_endpoint (endpoint_->c_str()); + term_endpoint (endpoint_->c_str ()); delete endpoint_; } -void zmq::socket_base_t::update_pipe_options(int option_) +void zmq::socket_base_t::update_pipe_options (int option_) { - if (option_ == ZMQ_SNDHWM || option_ == ZMQ_RCVHWM) - { - for (pipes_t::size_type i = 0; i != pipes.size(); ++i) - { - pipes[i]->set_hwms(options.rcvhwm, options.sndhwm); - pipes[i]->send_hwms_to_peer(options.sndhwm, options.rcvhwm); + if (option_ == ZMQ_SNDHWM || option_ == ZMQ_RCVHWM) { + for (pipes_t::size_type i = 0; i != pipes.size (); ++i) { + pipes[i]->set_hwms (options.rcvhwm, options.sndhwm); + pipes[i]->send_hwms_to_peer (options.sndhwm, options.rcvhwm); } } - } void zmq::socket_base_t::process_destroy () @@ -1518,16 +1520,16 @@ void zmq::socket_base_t::in_event () // of the reaper thread. Process any commands from other threads/sockets // that may be available at the moment. Ultimately, the socket will // be destroyed. - { - scoped_optional_lock_t sync_lock(thread_safe ? &sync : NULL); + { + scoped_optional_lock_t sync_lock (thread_safe ? &sync : NULL); - // If the socket is thread safe we need to unsignal the reaper signaler - if (thread_safe) - reaper_signaler->recv(); + // If the socket is thread safe we need to unsignal the reaper signaler + if (thread_safe) + reaper_signaler->recv (); - process_commands (0, false); - } - check_destroy(); + process_commands (0, false); + } + check_destroy (); } void zmq::socket_base_t::out_event () @@ -1544,7 +1546,6 @@ void zmq::socket_base_t::check_destroy () { // If the object was already marked as destroyed, finish the deallocation. if (destroyed) { - // Remove the socket from the reaper's poller. poller->rm_fd (handle); @@ -1609,8 +1610,8 @@ void zmq::socket_base_t::extract_flags (msg_t *msg_) int zmq::socket_base_t::monitor (const char *addr_, int events_) { - scoped_lock_t lock(monitor_sync); - + scoped_lock_t lock (monitor_sync); + if (unlikely (ctx_terminated)) { errno = ETERM; return -1; @@ -1644,65 +1645,73 @@ int zmq::socket_base_t::monitor (const char *addr_, int events_) // Never block context termination on pending event messages int linger = 0; - int rc = zmq_setsockopt (monitor_socket, ZMQ_LINGER, &linger, sizeof (linger)); + int rc = + zmq_setsockopt (monitor_socket, ZMQ_LINGER, &linger, sizeof (linger)); if (rc == -1) stop_monitor (false); // Spawn the monitor socket endpoint rc = zmq_bind (monitor_socket, addr_); if (rc == -1) - stop_monitor (false); + stop_monitor (false); return rc; } -void zmq::socket_base_t::event_connected (const std::string &addr_, zmq::fd_t fd_) +void zmq::socket_base_t::event_connected (const std::string &addr_, + zmq::fd_t fd_) { - event(addr_, fd_, ZMQ_EVENT_CONNECTED); + event (addr_, fd_, ZMQ_EVENT_CONNECTED); } -void zmq::socket_base_t::event_connect_delayed (const std::string &addr_, int err_) +void zmq::socket_base_t::event_connect_delayed (const std::string &addr_, + int err_) { - event(addr_, err_, ZMQ_EVENT_CONNECT_DELAYED); + event (addr_, err_, ZMQ_EVENT_CONNECT_DELAYED); } -void zmq::socket_base_t::event_connect_retried (const std::string &addr_, int interval_) +void zmq::socket_base_t::event_connect_retried (const std::string &addr_, + int interval_) { - event(addr_, interval_, ZMQ_EVENT_CONNECT_RETRIED); + event (addr_, interval_, ZMQ_EVENT_CONNECT_RETRIED); } -void zmq::socket_base_t::event_listening (const std::string &addr_, zmq::fd_t fd_) +void zmq::socket_base_t::event_listening (const std::string &addr_, + zmq::fd_t fd_) { - event(addr_, fd_, ZMQ_EVENT_LISTENING); + event (addr_, fd_, ZMQ_EVENT_LISTENING); } void zmq::socket_base_t::event_bind_failed (const std::string &addr_, int err_) { - event(addr_, err_, ZMQ_EVENT_BIND_FAILED); + event (addr_, err_, ZMQ_EVENT_BIND_FAILED); } -void zmq::socket_base_t::event_accepted (const std::string &addr_, zmq::fd_t fd_) +void zmq::socket_base_t::event_accepted (const std::string &addr_, + zmq::fd_t fd_) { - event(addr_, fd_, ZMQ_EVENT_ACCEPTED); + event (addr_, fd_, ZMQ_EVENT_ACCEPTED); } -void zmq::socket_base_t::event_accept_failed (const std::string &addr_, int err_) +void zmq::socket_base_t::event_accept_failed (const std::string &addr_, + int err_) { - event(addr_, err_, ZMQ_EVENT_ACCEPT_FAILED); + event (addr_, err_, ZMQ_EVENT_ACCEPT_FAILED); } void zmq::socket_base_t::event_closed (const std::string &addr_, zmq::fd_t fd_) { - event(addr_, fd_, ZMQ_EVENT_CLOSED); + event (addr_, fd_, ZMQ_EVENT_CLOSED); } void zmq::socket_base_t::event_close_failed (const std::string &addr_, int err_) { - event(addr_, err_, ZMQ_EVENT_CLOSE_FAILED); + event (addr_, err_, ZMQ_EVENT_CLOSE_FAILED); } -void zmq::socket_base_t::event_disconnected (const std::string &addr_, zmq::fd_t fd_) +void zmq::socket_base_t::event_disconnected (const std::string &addr_, + zmq::fd_t fd_) { - event(addr_, fd_, ZMQ_EVENT_DISCONNECTED); + event (addr_, fd_, ZMQ_EVENT_DISCONNECTED); } void zmq::socket_base_t::event_handshake_failed_no_detail ( @@ -1729,17 +1738,20 @@ void zmq::socket_base_t::event_handshake_succeeded (const std::string &addr_, event (addr_, err_, ZMQ_EVENT_HANDSHAKE_SUCCEEDED); } -void zmq::socket_base_t::event(const std::string &addr_, intptr_t value_, int type_) +void zmq::socket_base_t::event (const std::string &addr_, + intptr_t value_, + int type_) { - scoped_lock_t lock(monitor_sync); - if (monitor_events & type_) - { + scoped_lock_t lock (monitor_sync); + if (monitor_events & type_) { monitor_event (type_, value_, addr_); } } // Send a monitor event -void zmq::socket_base_t::monitor_event (int event_, intptr_t value_, const std::string &addr_) +void zmq::socket_base_t::monitor_event (int event_, + intptr_t value_, + const std::string &addr_) { // this is a private method which is only called from // contexts where the mutex has been locked before @@ -1752,12 +1764,12 @@ void zmq::socket_base_t::monitor_event (int event_, intptr_t value_, const std:: // Avoid dereferencing uint32_t on unaligned address uint16_t event = (uint16_t) event_; uint32_t value = (uint32_t) value_; - memcpy (data + 0, &event, sizeof(event)); - memcpy (data + 2, &value, sizeof(value)); + memcpy (data + 0, &event, sizeof (event)); + memcpy (data + 2, &value, sizeof (value)); zmq_sendmsg (monitor_socket, &msg, ZMQ_SNDMORE); // Send address in second frame - zmq_msg_init_size (&msg, addr_.size()); + zmq_msg_init_size (&msg, addr_.size ()); memcpy (zmq_msg_data (&msg), addr_.c_str (), addr_.size ()); zmq_sendmsg (monitor_socket, &msg, 0); } @@ -1769,7 +1781,8 @@ void zmq::socket_base_t::stop_monitor (bool send_monitor_stopped_event_) // contexts where the mutex has been locked before if (monitor_socket) { - if ((monitor_events & ZMQ_EVENT_MONITOR_STOPPED) && send_monitor_stopped_event_) + if ((monitor_events & ZMQ_EVENT_MONITOR_STOPPED) + && send_monitor_stopped_event_) monitor_event (ZMQ_EVENT_MONITOR_STOPPED, 0, ""); zmq_close (monitor_socket); monitor_socket = NULL; diff --git a/src/socket_base.hpp b/src/socket_base.hpp index 430a1be21d..8d85bd5f93 100644 --- a/src/socket_base.hpp +++ b/src/socket_base.hpp @@ -46,262 +46,259 @@ #include "clock.hpp" #include "pipe.hpp" -extern "C" -{ - void zmq_free_event (void *data, void *hint); +extern "C" { +void zmq_free_event (void *data, void *hint); } namespace zmq { +class ctx_t; +class msg_t; +class pipe_t; + +class socket_base_t : public own_t, + public array_item_t<>, + public i_poll_events, + public i_pipe_events +{ + friend class reaper_t; + + public: + // Returns false if object is not a socket. + bool check_tag (); + + // Create a socket of a specified type. + static socket_base_t * + create (int type_, zmq::ctx_t *parent_, uint32_t tid_, int sid_); + + // Returns the mailbox associated with this socket. + i_mailbox *get_mailbox (); + + // Interrupt blocking call if the socket is stuck in one. + // This function can be called from a different thread! + void stop (); + + // Interface for communication with the API layer. + int setsockopt (int option_, const void *optval_, size_t optvallen_); + int getsockopt (int option_, void *optval_, size_t *optvallen_); + int bind (const char *addr_); + int connect (const char *addr_); + int term_endpoint (const char *addr_); + int send (zmq::msg_t *msg_, int flags_); + int recv (zmq::msg_t *msg_, int flags_); + int add_signaler (signaler_t *s); + int remove_signaler (signaler_t *s); + int close (); + + // These functions are used by the polling mechanism to determine + // which events are to be reported from this socket. + bool has_in (); + bool has_out (); + + // Joining and leaving groups + int join (const char *group); + int leave (const char *group); + + // Using this function reaper thread ask the socket to register with + // its poller. + void start_reaping (poller_t *poller_); + + // i_poll_events implementation. This interface is used when socket + // is handled by the poller in the reaper thread. + void in_event (); + void out_event (); + void timer_event (int id_); + + // i_pipe_events interface implementation. + void read_activated (pipe_t *pipe_); + void write_activated (pipe_t *pipe_); + void hiccuped (pipe_t *pipe_); + void pipe_terminated (pipe_t *pipe_); + void lock (); + void unlock (); + + int monitor (const char *endpoint_, int events_); + + void event_connected (const std::string &addr_, zmq::fd_t fd_); + void event_connect_delayed (const std::string &addr_, int err_); + void event_connect_retried (const std::string &addr_, int interval_); + void event_listening (const std::string &addr_, zmq::fd_t fd_); + void event_bind_failed (const std::string &addr_, int err_); + void event_accepted (const std::string &addr_, zmq::fd_t fd_); + void event_accept_failed (const std::string &addr_, int err_); + void event_closed (const std::string &addr_, zmq::fd_t fd_); + void event_close_failed (const std::string &addr_, int err_); + void event_disconnected (const std::string &addr_, zmq::fd_t fd_); + void event_handshake_failed_no_detail (const std::string &addr_, int err_); + void event_handshake_failed_protocol (const std::string &addr_, int err_); + void event_handshake_failed_auth (const std::string &addr_, int err_); + void event_handshake_succeeded (const std::string &addr_, int err_); + + // Query the state of a specific peer. The default implementation + // always returns an ENOTSUP error. + virtual int get_peer_state (const void *identity, + size_t identity_size) const; + + protected: + socket_base_t (zmq::ctx_t *parent_, + uint32_t tid_, + int sid_, + bool thread_safe_ = false); + virtual ~socket_base_t (); + + // Concrete algorithms for the x- methods are to be defined by + // individual socket types. + virtual void xattach_pipe (zmq::pipe_t *pipe_, + bool subscribe_to_all_ = false) = 0; + + // The default implementation assumes there are no specific socket + // options for the particular socket type. If not so, override this + // method. + virtual int + xsetsockopt (int option_, const void *optval_, size_t optvallen_); + + // The default implementation assumes that send is not supported. + virtual bool xhas_out (); + virtual int xsend (zmq::msg_t *msg_); + + // The default implementation assumes that recv in not supported. + virtual bool xhas_in (); + virtual int xrecv (zmq::msg_t *msg_); + + // Returns the credential for the peer from which we have received + // the last message. If no message has been received yet, + // the function returns empty credential. + virtual const blob_t &get_credential () const; + + // i_pipe_events will be forwarded to these functions. + virtual void xread_activated (pipe_t *pipe_); + virtual void xwrite_activated (pipe_t *pipe_); + virtual void xhiccuped (pipe_t *pipe_); + virtual void xpipe_terminated (pipe_t *pipe_) = 0; + + // the default implementation assumes that joub and leave are not supported. + virtual int xjoin (const char *group_); + virtual int xleave (const char *group_); + + // Delay actual destruction of the socket. + void process_destroy (); + + // Next assigned name on a zmq_connect() call used by ROUTER and STREAM socket types + std::string connect_routing_id; + + private: + // test if event should be sent and then dispatch it + void event (const std::string &addr_, intptr_t fd_, int type_); + + // Socket event data dispatch + void monitor_event (int event_, intptr_t value_, const std::string &addr_); + + // Monitor socket cleanup + void stop_monitor (bool send_monitor_stopped_event_ = true); + + // Creates new endpoint ID and adds the endpoint to the map. + void add_endpoint (const char *addr_, own_t *endpoint_, pipe_t *pipe); + + // Map of open endpoints. + typedef std::pair endpoint_pipe_t; + typedef std::multimap endpoints_t; + endpoints_t endpoints; + + // Map of open inproc endpoints. + typedef std::multimap inprocs_t; + inprocs_t inprocs; + + // To be called after processing commands or invoking any command + // handlers explicitly. If required, it will deallocate the socket. + void check_destroy (); + + // Moves the flags from the message to local variables, + // to be later retrieved by getsockopt. + void extract_flags (msg_t *msg_); + + // Used to check whether the object is a socket. + uint32_t tag; + + // If true, associated context was already terminated. + bool ctx_terminated; + + // If true, object should have been already destroyed. However, + // destruction is delayed while we unwind the stack to the point + // where it doesn't intersect the object being destroyed. + bool destroyed; - class ctx_t; - class msg_t; - class pipe_t; - - class socket_base_t : - public own_t, - public array_item_t <>, - public i_poll_events, - public i_pipe_events - { - friend class reaper_t; - - public: - - // Returns false if object is not a socket. - bool check_tag (); - - // Create a socket of a specified type. - static socket_base_t *create (int type_, zmq::ctx_t *parent_, - uint32_t tid_, int sid_); - - // Returns the mailbox associated with this socket. - i_mailbox *get_mailbox (); - - // Interrupt blocking call if the socket is stuck in one. - // This function can be called from a different thread! - void stop (); - - // Interface for communication with the API layer. - int setsockopt (int option_, const void *optval_, size_t optvallen_); - int getsockopt (int option_, void *optval_, size_t *optvallen_); - int bind (const char *addr_); - int connect (const char *addr_); - int term_endpoint (const char *addr_); - int send (zmq::msg_t *msg_, int flags_); - int recv (zmq::msg_t *msg_, int flags_); - int add_signaler (signaler_t *s); - int remove_signaler (signaler_t *s); - int close (); - - // These functions are used by the polling mechanism to determine - // which events are to be reported from this socket. - bool has_in (); - bool has_out (); - - // Joining and leaving groups - int join (const char *group); - int leave (const char *group); - - // Using this function reaper thread ask the socket to register with - // its poller. - void start_reaping (poller_t *poller_); - - // i_poll_events implementation. This interface is used when socket - // is handled by the poller in the reaper thread. - void in_event (); - void out_event (); - void timer_event (int id_); - - // i_pipe_events interface implementation. - void read_activated (pipe_t *pipe_); - void write_activated (pipe_t *pipe_); - void hiccuped (pipe_t *pipe_); - void pipe_terminated (pipe_t *pipe_); - void lock(); - void unlock(); - - int monitor (const char *endpoint_, int events_); - - void event_connected (const std::string &addr_, zmq::fd_t fd_); - void event_connect_delayed (const std::string &addr_, int err_); - void event_connect_retried (const std::string &addr_, int interval_); - void event_listening (const std::string &addr_, zmq::fd_t fd_); - void event_bind_failed (const std::string &addr_, int err_); - void event_accepted (const std::string &addr_, zmq::fd_t fd_); - void event_accept_failed (const std::string &addr_, int err_); - void event_closed (const std::string &addr_, zmq::fd_t fd_); - void event_close_failed (const std::string &addr_, int err_); - void event_disconnected (const std::string &addr_, zmq::fd_t fd_); - void event_handshake_failed_no_detail(const std::string &addr_, int err_); - void event_handshake_failed_protocol(const std::string &addr_, int err_); - void event_handshake_failed_auth(const std::string &addr_, int err_); - void event_handshake_succeeded(const std::string &addr_, int err_); - - // Query the state of a specific peer. The default implementation - // always returns an ENOTSUP error. - virtual int get_peer_state (const void *identity, - size_t identity_size) const; - - protected: - - socket_base_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_, bool thread_safe_ = false); - virtual ~socket_base_t (); - - // Concrete algorithms for the x- methods are to be defined by - // individual socket types. - virtual void xattach_pipe (zmq::pipe_t *pipe_, - bool subscribe_to_all_ = false) = 0; - - // The default implementation assumes there are no specific socket - // options for the particular socket type. If not so, override this - // method. - virtual int xsetsockopt (int option_, const void *optval_, - size_t optvallen_); - - // The default implementation assumes that send is not supported. - virtual bool xhas_out (); - virtual int xsend (zmq::msg_t *msg_); - - // The default implementation assumes that recv in not supported. - virtual bool xhas_in (); - virtual int xrecv (zmq::msg_t *msg_); - - // Returns the credential for the peer from which we have received - // the last message. If no message has been received yet, - // the function returns empty credential. - virtual const blob_t &get_credential () const; - - // i_pipe_events will be forwarded to these functions. - virtual void xread_activated (pipe_t *pipe_); - virtual void xwrite_activated (pipe_t *pipe_); - virtual void xhiccuped (pipe_t *pipe_); - virtual void xpipe_terminated (pipe_t *pipe_) = 0; - - // the default implementation assumes that joub and leave are not supported. - virtual int xjoin (const char *group_); - virtual int xleave (const char *group_); - - // Delay actual destruction of the socket. - void process_destroy (); - - // Next assigned name on a zmq_connect() call used by ROUTER and STREAM socket types - std::string connect_routing_id; - - private: - // test if event should be sent and then dispatch it - void event(const std::string &addr_, intptr_t fd_, int type_); - - // Socket event data dispatch - void monitor_event (int event_, intptr_t value_, const std::string& addr_); - - // Monitor socket cleanup - void stop_monitor (bool send_monitor_stopped_event_ = true); - - // Creates new endpoint ID and adds the endpoint to the map. - void add_endpoint (const char *addr_, own_t *endpoint_, pipe_t *pipe); - - // Map of open endpoints. - typedef std::pair endpoint_pipe_t; - typedef std::multimap endpoints_t; - endpoints_t endpoints; - - // Map of open inproc endpoints. - typedef std::multimap inprocs_t; - inprocs_t inprocs; - - // To be called after processing commands or invoking any command - // handlers explicitly. If required, it will deallocate the socket. - void check_destroy (); - - // Moves the flags from the message to local variables, - // to be later retrieved by getsockopt. - void extract_flags (msg_t *msg_); - - // Used to check whether the object is a socket. - uint32_t tag; - - // If true, associated context was already terminated. - bool ctx_terminated; - - // If true, object should have been already destroyed. However, - // destruction is delayed while we unwind the stack to the point - // where it doesn't intersect the object being destroyed. - bool destroyed; - - // Parse URI string. - int parse_uri (const char *uri_, std::string &protocol_, - std::string &address_); - - // Check whether transport protocol, as specified in connect or - // bind, is available and compatible with the socket type. - int check_protocol (const std::string &protocol_); + // Parse URI string. + int + parse_uri (const char *uri_, std::string &protocol_, std::string &address_); - // Register the pipe with this socket. - void attach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_ = false); + // Check whether transport protocol, as specified in connect or + // bind, is available and compatible with the socket type. + int check_protocol (const std::string &protocol_); - // Processes commands sent to this socket (if any). If timeout is -1, - // returns only after at least one command was processed. - // If throttle argument is true, commands are processed at most once - // in a predefined time period. - int process_commands (int timeout_, bool throttle_); + // Register the pipe with this socket. + void attach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_ = false); - // Handlers for incoming commands. - void process_stop (); - void process_bind (zmq::pipe_t *pipe_); - void process_term (int linger_); - void process_term_endpoint (std::string *endpoint_); + // Processes commands sent to this socket (if any). If timeout is -1, + // returns only after at least one command was processed. + // If throttle argument is true, commands are processed at most once + // in a predefined time period. + int process_commands (int timeout_, bool throttle_); - void update_pipe_options(int option_); + // Handlers for incoming commands. + void process_stop (); + void process_bind (zmq::pipe_t *pipe_); + void process_term (int linger_); + void process_term_endpoint (std::string *endpoint_); - // Socket's mailbox object. - i_mailbox *mailbox; + void update_pipe_options (int option_); - // List of attached pipes. - typedef array_t pipes_t; - pipes_t pipes; + // Socket's mailbox object. + i_mailbox *mailbox; - // Reaper's poller and handle of this socket within it. - poller_t *poller; - poller_t::handle_t handle; + // List of attached pipes. + typedef array_t pipes_t; + pipes_t pipes; - // Timestamp of when commands were processed the last time. - uint64_t last_tsc; + // Reaper's poller and handle of this socket within it. + poller_t *poller; + poller_t::handle_t handle; - // Number of messages received since last command processing. - int ticks; + // Timestamp of when commands were processed the last time. + uint64_t last_tsc; - // True if the last message received had MORE flag set. - bool rcvmore; + // Number of messages received since last command processing. + int ticks; - // Improves efficiency of time measurement. - clock_t clock; + // True if the last message received had MORE flag set. + bool rcvmore; - // Monitor socket; - void *monitor_socket; + // Improves efficiency of time measurement. + clock_t clock; - // Bitmask of events being monitored - int monitor_events; + // Monitor socket; + void *monitor_socket; - // Last socket endpoint resolved URI - std::string last_endpoint; + // Bitmask of events being monitored + int monitor_events; - // Indicate if the socket is thread safe - bool thread_safe; + // Last socket endpoint resolved URI + std::string last_endpoint; - // Signaler to be used in the reaping stage - signaler_t* reaper_signaler; + // Indicate if the socket is thread safe + bool thread_safe; - // Mutex for synchronize access to the socket in thread safe mode - mutex_t sync; + // Signaler to be used in the reaping stage + signaler_t *reaper_signaler; - // Mutex to synchronize access to the monitor Pair socket - mutex_t monitor_sync; + // Mutex for synchronize access to the socket in thread safe mode + mutex_t sync; - socket_base_t (const socket_base_t&); - const socket_base_t &operator = (const socket_base_t&); - }; + // Mutex to synchronize access to the monitor Pair socket + mutex_t monitor_sync; + socket_base_t (const socket_base_t &); + const socket_base_t &operator= (const socket_base_t &); +}; } #endif diff --git a/src/socket_poller.cpp b/src/socket_poller.cpp index e09ade2890..d21791afa1 100644 --- a/src/socket_poller.cpp +++ b/src/socket_poller.cpp @@ -36,13 +36,13 @@ zmq::socket_poller_t::socket_poller_t () : signaler (NULL), need_rebuild (true), use_signaler (false), - poll_size(0) + poll_size (0) #if defined ZMQ_POLL_BASED_ON_POLL , pollfds (NULL) #elif defined ZMQ_POLL_BASED_ON_SELECT , - maxfd(0) + maxfd (0) #endif { #if defined ZMQ_POLL_BASED_ON_SELECT @@ -54,9 +54,9 @@ zmq::socket_poller_t::socket_poller_t () : FD_ZERO (&pollset_out); FD_ZERO (&pollset_err); #else - memset(&pollset_in, 0, sizeof(pollset_in)); - memset(&pollset_out, 0, sizeof(pollset_out)); - memset(&pollset_err, 0, sizeof(pollset_err)); + memset (&pollset_in, 0, sizeof (pollset_in)); + memset (&pollset_out, 0, sizeof (pollset_out)); + memset (&pollset_err, 0, sizeof (pollset_err)); #endif #endif } @@ -66,12 +66,15 @@ zmq::socket_poller_t::~socket_poller_t () // Mark the socket_poller as dead tag = 0xdeadbeef; - for (items_t::iterator it = items.begin(); it != items.end(); ++it) { - if (it->socket && it->socket->check_tag()) { + for (items_t::iterator it = items.begin (); it != items.end (); ++it) { + if (it->socket && it->socket->check_tag ()) { int thread_safe; - size_t thread_safe_size = sizeof(int); + size_t thread_safe_size = sizeof (int); - if (it->socket->getsockopt (ZMQ_THREAD_SAFE, &thread_safe, &thread_safe_size) == 0 && thread_safe) + if (it->socket->getsockopt (ZMQ_THREAD_SAFE, &thread_safe, + &thread_safe_size) + == 0 + && thread_safe) it->socket->remove_signaler (signaler); } } @@ -94,7 +97,9 @@ bool zmq::socket_poller_t::check_tag () return tag == 0xCAFEBABE; } -int zmq::socket_poller_t::add (socket_base_t *socket_, void* user_data_, short events_) +int zmq::socket_poller_t::add (socket_base_t *socket_, + void *user_data_, + short events_) { for (items_t::iterator it = items.begin (); it != items.end (); ++it) { if (it->socket == socket_) { @@ -104,7 +109,7 @@ int zmq::socket_poller_t::add (socket_base_t *socket_, void* user_data_, short e } int thread_safe; - size_t thread_safe_size = sizeof(int); + size_t thread_safe_size = sizeof (int); int rc = socket_->getsockopt (ZMQ_THREAD_SAFE, &thread_safe, &thread_safe_size); @@ -129,9 +134,14 @@ int zmq::socket_poller_t::add (socket_base_t *socket_, void* user_data_, short e zmq_assert (rc == 0); } - item_t item = {socket_, 0, user_data_, events_ + item_t item = { + socket_, + 0, + user_data_, + events_ #if defined ZMQ_POLL_BASED_ON_POLL - ,-1 + , + -1 #endif }; items.push_back (item); @@ -142,25 +152,30 @@ int zmq::socket_poller_t::add (socket_base_t *socket_, void* user_data_, short e int zmq::socket_poller_t::add_fd (fd_t fd_, void *user_data_, short events_) { - for (items_t::iterator it = items.begin (); it != items.end (); ++it) { + for (items_t::iterator it = items.begin (); it != items.end (); ++it) { if (!it->socket && it->fd == fd_) { errno = EINVAL; return -1; } } - item_t item = {NULL, fd_, user_data_, events_ + item_t item = { + NULL, + fd_, + user_data_, + events_ #if defined ZMQ_POLL_BASED_ON_POLL - ,-1 + , + -1 #endif - }; + }; items.push_back (item); need_rebuild = true; return 0; } -int zmq::socket_poller_t::modify (socket_base_t *socket_, short events_) +int zmq::socket_poller_t::modify (socket_base_t *socket_, short events_) { items_t::iterator it; @@ -169,7 +184,7 @@ int zmq::socket_poller_t::modify (socket_base_t *socket_, short events_) break; } - if (it == items.end()) { + if (it == items.end ()) { errno = EINVAL; return -1; } @@ -190,7 +205,7 @@ int zmq::socket_poller_t::modify_fd (fd_t fd_, short events_) break; } - if (it == items.end()) { + if (it == items.end ()) { errno = EINVAL; return -1; } @@ -211,18 +226,20 @@ int zmq::socket_poller_t::remove (socket_base_t *socket_) break; } - if (it == items.end()) { + if (it == items.end ()) { errno = EINVAL; return -1; } - items.erase(it); + items.erase (it); need_rebuild = true; int thread_safe; - size_t thread_safe_size = sizeof(int); + size_t thread_safe_size = sizeof (int); - if (socket_->getsockopt (ZMQ_THREAD_SAFE, &thread_safe, &thread_safe_size) == 0 && thread_safe) + if (socket_->getsockopt (ZMQ_THREAD_SAFE, &thread_safe, &thread_safe_size) + == 0 + && thread_safe) socket_->remove_signaler (signaler); return 0; @@ -237,7 +254,7 @@ int zmq::socket_poller_t::remove_fd (fd_t fd_) break; } - if (it == items.end()) { + if (it == items.end ()) { errno = EINVAL; return -1; } @@ -265,7 +282,7 @@ void zmq::socket_poller_t::rebuild () if (it->events) { if (it->socket) { int thread_safe; - size_t thread_safe_size = sizeof(int); + size_t thread_safe_size = sizeof (int); int rc = it->socket->getsockopt (ZMQ_THREAD_SAFE, &thread_safe, &thread_safe_size); @@ -276,11 +293,9 @@ void zmq::socket_poller_t::rebuild () use_signaler = true; poll_size++; } - } - else + } else poll_size++; - } - else + } else poll_size++; } } @@ -288,14 +303,14 @@ void zmq::socket_poller_t::rebuild () if (poll_size == 0) return; - pollfds = (pollfd*) malloc (poll_size * sizeof (pollfd)); + pollfds = (pollfd *) malloc (poll_size * sizeof (pollfd)); alloc_assert (pollfds); int item_nbr = 0; if (use_signaler) { item_nbr = 1; - pollfds[0].fd = signaler->get_fd(); + pollfds[0].fd = signaler->get_fd (); pollfds[0].events = POLLIN; } @@ -303,7 +318,7 @@ void zmq::socket_poller_t::rebuild () if (it->events) { if (it->socket) { int thread_safe; - size_t thread_safe_size = sizeof(int); + size_t thread_safe_size = sizeof (int); int rc = it->socket->getsockopt (ZMQ_THREAD_SAFE, &thread_safe, &thread_safe_size); @@ -311,26 +326,26 @@ void zmq::socket_poller_t::rebuild () if (!thread_safe) { size_t fd_size = sizeof (zmq::fd_t); - rc = it->socket->getsockopt (ZMQ_FD, &pollfds [item_nbr].fd, &fd_size); + rc = it->socket->getsockopt (ZMQ_FD, &pollfds[item_nbr].fd, + &fd_size); zmq_assert (rc == 0); - pollfds [item_nbr].events = POLLIN; + pollfds[item_nbr].events = POLLIN; item_nbr++; } - } - else { - pollfds [item_nbr].fd = it->fd; - pollfds [item_nbr].events = - (it->events & ZMQ_POLLIN ? POLLIN : 0) | - (it->events & ZMQ_POLLOUT ? POLLOUT : 0) | - (it->events & ZMQ_POLLPRI ? POLLPRI : 0); + } else { + pollfds[item_nbr].fd = it->fd; + pollfds[item_nbr].events = + (it->events & ZMQ_POLLIN ? POLLIN : 0) + | (it->events & ZMQ_POLLOUT ? POLLOUT : 0) + | (it->events & ZMQ_POLLPRI ? POLLPRI : 0); it->pollfd_index = item_nbr; item_nbr++; } } } - #elif defined ZMQ_POLL_BASED_ON_SELECT +#elif defined ZMQ_POLL_BASED_ON_SELECT FD_ZERO (&pollset_in); FD_ZERO (&pollset_out); @@ -347,7 +362,7 @@ void zmq::socket_poller_t::rebuild () for (items_t::iterator it = items.begin (); it != items.end (); ++it) { if (it->socket) { int thread_safe; - size_t thread_safe_size = sizeof(int); + size_t thread_safe_size = sizeof (int); int rc = it->socket->getsockopt (ZMQ_THREAD_SAFE, &thread_safe, &thread_safe_size); @@ -371,7 +386,7 @@ void zmq::socket_poller_t::rebuild () // notification file descriptor retrieved by the ZMQ_FD socket option. if (it->socket) { int thread_safe; - size_t thread_safe_size = sizeof(int); + size_t thread_safe_size = sizeof (int); int rc = it->socket->getsockopt (ZMQ_THREAD_SAFE, &thread_safe, &thread_safe_size); @@ -413,9 +428,7 @@ void zmq::socket_poller_t::rebuild () } void zmq::socket_poller_t::zero_trail_events ( - zmq::socket_poller_t::event_t *events_, - int n_events_, - int found) + zmq::socket_poller_t::event_t *events_, int n_events_, int found) { for (int i = found; i < n_events_; ++i) { events_[i].socket = NULL; @@ -427,26 +440,25 @@ void zmq::socket_poller_t::zero_trail_events ( #if defined ZMQ_POLL_BASED_ON_POLL int zmq::socket_poller_t::check_events (zmq::socket_poller_t::event_t *events_, - int n_events_) + int n_events_) #elif defined ZMQ_POLL_BASED_ON_SELECT int zmq::socket_poller_t::check_events (zmq::socket_poller_t::event_t *events_, - int n_events_, - fd_set& inset, - fd_set& outset, - fd_set& errset) + int n_events_, + fd_set &inset, + fd_set &outset, + fd_set &errset) #endif { int found = 0; - for (items_t::iterator it = items.begin (); it != items.end () && - found < n_events_; ++it) { - + for (items_t::iterator it = items.begin (); + it != items.end () && found < n_events_; ++it) { // The poll item is a 0MQ socket. Retrieve pending events // using the ZMQ_EVENTS socket option. if (it->socket) { size_t events_size = sizeof (uint32_t); uint32_t events; if (it->socket->getsockopt (ZMQ_EVENTS, &events, &events_size) - == -1) { + == -1) { return -1; } @@ -460,10 +472,9 @@ int zmq::socket_poller_t::check_events (zmq::socket_poller_t::event_t *events_, // Else, the poll item is a raw file descriptor, simply convert // the events to zmq_pollitem_t-style format. else { - #if defined ZMQ_POLL_BASED_ON_POLL - short revents = pollfds [it->pollfd_index].revents; + short revents = pollfds[it->pollfd_index].revents; short events = 0; if (revents & POLLIN) @@ -501,12 +512,12 @@ int zmq::socket_poller_t::check_events (zmq::socket_poller_t::event_t *events_, } //Return 0 if timeout is expired otherwise 1 -int zmq::socket_poller_t::adjust_timeout (zmq::clock_t& clock, long timeout_, - uint64_t& now, - uint64_t& end, - bool& first_pass) +int zmq::socket_poller_t::adjust_timeout (zmq::clock_t &clock, + long timeout_, + uint64_t &now, + uint64_t &end, + bool &first_pass) { - // If socket_poller_t::timeout is zero, exit immediately whether there // are events or not. if (timeout_ == 0) @@ -539,8 +550,8 @@ int zmq::socket_poller_t::adjust_timeout (zmq::clock_t& clock, long timeout_, } int zmq::socket_poller_t::wait (zmq::socket_poller_t::event_t *events_, - int n_events_, - long timeout_) + int n_events_, + long timeout_) { if (items.empty () && timeout_ < 0) { errno = EFAULT; @@ -586,8 +597,7 @@ int zmq::socket_poller_t::wait (zmq::socket_poller_t::event_t *events_, int timeout; if (first_pass) timeout = 0; - else - if (timeout_ < 0) + else if (timeout_ < 0) timeout = -1; else timeout = end - now; @@ -632,7 +642,6 @@ int zmq::socket_poller_t::wait (zmq::socket_poller_t::event_t *events_, fd_set inset, outset, errset; while (true) { - // Compute the timeout for the subsequent poll. timeval timeout; timeval *ptimeout; @@ -640,9 +649,7 @@ int zmq::socket_poller_t::wait (zmq::socket_poller_t::event_t *events_, timeout.tv_sec = 0; timeout.tv_usec = 0; ptimeout = &timeout; - } - else - if (timeout_ < 0) + } else if (timeout_ < 0) ptimeout = NULL; else { timeout.tv_sec = (long) ((end - now) / 1000); @@ -657,9 +664,15 @@ int zmq::socket_poller_t::wait (zmq::socket_poller_t::event_t *events_, // SOCKETS are continuous from the beginning of fd_array in fd_set. // We just need to copy fd_count elements of fd_array. // We gain huge memcpy() improvement if number of used SOCKETs is much lower than FD_SETSIZE. - memcpy (&inset, &pollset_in, (char *) (pollset_in.fd_array + pollset_in.fd_count ) - (char *) &pollset_in ); - memcpy (&outset, &pollset_out, (char *) (pollset_out.fd_array + pollset_out.fd_count) - (char *) &pollset_out); - memcpy (&errset, &pollset_err, (char *) (pollset_err.fd_array + pollset_err.fd_count) - (char *) &pollset_err); + memcpy (&inset, &pollset_in, + (char *) (pollset_in.fd_array + pollset_in.fd_count) + - (char *) &pollset_in); + memcpy (&outset, &pollset_out, + (char *) (pollset_out.fd_array + pollset_out.fd_count) + - (char *) &pollset_out); + memcpy (&errset, &pollset_err, + (char *) (pollset_err.fd_array + pollset_err.fd_count) + - (char *) &pollset_err); int rc = select (0, &inset, &outset, &errset, ptimeout); if (unlikely (rc == SOCKET_ERROR)) { errno = zmq::wsa_error_to_errno (WSAGetLastError ()); @@ -683,7 +696,7 @@ int zmq::socket_poller_t::wait (zmq::socket_poller_t::event_t *events_, signaler->recv (); // Check for the events. - int found = check_events(events_, n_events_, inset, outset, errset); + int found = check_events (events_, n_events_, inset, outset, errset); if (found) { if (found > 0) zero_trail_events (events_, n_events_, found); diff --git a/src/socket_poller.hpp b/src/socket_poller.hpp index a774ce6a2b..67599d920a 100644 --- a/src/socket_poller.hpp +++ b/src/socket_poller.hpp @@ -50,96 +50,97 @@ namespace zmq { +class socket_poller_t +{ + public: + socket_poller_t (); + ~socket_poller_t (); - class socket_poller_t + typedef struct event_t { - public: - socket_poller_t (); - ~socket_poller_t (); - - typedef struct event_t - { - socket_base_t *socket; - fd_t fd; - void *user_data; - short events; - } event_t; + socket_base_t *socket; + fd_t fd; + void *user_data; + short events; + } event_t; - int add (socket_base_t *socket, void *user_data, short events); - int modify (socket_base_t *socket, short events); - int remove (socket_base_t *socket); + int add (socket_base_t *socket, void *user_data, short events); + int modify (socket_base_t *socket, short events); + int remove (socket_base_t *socket); - int add_fd (fd_t fd, void *user_data, short events); - int modify_fd (fd_t fd, short events); - int remove_fd (fd_t fd); + int add_fd (fd_t fd, void *user_data, short events); + int modify_fd (fd_t fd, short events); + int remove_fd (fd_t fd); - int wait (event_t *event, int n_events, long timeout); + int wait (event_t *event, int n_events, long timeout); - inline int size (void) { return static_cast (items.size ()); }; + inline int size (void) { return static_cast (items.size ()); }; - // Return false if object is not a socket. - bool check_tag (); + // Return false if object is not a socket. + bool check_tag (); - private: - void zero_trail_events (zmq::socket_poller_t::event_t *events_, - int n_events_, - int found); + private: + void zero_trail_events (zmq::socket_poller_t::event_t *events_, + int n_events_, + int found); #if defined ZMQ_POLL_BASED_ON_POLL - int check_events (zmq::socket_poller_t::event_t *events_, - int n_events_); + int check_events (zmq::socket_poller_t::event_t *events_, int n_events_); #elif defined ZMQ_POLL_BASED_ON_SELECT - int check_events (zmq::socket_poller_t::event_t *events_, int n_events_, - fd_set& inset, - fd_set& outset, - fd_set& errset); + int check_events (zmq::socket_poller_t::event_t *events_, + int n_events_, + fd_set &inset, + fd_set &outset, + fd_set &errset); #endif - int adjust_timeout (zmq::clock_t& clock, long timeout_, uint64_t& now, - uint64_t& end, - bool& first_pass); - void rebuild (); - - // Used to check whether the object is a socket_poller. - uint32_t tag; - - // Signaler used for thread safe sockets polling - signaler_t* signaler; - - typedef struct item_t { - socket_base_t *socket; - fd_t fd; - void *user_data; - short events; + int adjust_timeout (zmq::clock_t &clock, + long timeout_, + uint64_t &now, + uint64_t &end, + bool &first_pass); + void rebuild (); + + // Used to check whether the object is a socket_poller. + uint32_t tag; + + // Signaler used for thread safe sockets polling + signaler_t *signaler; + + typedef struct item_t + { + socket_base_t *socket; + fd_t fd; + void *user_data; + short events; #if defined ZMQ_POLL_BASED_ON_POLL - int pollfd_index; + int pollfd_index; #endif - } item_t; + } item_t; - // List of sockets - typedef std::vector items_t; - items_t items; + // List of sockets + typedef std::vector items_t; + items_t items; - // Does the pollset needs rebuilding? - bool need_rebuild; + // Does the pollset needs rebuilding? + bool need_rebuild; - // Should the signaler be used for the thread safe polling? - bool use_signaler; + // Should the signaler be used for the thread safe polling? + bool use_signaler; - // Size of the pollset - int poll_size; + // Size of the pollset + int poll_size; #if defined ZMQ_POLL_BASED_ON_POLL - pollfd *pollfds; + pollfd *pollfds; #elif defined ZMQ_POLL_BASED_ON_SELECT - fd_set pollset_in; - fd_set pollset_out; - fd_set pollset_err; - zmq::fd_t maxfd; + fd_set pollset_in; + fd_set pollset_out; + fd_set pollset_err; + zmq::fd_t maxfd; #endif - socket_poller_t (const socket_poller_t&); - const socket_poller_t &operator = (const socket_poller_t&); - }; - + socket_poller_t (const socket_poller_t &); + const socket_poller_t &operator= (const socket_poller_t &); +}; } #endif diff --git a/src/socks.cpp b/src/socks.cpp index 6a7cb2e72a..148d76f1a9 100644 --- a/src/socks.cpp +++ b/src/socks.cpp @@ -40,23 +40,24 @@ #include #endif -zmq::socks_greeting_t::socks_greeting_t (uint8_t method_) : - num_methods (1) +zmq::socks_greeting_t::socks_greeting_t (uint8_t method_) : num_methods (1) { - methods [0] = method_; + methods[0] = method_; } -zmq::socks_greeting_t::socks_greeting_t ( - uint8_t *methods_, uint8_t num_methods_) - : num_methods (num_methods_) +zmq::socks_greeting_t::socks_greeting_t (uint8_t *methods_, + uint8_t num_methods_) : + num_methods (num_methods_) { for (uint8_t i = 0; i < num_methods_; i++) - methods [i] = methods_ [i]; + methods[i] = methods_[i]; } -zmq::socks_greeting_encoder_t::socks_greeting_encoder_t () - : bytes_encoded (0), bytes_written (0) -{} +zmq::socks_greeting_encoder_t::socks_greeting_encoder_t () : + bytes_encoded (0), + bytes_written (0) +{ +} void zmq::socks_greeting_encoder_t::encode (const socks_greeting_t &greeting_) { @@ -65,7 +66,7 @@ void zmq::socks_greeting_encoder_t::encode (const socks_greeting_t &greeting_) *ptr++ = 0x05; *ptr++ = (uint8_t) greeting_.num_methods; for (uint8_t i = 0; i < greeting_.num_methods; i++) - *ptr++ = greeting_.methods [i]; + *ptr++ = greeting_.methods[i]; bytes_encoded = 2 + greeting_.num_methods; bytes_written = 0; @@ -73,10 +74,10 @@ void zmq::socks_greeting_encoder_t::encode (const socks_greeting_t &greeting_) int zmq::socks_greeting_encoder_t::output (fd_t fd_) { - const int rc = tcp_write ( - fd_, buf + bytes_written, bytes_encoded - bytes_written); + const int rc = + tcp_write (fd_, buf + bytes_written, bytes_encoded - bytes_written); if (rc > 0) - bytes_written += static_cast (rc); + bytes_written += static_cast (rc); return rc; } @@ -90,21 +91,21 @@ void zmq::socks_greeting_encoder_t::reset () bytes_encoded = bytes_written = 0; } -zmq::socks_choice_t::socks_choice_t (unsigned char method_) - : method (method_) -{} +zmq::socks_choice_t::socks_choice_t (unsigned char method_) : method (method_) +{ +} -zmq::socks_choice_decoder_t::socks_choice_decoder_t () - : bytes_read (0) -{} +zmq::socks_choice_decoder_t::socks_choice_decoder_t () : bytes_read (0) +{ +} int zmq::socks_choice_decoder_t::input (fd_t fd_) { zmq_assert (bytes_read < 2); const int rc = tcp_read (fd_, buf + bytes_read, 2 - bytes_read); if (rc > 0) { - bytes_read += static_cast (rc); - if (buf [0] != 0x05) + bytes_read += static_cast (rc); + if (buf[0] != 0x05) return -1; } return rc; @@ -118,7 +119,7 @@ bool zmq::socks_choice_decoder_t::message_ready () const zmq::socks_choice_t zmq::socks_choice_decoder_t::decode () { zmq_assert (message_ready ()); - return socks_choice_t (buf [1]); + return socks_choice_t (buf[1]); } void zmq::socks_choice_decoder_t::reset () @@ -127,20 +128,25 @@ void zmq::socks_choice_decoder_t::reset () } -zmq::socks_request_t::socks_request_t ( - uint8_t command_, std::string hostname_, uint16_t port_) - : command (command_), hostname (hostname_), port (port_) +zmq::socks_request_t::socks_request_t (uint8_t command_, + std::string hostname_, + uint16_t port_) : + command (command_), + hostname (hostname_), + port (port_) { zmq_assert (hostname_.size () <= UINT8_MAX); } -zmq::socks_request_encoder_t::socks_request_encoder_t () - : bytes_encoded (0), bytes_written (0) -{} +zmq::socks_request_encoder_t::socks_request_encoder_t () : + bytes_encoded (0), + bytes_written (0) +{ +} void zmq::socks_request_encoder_t::encode (const socks_request_t &req) { - zmq_assert (req.hostname.size() <= UINT8_MAX); + zmq_assert (req.hostname.size () <= UINT8_MAX); unsigned char *ptr = buf; *ptr++ = 0x05; @@ -161,20 +167,17 @@ void zmq::socks_request_encoder_t::encode (const socks_request_t &req) const int rc = getaddrinfo (req.hostname.c_str (), NULL, &hints, &res); if (rc == 0 && res->ai_family == AF_INET) { struct sockaddr_in *sockaddr_in = - reinterpret_cast (res->ai_addr); + reinterpret_cast (res->ai_addr); *ptr++ = 0x01; memcpy (ptr, &sockaddr_in->sin_addr, 4); ptr += 4; - } - else - if (rc == 0 && res->ai_family == AF_INET6) { + } else if (rc == 0 && res->ai_family == AF_INET6) { struct sockaddr_in6 *sockaddr_in6 = - reinterpret_cast (res->ai_addr); + reinterpret_cast (res->ai_addr); *ptr++ = 0x04; memcpy (ptr, &sockaddr_in6->sin6_addr, 16); ptr += 16; - } - else { + } else { *ptr++ = 0x03; *ptr++ = (unsigned char) req.hostname.size (); memcpy (ptr, req.hostname.c_str (), req.hostname.size ()); @@ -193,10 +196,10 @@ void zmq::socks_request_encoder_t::encode (const socks_request_t &req) int zmq::socks_request_encoder_t::output (fd_t fd_) { - const int rc = tcp_write ( - fd_, buf + bytes_written, bytes_encoded - bytes_written); + const int rc = + tcp_write (fd_, buf + bytes_written, bytes_encoded - bytes_written); if (rc > 0) - bytes_written += static_cast (rc); + bytes_written += static_cast (rc); return rc; } @@ -210,14 +213,18 @@ void zmq::socks_request_encoder_t::reset () bytes_encoded = bytes_written = 0; } -zmq::socks_response_t::socks_response_t ( - uint8_t response_code_, std::string address_, uint16_t port_) - : response_code (response_code_), address (address_), port (port_) -{} +zmq::socks_response_t::socks_response_t (uint8_t response_code_, + std::string address_, + uint16_t port_) : + response_code (response_code_), + address (address_), + port (port_) +{ +} -zmq::socks_response_decoder_t::socks_response_decoder_t () - : bytes_read (0) -{} +zmq::socks_response_decoder_t::socks_response_decoder_t () : bytes_read (0) +{ +} int zmq::socks_response_decoder_t::input (fd_t fd_) { @@ -226,30 +233,28 @@ int zmq::socks_response_decoder_t::input (fd_t fd_) if (bytes_read < 5) n = 5 - bytes_read; else { - const uint8_t atyp = buf [3]; + const uint8_t atyp = buf[3]; zmq_assert (atyp == 0x01 || atyp == 0x03 || atyp == 0x04); if (atyp == 0x01) n = 3 + 2; - else - if (atyp == 0x03) - n = buf [4] + 2; - else - if (atyp == 0x04) + else if (atyp == 0x03) + n = buf[4] + 2; + else if (atyp == 0x04) n = 15 + 2; } const int rc = tcp_read (fd_, buf + bytes_read, n); if (rc > 0) { - bytes_read += static_cast (rc); - if (buf [0] != 0x05) + bytes_read += static_cast (rc); + if (buf[0] != 0x05) return -1; if (bytes_read >= 2) - if (buf [1] > 0x08) + if (buf[1] > 0x08) return -1; if (bytes_read >= 3) - if (buf [2] != 0x00) + if (buf[2] != 0x00) return -1; if (bytes_read >= 4) { - const uint8_t atyp = buf [3]; + const uint8_t atyp = buf[3]; if (atyp != 0x01 && atyp != 0x03 && atyp != 0x04) return -1; } @@ -262,13 +267,12 @@ bool zmq::socks_response_decoder_t::message_ready () const if (bytes_read < 4) return false; else { - const uint8_t atyp = buf [3]; + const uint8_t atyp = buf[3]; zmq_assert (atyp == 0x01 || atyp == 0x03 || atyp == 0x04); if (atyp == 0x01) return bytes_read == 10; - else - if (atyp == 0x03) - return bytes_read > 4 && bytes_read == 4 + 1 + buf [4] + 2u; + else if (atyp == 0x03) + return bytes_read > 4 && bytes_read == 4 + 1 + buf[4] + 2u; else return bytes_read == 22; } @@ -277,7 +281,7 @@ bool zmq::socks_response_decoder_t::message_ready () const zmq::socks_response_t zmq::socks_response_decoder_t::decode () { zmq_assert (message_ready ()); - return socks_response_t (buf [1], "", 0); + return socks_response_t (buf[1], "", 0); } void zmq::socks_response_decoder_t::reset () diff --git a/src/socks.hpp b/src/socks.hpp index 6376e793ec..aed4d1b3b1 100644 --- a/src/socks.hpp +++ b/src/socks.hpp @@ -36,100 +36,98 @@ namespace zmq { +struct socks_greeting_t +{ + socks_greeting_t (uint8_t method); + socks_greeting_t (uint8_t *methods_, uint8_t num_methods_); + + uint8_t methods[UINT8_MAX]; + const size_t num_methods; +}; + +class socks_greeting_encoder_t +{ + public: + socks_greeting_encoder_t (); + void encode (const socks_greeting_t &greeting_); + int output (fd_t fd_); + bool has_pending_data () const; + void reset (); + + private: + size_t bytes_encoded; + size_t bytes_written; + uint8_t buf[2 + UINT8_MAX]; +}; + +struct socks_choice_t +{ + socks_choice_t (uint8_t method_); + + uint8_t method; +}; - struct socks_greeting_t - { - socks_greeting_t (uint8_t method); - socks_greeting_t (uint8_t *methods_, uint8_t num_methods_); - - uint8_t methods [UINT8_MAX]; - const size_t num_methods; - }; - - class socks_greeting_encoder_t - { - public: - socks_greeting_encoder_t (); - void encode (const socks_greeting_t &greeting_); - int output (fd_t fd_); - bool has_pending_data () const; - void reset (); - - private: - size_t bytes_encoded; - size_t bytes_written; - uint8_t buf [2 + UINT8_MAX]; - }; - - struct socks_choice_t - { - socks_choice_t (uint8_t method_); - - uint8_t method; - }; - - class socks_choice_decoder_t - { - public: - socks_choice_decoder_t (); - int input (fd_t fd_); - bool message_ready () const; - socks_choice_t decode (); - void reset (); - - private: - unsigned char buf [2]; - size_t bytes_read; - }; - - struct socks_request_t - { - socks_request_t ( - uint8_t command_, std::string hostname_, uint16_t port_); - - const uint8_t command; - const std::string hostname; - const uint16_t port; - }; - - class socks_request_encoder_t - { - public: - socks_request_encoder_t (); - void encode (const socks_request_t &req); - int output (fd_t fd_); - bool has_pending_data () const; - void reset (); - - private: - size_t bytes_encoded; - size_t bytes_written; - uint8_t buf [4 + UINT8_MAX + 1 + 2]; - }; - - struct socks_response_t - { - socks_response_t ( - uint8_t response_code_, std::string address_, uint16_t port_); - uint8_t response_code; - std::string address; - uint16_t port; - }; - - class socks_response_decoder_t - { - public: - socks_response_decoder_t (); - int input (fd_t fd_); - bool message_ready () const; - socks_response_t decode (); - void reset (); - - private: - int8_t buf [4 + UINT8_MAX + 1 + 2]; - size_t bytes_read; - }; +class socks_choice_decoder_t +{ + public: + socks_choice_decoder_t (); + int input (fd_t fd_); + bool message_ready () const; + socks_choice_t decode (); + void reset (); + + private: + unsigned char buf[2]; + size_t bytes_read; +}; + +struct socks_request_t +{ + socks_request_t (uint8_t command_, std::string hostname_, uint16_t port_); + + const uint8_t command; + const std::string hostname; + const uint16_t port; +}; +class socks_request_encoder_t +{ + public: + socks_request_encoder_t (); + void encode (const socks_request_t &req); + int output (fd_t fd_); + bool has_pending_data () const; + void reset (); + + private: + size_t bytes_encoded; + size_t bytes_written; + uint8_t buf[4 + UINT8_MAX + 1 + 2]; +}; + +struct socks_response_t +{ + socks_response_t (uint8_t response_code_, + std::string address_, + uint16_t port_); + uint8_t response_code; + std::string address; + uint16_t port; +}; + +class socks_response_decoder_t +{ + public: + socks_response_decoder_t (); + int input (fd_t fd_); + bool message_ready () const; + socks_response_t decode (); + void reset (); + + private: + int8_t buf[4 + UINT8_MAX + 1 + 2]; + size_t bytes_read; +}; } #endif diff --git a/src/socks_connecter.cpp b/src/socks_connecter.cpp index ab14dcd5a1..8520667382 100644 --- a/src/socks_connecter.cpp +++ b/src/socks_connecter.cpp @@ -50,18 +50,21 @@ #endif zmq::socks_connecter_t::socks_connecter_t (class io_thread_t *io_thread_, - class session_base_t *session_, const options_t &options_, - address_t *addr_, address_t *proxy_addr_, bool delayed_start_) : + class session_base_t *session_, + const options_t &options_, + address_t *addr_, + address_t *proxy_addr_, + bool delayed_start_) : own_t (io_thread_, options_), io_object_t (io_thread_), addr (addr_), proxy_addr (proxy_addr_), status (unplugged), s (retired_fd), - handle((handle_t)NULL), - handle_valid(false), + handle ((handle_t) NULL), + handle_valid (false), delayed_start (delayed_start_), - timer_started(false), + timer_started (false), session (session_), current_reconnect_ivl (options.reconnect_ivl) { @@ -74,7 +77,7 @@ zmq::socks_connecter_t::socks_connecter_t (class io_thread_t *io_thread_, zmq::socks_connecter_t::~socks_connecter_t () { zmq_assert (s == retired_fd); - LIBZMQ_DELETE(proxy_addr); + LIBZMQ_DELETE (proxy_addr); } void zmq::socks_connecter_t::process_plug () @@ -109,49 +112,44 @@ void zmq::socks_connecter_t::process_term (int linger_) void zmq::socks_connecter_t::in_event () { - zmq_assert (status != unplugged - && status != waiting_for_reconnect_time); + zmq_assert (status != unplugged && status != waiting_for_reconnect_time); if (status == waiting_for_choice) { int rc = choice_decoder.input (s); if (rc == 0 || rc == -1) error (); - else - if (choice_decoder.message_ready ()) { - const socks_choice_t choice = choice_decoder.decode (); - rc = process_server_response (choice); - if (rc == -1) - error (); - else { - std::string hostname = ""; - uint16_t port = 0; - if (parse_address (addr->address, hostname, port) == -1) - error (); - else { - request_encoder.encode ( - socks_request_t (1, hostname, port)); - reset_pollin (handle); - set_pollout (handle); - status = sending_request; - } - } + else if (choice_decoder.message_ready ()) { + const socks_choice_t choice = choice_decoder.decode (); + rc = process_server_response (choice); + if (rc == -1) + error (); + else { + std::string hostname = ""; + uint16_t port = 0; + if (parse_address (addr->address, hostname, port) == -1) + error (); + else { + request_encoder.encode ( + socks_request_t (1, hostname, port)); + reset_pollin (handle); + set_pollout (handle); + status = sending_request; + } + } } - } - else - if (status == waiting_for_response) { + } else if (status == waiting_for_response) { int rc = response_decoder.input (s); if (rc == 0 || rc == -1) error (); - else - if (response_decoder.message_ready ()) { + else if (response_decoder.message_ready ()) { const socks_response_t response = response_decoder.decode (); rc = process_server_response (response); if (rc == -1) error (); else { // Create the engine object for this connection. - stream_engine_t *engine = new (std::nothrow) - stream_engine_t (s, options, endpoint); + stream_engine_t *engine = + new (std::nothrow) stream_engine_t (s, options, endpoint); alloc_assert (engine); // Attach the engine to the corresponding session object. @@ -167,47 +165,39 @@ void zmq::socks_connecter_t::in_event () terminate (); } } - } - else + } else error (); } void zmq::socks_connecter_t::out_event () { zmq_assert (status == waiting_for_proxy_connection - || status == sending_greeting - || status == sending_request); + || status == sending_greeting || status == sending_request); if (status == waiting_for_proxy_connection) { const int rc = (int) check_proxy_connection (); if (rc == -1) error (); else { - greeting_encoder.encode ( - socks_greeting_t (socks_no_auth_required)); + greeting_encoder.encode (socks_greeting_t (socks_no_auth_required)); status = sending_greeting; } - } - else - if (status == sending_greeting) { + } else if (status == sending_greeting) { zmq_assert (greeting_encoder.has_pending_data ()); const int rc = greeting_encoder.output (s); if (rc == -1 || rc == 0) error (); - else - if (!greeting_encoder.has_pending_data ()) { + else if (!greeting_encoder.has_pending_data ()) { reset_pollout (handle); set_pollin (handle); status = waiting_for_choice; } - } - else { + } else { zmq_assert (request_encoder.has_pending_data ()); const int rc = request_encoder.output (s); if (rc == -1 || rc == 0) error (); - else - if (!request_encoder.has_pending_data ()) { + else if (!request_encoder.has_pending_data ()) { reset_pollout (handle); set_pollin (handle); status = waiting_for_response; @@ -227,8 +217,7 @@ void zmq::socks_connecter_t::initiate_connect () status = sending_greeting; } // Connection establishment may be delayed. Poll for its completion. - else - if (errno == EINPROGRESS) { + else if (errno == EINPROGRESS) { handle = add_fd (s); set_pollout (handle); status = waiting_for_proxy_connection; @@ -243,16 +232,16 @@ void zmq::socks_connecter_t::initiate_connect () } int zmq::socks_connecter_t::process_server_response ( - const socks_choice_t &response) + const socks_choice_t &response) { // We do not support any authentication method for now. - return response.method == 0? 0: -1; + return response.method == 0 ? 0 : -1; } int zmq::socks_connecter_t::process_server_response ( - const socks_response_t &response) + const socks_response_t &response) { - return response.response_code == 0? 0: -1; + return response.response_code == 0 ? 0 : -1; } void zmq::socks_connecter_t::timer_event (int id_) @@ -284,16 +273,16 @@ void zmq::socks_connecter_t::start_timer () int zmq::socks_connecter_t::get_new_reconnect_ivl () { // The new interval is the current interval + random value. - const int interval = current_reconnect_ivl + - generate_random () % options.reconnect_ivl; + const int interval = + current_reconnect_ivl + generate_random () % options.reconnect_ivl; // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. - if (options.reconnect_ivl_max > 0 && - options.reconnect_ivl_max > options.reconnect_ivl) + if (options.reconnect_ivl_max > 0 + && options.reconnect_ivl_max > options.reconnect_ivl) // Calculate the next interval current_reconnect_ivl = - std::min (current_reconnect_ivl * 2, options.reconnect_ivl_max); + std::min (current_reconnect_ivl * 2, options.reconnect_ivl_max); return interval; } @@ -302,14 +291,14 @@ int zmq::socks_connecter_t::connect_to_proxy () zmq_assert (s == retired_fd); // Resolve the address - LIBZMQ_DELETE(proxy_addr->resolved.tcp_addr); + LIBZMQ_DELETE (proxy_addr->resolved.tcp_addr); proxy_addr->resolved.tcp_addr = new (std::nothrow) tcp_address_t (); alloc_assert (proxy_addr->resolved.tcp_addr); int rc = proxy_addr->resolved.tcp_addr->resolve ( - proxy_addr->address.c_str (), false, options.ipv6); + proxy_addr->address.c_str (), false, options.ipv6); if (rc != 0) { - LIBZMQ_DELETE(proxy_addr->resolved.tcp_addr); + LIBZMQ_DELETE (proxy_addr->resolved.tcp_addr); return -1; } zmq_assert (proxy_addr->resolved.tcp_addr != NULL); @@ -367,10 +356,10 @@ int zmq::socks_connecter_t::connect_to_proxy () if (rc == 0) return 0; - // Translate error codes indicating asynchronous connect has been - // launched to a uniform EINPROGRESS. + // Translate error codes indicating asynchronous connect has been + // launched to a uniform EINPROGRESS. #ifdef ZMQ_HAVE_WINDOWS - const int last_error = WSAGetLastError(); + const int last_error = WSAGetLastError (); if (last_error == WSAEINPROGRESS || last_error == WSAEWOULDBLOCK) errno = EINPROGRESS; else { @@ -394,22 +383,18 @@ zmq::fd_t zmq::socks_connecter_t::check_proxy_connection () socklen_t len = sizeof err; #endif - int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char*) &err, &len); + int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char *) &err, &len); // Assert if the error was caused by 0MQ bug. // Networking problems are OK. No need to assert. #ifdef ZMQ_HAVE_WINDOWS zmq_assert (rc == 0); if (err != 0) { - wsa_assert (err == WSAECONNREFUSED - || err == WSAETIMEDOUT - || err == WSAECONNABORTED - || err == WSAEHOSTUNREACH - || err == WSAENETUNREACH - || err == WSAENETDOWN - || err == WSAEACCES - || err == WSAEINVAL - || err == WSAEADDRINUSE); + wsa_assert (err == WSAECONNREFUSED || err == WSAETIMEDOUT + || err == WSAECONNABORTED || err == WSAEHOSTUNREACH + || err == WSAENETUNREACH || err == WSAENETDOWN + || err == WSAEACCES || err == WSAEINVAL + || err == WSAEADDRINUSE); return -1; } #else @@ -419,24 +404,22 @@ zmq::fd_t zmq::socks_connecter_t::check_proxy_connection () err = errno; if (err != 0) { errno = err; - errno_assert ( - errno == ECONNREFUSED || - errno == ECONNRESET || - errno == ETIMEDOUT || - errno == EHOSTUNREACH || - errno == ENETUNREACH || - errno == ENETDOWN || - errno == EINVAL); + errno_assert (errno == ECONNREFUSED || errno == ECONNRESET + || errno == ETIMEDOUT || errno == EHOSTUNREACH + || errno == ENETUNREACH || errno == ENETDOWN + || errno == EINVAL); return -1; } #endif rc = tune_tcp_socket (s); - rc = rc | tune_tcp_keepalives (s, options.tcp_keepalive, options.tcp_keepalive_cnt, - options.tcp_keepalive_idle, options.tcp_keepalive_intvl); + rc = rc + | tune_tcp_keepalives ( + s, options.tcp_keepalive, options.tcp_keepalive_cnt, + options.tcp_keepalive_idle, options.tcp_keepalive_intvl); if (rc != 0) return -1; - + return 0; } @@ -454,8 +437,9 @@ void zmq::socks_connecter_t::close () s = retired_fd; } -int zmq::socks_connecter_t::parse_address ( - const std::string &address_, std::string &hostname_, uint16_t &port_) +int zmq::socks_connecter_t::parse_address (const std::string &address_, + std::string &hostname_, + uint16_t &port_) { // Find the ':' at end that separates address from the port number. const size_t idx = address_.rfind (':'); @@ -465,7 +449,7 @@ int zmq::socks_connecter_t::parse_address ( } // Extract hostname - if (idx < 2 || address_ [0] != '[' || address_ [idx - 1] != ']') + if (idx < 2 || address_[0] != '[' || address_[idx - 1] != ']') hostname_ = address_.substr (0, idx); else hostname_ = address_.substr (1, idx - 2); diff --git a/src/socks_connecter.hpp b/src/socks_connecter.hpp index e34a0254bd..fd16d384e2 100644 --- a/src/socks_connecter.hpp +++ b/src/socks_connecter.hpp @@ -38,126 +38,134 @@ namespace zmq { +class io_thread_t; +class session_base_t; +struct address_t; - class io_thread_t; - class session_base_t; - struct address_t; - - class socks_connecter_t : public own_t, public io_object_t +class socks_connecter_t : public own_t, public io_object_t +{ + public: + // If 'delayed_start' is true connecter first waits for a while, + // then starts connection process. + socks_connecter_t (zmq::io_thread_t *io_thread_, + zmq::session_base_t *session_, + const options_t &options_, + address_t *addr_, + address_t *proxy_addr_, + bool delayed_start_); + ~socks_connecter_t (); + + private: + enum { - public: - - // If 'delayed_start' is true connecter first waits for a while, - // then starts connection process. - socks_connecter_t (zmq::io_thread_t *io_thread_, - zmq::session_base_t *session_, const options_t &options_, - address_t *addr_, address_t *proxy_addr_, bool delayed_start_); - ~socks_connecter_t (); - - private: - enum { - unplugged, - waiting_for_reconnect_time, - waiting_for_proxy_connection, - sending_greeting, - waiting_for_choice, - sending_request, - waiting_for_response - }; - - // ID of the timer used to delay the reconnection. - enum { reconnect_timer_id = 1 }; + unplugged, + waiting_for_reconnect_time, + waiting_for_proxy_connection, + sending_greeting, + waiting_for_choice, + sending_request, + waiting_for_response + }; - // Method ID - enum { socks_no_auth_required = 0 }; + // ID of the timer used to delay the reconnection. + enum + { + reconnect_timer_id = 1 + }; - // Handlers for incoming commands. - virtual void process_plug (); - virtual void process_term (int linger_); + // Method ID + enum + { + socks_no_auth_required = 0 + }; - // Handlers for I/O events. - virtual void in_event (); - virtual void out_event (); - virtual void timer_event (int id_); + // Handlers for incoming commands. + virtual void process_plug (); + virtual void process_term (int linger_); - // Internal function to start the actual connection establishment. - void initiate_connect (); + // Handlers for I/O events. + virtual void in_event (); + virtual void out_event (); + virtual void timer_event (int id_); - int process_server_response (const socks_choice_t &response); - int process_server_response (const socks_response_t &response); + // Internal function to start the actual connection establishment. + void initiate_connect (); - int parse_address (const std::string &address_, - std::string &hostname_, uint16_t &port_); + int process_server_response (const socks_choice_t &response); + int process_server_response (const socks_response_t &response); - int connect_to_proxy (); + int parse_address (const std::string &address_, + std::string &hostname_, + uint16_t &port_); - void error (); + int connect_to_proxy (); - // Internal function to start reconnect timer - void start_timer (); + void error (); - // Internal function to return a reconnect backoff delay. - // Will modify the current_reconnect_ivl used for next call - // Returns the currently used interval - int get_new_reconnect_ivl (); + // Internal function to start reconnect timer + void start_timer (); - // Open TCP connecting socket. Returns -1 in case of error, - // 0 if connect was successful immediately. Returns -1 with - // EAGAIN errno if async connect was launched. - int open (); + // Internal function to return a reconnect backoff delay. + // Will modify the current_reconnect_ivl used for next call + // Returns the currently used interval + int get_new_reconnect_ivl (); - // Close the connecting socket. - void close (); + // Open TCP connecting socket. Returns -1 in case of error, + // 0 if connect was successful immediately. Returns -1 with + // EAGAIN errno if async connect was launched. + int open (); - // Get the file descriptor of newly created connection. Returns - // retired_fd if the connection was unsuccessful. - zmq::fd_t check_proxy_connection (); + // Close the connecting socket. + void close (); - socks_greeting_encoder_t greeting_encoder; - socks_choice_decoder_t choice_decoder; - socks_request_encoder_t request_encoder; - socks_response_decoder_t response_decoder; + // Get the file descriptor of newly created connection. Returns + // retired_fd if the connection was unsuccessful. + zmq::fd_t check_proxy_connection (); - // Address to connect to. Owned by session_base_t. - address_t *addr; + socks_greeting_encoder_t greeting_encoder; + socks_choice_decoder_t choice_decoder; + socks_request_encoder_t request_encoder; + socks_response_decoder_t response_decoder; - // SOCKS address; owned by this connecter. - address_t *proxy_addr; + // Address to connect to. Owned by session_base_t. + address_t *addr; - int status; + // SOCKS address; owned by this connecter. + address_t *proxy_addr; - // Underlying socket. - fd_t s; + int status; - // Handle corresponding to the listening socket. - handle_t handle; + // Underlying socket. + fd_t s; - // If true file descriptor is registered with the poller and 'handle' - // contains valid value. - bool handle_valid; + // Handle corresponding to the listening socket. + handle_t handle; - // If true, connecter is waiting a while before trying to connect. - const bool delayed_start; + // If true file descriptor is registered with the poller and 'handle' + // contains valid value. + bool handle_valid; - // True iff a timer has been started. - bool timer_started; + // If true, connecter is waiting a while before trying to connect. + const bool delayed_start; - // Reference to the session we belong to. - zmq::session_base_t *session; + // True iff a timer has been started. + bool timer_started; - // Current reconnect ivl, updated for backoff strategy - int current_reconnect_ivl; + // Reference to the session we belong to. + zmq::session_base_t *session; - // String representation of endpoint to connect to - std::string endpoint; + // Current reconnect ivl, updated for backoff strategy + int current_reconnect_ivl; - // Socket - zmq::socket_base_t *socket; + // String representation of endpoint to connect to + std::string endpoint; - socks_connecter_t (const socks_connecter_t&); - const socks_connecter_t &operator = (const socks_connecter_t&); - }; + // Socket + zmq::socket_base_t *socket; + socks_connecter_t (const socks_connecter_t &); + const socks_connecter_t &operator= (const socks_connecter_t &); +}; } #endif diff --git a/src/stdint.hpp b/src/stdint.hpp index 3ee4892a2c..4efc86f1a2 100644 --- a/src/stdint.hpp +++ b/src/stdint.hpp @@ -61,7 +61,7 @@ typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #endif #ifndef UINT32_MAX -#define UINT32_MAX _UI32_MAX +#define UINT32_MAX _UI32_MAX #endif #else diff --git a/src/stream.cpp b/src/stream.cpp index f522ffcd16..092c88dfb0 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -60,7 +60,7 @@ zmq::stream_t::~stream_t () void zmq::stream_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_) { - LIBZMQ_UNUSED(subscribe_to_all_); + LIBZMQ_UNUSED (subscribe_to_all_); zmq_assert (pipe_); @@ -106,10 +106,9 @@ int zmq::stream_t::xsend (msg_t *msg_) // then just silently ignore it. // TODO: The connections should be killed instead. if (msg_->flags () & msg_t::more) { - // Find the pipe associated with the routing id stored in the prefix. // If there's no such pipe return an error - blob_t routing_id ((unsigned char*) msg_->data (), msg_->size ()); + blob_t routing_id ((unsigned char *) msg_->data (), msg_->size ()); outpipes_t::iterator it = outpipes.find (routing_id); if (it != outpipes.end ()) { @@ -120,8 +119,7 @@ int zmq::stream_t::xsend (msg_t *msg_) errno = EAGAIN; return -1; } - } - else { + } else { errno = EHOSTUNREACH; return -1; } @@ -145,7 +143,6 @@ int zmq::stream_t::xsend (msg_t *msg_) // Push the message into the pipe. If there's no out pipe, just drop it. if (current_out) { - // Close the remote connection if user has asked to do so // by sending zero length message. // Pending messages in the pipe will be dropped (on receiving term- ack) @@ -162,8 +159,7 @@ int zmq::stream_t::xsend (msg_t *msg_) if (likely (ok)) current_out->flush (); current_out = NULL; - } - else { + } else { int rc = msg_->close (); errno_assert (rc == 0); } @@ -175,17 +171,19 @@ int zmq::stream_t::xsend (msg_t *msg_) return 0; } -int zmq::stream_t::xsetsockopt (int option_, const void *optval_, - size_t optvallen_) +int zmq::stream_t::xsetsockopt (int option_, + const void *optval_, + size_t optvallen_) { bool is_int = (optvallen_ == sizeof (int)); int value = 0; - if (is_int) memcpy(&value, optval_, sizeof (int)); + if (is_int) + memcpy (&value, optval_, sizeof (int)); switch (option_) { case ZMQ_CONNECT_ROUTING_ID: if (optval_ && optvallen_) { - connect_routing_id.assign ((char*) optval_, optvallen_); + connect_routing_id.assign ((char *) optval_, optvallen_); return 0; } break; @@ -211,8 +209,7 @@ int zmq::stream_t::xrecv (msg_t *msg_) int rc = msg_->move (prefetched_routing_id); errno_assert (rc == 0); routing_id_sent = true; - } - else { + } else { int rc = msg_->move (prefetched_msg); errno_assert (rc == 0); prefetched = false; @@ -232,15 +229,15 @@ int zmq::stream_t::xrecv (msg_t *msg_) // Rather than sending this frame, we keep it in prefetched // buffer and send a frame with peer's ID. const blob_t &routing_id = pipe->get_routing_id (); - rc = msg_->close(); + rc = msg_->close (); errno_assert (rc == 0); rc = msg_->init_size (routing_id.size ()); errno_assert (rc == 0); // forward metadata (if any) - metadata_t *metadata = prefetched_msg.metadata(); + metadata_t *metadata = prefetched_msg.metadata (); if (metadata) - msg_->set_metadata(metadata); + msg_->set_metadata (metadata); memcpy (msg_->data (), routing_id.data (), routing_id.size ()); msg_->set_flags (msg_t::more); @@ -272,11 +269,12 @@ bool zmq::stream_t::xhas_in () errno_assert (rc == 0); // forward metadata (if any) - metadata_t *metadata = prefetched_msg.metadata(); + metadata_t *metadata = prefetched_msg.metadata (); if (metadata) - prefetched_routing_id.set_metadata(metadata); + prefetched_routing_id.set_metadata (metadata); - memcpy (prefetched_routing_id.data (), routing_id.data (), routing_id.size ()); + memcpy (prefetched_routing_id.data (), routing_id.data (), + routing_id.size ()); prefetched_routing_id.set_flags (msg_t::more); prefetched = true; @@ -296,17 +294,16 @@ bool zmq::stream_t::xhas_out () void zmq::stream_t::identify_peer (pipe_t *pipe_) { // Always assign routing id for raw-socket - unsigned char buffer [5]; - buffer [0] = 0; + unsigned char buffer[5]; + buffer[0] = 0; blob_t routing_id; if (connect_routing_id.length ()) { - routing_id.set ((unsigned char*) connect_routing_id.c_str(), - connect_routing_id.length ()); + routing_id.set ((unsigned char *) connect_routing_id.c_str (), + connect_routing_id.length ()); connect_routing_id.clear (); outpipes_t::iterator it = outpipes.find (routing_id); zmq_assert (it == outpipes.end ()); - } - else { + } else { put_uint32 (buffer + 1, next_integral_routing_id++); routing_id.set (buffer, sizeof buffer); memcpy (options.routing_id, routing_id.data (), routing_id.size ()); @@ -315,7 +312,8 @@ void zmq::stream_t::identify_peer (pipe_t *pipe_) pipe_->set_router_socket_routing_id (routing_id); // Add the record into output pipes lookup table outpipe_t outpipe = {pipe_, true}; - const bool ok = outpipes.ZMQ_MAP_INSERT_OR_EMPLACE ( - ZMQ_MOVE(routing_id), outpipe).second; + const bool ok = + outpipes.ZMQ_MAP_INSERT_OR_EMPLACE (ZMQ_MOVE (routing_id), outpipe) + .second; zmq_assert (ok); } diff --git a/src/stream.hpp b/src/stream.hpp index b3a4a617bc..b91deec869 100644 --- a/src/stream.hpp +++ b/src/stream.hpp @@ -36,72 +36,69 @@ namespace zmq { +class ctx_t; +class pipe_t; - class ctx_t; - class pipe_t; - - class stream_t : - public socket_base_t +class stream_t : public socket_base_t +{ + public: + stream_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); + ~stream_t (); + + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsend (zmq::msg_t *msg_); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + bool xhas_out (); + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + int xsetsockopt (int option_, const void *optval_, size_t optvallen_); + + private: + // Generate peer's id and update lookup map + void identify_peer (pipe_t *pipe_); + + // Fair queueing object for inbound pipes. + fq_t fq; + + // True iff there is a message held in the pre-fetch buffer. + bool prefetched; + + // If true, the receiver got the message part with + // the peer's identity. + bool routing_id_sent; + + // Holds the prefetched identity. + msg_t prefetched_routing_id; + + // Holds the prefetched message. + msg_t prefetched_msg; + + struct outpipe_t { - public: - - stream_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); - ~stream_t (); - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsend (zmq::msg_t *msg_); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - bool xhas_out (); - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - int xsetsockopt (int option_, const void *optval_, size_t optvallen_); - private: - // Generate peer's id and update lookup map - void identify_peer (pipe_t *pipe_); - - // Fair queueing object for inbound pipes. - fq_t fq; - - // True iff there is a message held in the pre-fetch buffer. - bool prefetched; - - // If true, the receiver got the message part with - // the peer's identity. - bool routing_id_sent; - - // Holds the prefetched identity. - msg_t prefetched_routing_id; - - // Holds the prefetched message. - msg_t prefetched_msg; - - struct outpipe_t - { - zmq::pipe_t *pipe; - bool active; - }; - - // Outbound pipes indexed by the peer IDs. - typedef std::map outpipes_t; - outpipes_t outpipes; - - // The pipe we are currently writing to. - zmq::pipe_t *current_out; - - // If true, more outgoing message parts are expected. - bool more_out; - - // Routing IDs are generated. It's a simple increment and wrap-over - // algorithm. This value is the next ID to use (if not used already). - uint32_t next_integral_routing_id; - - stream_t (const stream_t&); - const stream_t &operator = (const stream_t&); + zmq::pipe_t *pipe; + bool active; }; + // Outbound pipes indexed by the peer IDs. + typedef std::map outpipes_t; + outpipes_t outpipes; + + // The pipe we are currently writing to. + zmq::pipe_t *current_out; + + // If true, more outgoing message parts are expected. + bool more_out; + + // Routing IDs are generated. It's a simple increment and wrap-over + // algorithm. This value is the next ID to use (if not used already). + uint32_t next_integral_routing_id; + + stream_t (const stream_t &); + const stream_t &operator= (const stream_t &); +}; } #endif diff --git a/src/stream_engine.cpp b/src/stream_engine.cpp index f0f2887110..d594f2c6f6 100644 --- a/src/stream_engine.cpp +++ b/src/stream_engine.cpp @@ -62,11 +62,12 @@ #include "likely.hpp" #include "wire.hpp" -zmq::stream_engine_t::stream_engine_t (fd_t fd_, const options_t &options_, +zmq::stream_engine_t::stream_engine_t (fd_t fd_, + const options_t &options_, const std::string &endpoint_) : s (fd_), - as_server(false), - handle((handle_t)NULL), + as_server (false), + handle ((handle_t) NULL), inpos (NULL), insize (0), decoder (NULL), @@ -103,10 +104,9 @@ zmq::stream_engine_t::stream_engine_t (fd_t fd_, const options_t &options_, int family = get_peer_ip_address (s, peer_address); if (family == 0) - peer_address.clear(); + peer_address.clear (); #if defined ZMQ_HAVE_SO_PEERCRED - else - if (family == PF_UNIX) { + else if (family == PF_UNIX) { struct ucred cred; socklen_t size = sizeof (cred); if (!getsockopt (s, SOL_SOCKET, SO_PEERCRED, &cred, &size)) { @@ -116,12 +116,11 @@ zmq::stream_engine_t::stream_engine_t (fd_t fd_, const options_t &options_, } } #elif defined ZMQ_HAVE_LOCAL_PEERCRED - else - if (family == PF_UNIX) { + else if (family == PF_UNIX) { struct xucred cred; socklen_t size = sizeof (cred); if (!getsockopt (s, 0, LOCAL_PEERCRED, &cred, &size) - && cred.cr_version == XUCRED_VERSION) { + && cred.cr_version == XUCRED_VERSION) { std::ostringstream buf; buf << ":" << cred.cr_uid << ":"; if (cred.cr_ngroups > 0) @@ -132,9 +131,9 @@ zmq::stream_engine_t::stream_engine_t (fd_t fd_, const options_t &options_, } #endif - if(options.heartbeat_interval > 0) { + if (options.heartbeat_interval > 0) { heartbeat_timeout = options.heartbeat_timeout; - if(heartbeat_timeout == -1) + if (heartbeat_timeout == -1) heartbeat_timeout = options.heartbeat_interval; } } @@ -149,7 +148,7 @@ zmq::stream_engine_t::~stream_engine_t () wsa_assert (rc != SOCKET_ERROR); #else int rc = close (s); -#if defined(__FreeBSD_kernel__) || defined (__FreeBSD__) +#if defined(__FreeBSD_kernel__) || defined(__FreeBSD__) // FreeBSD may return ECONNRESET on close() under load but this is not // an error. if (rc == -1 && errno == ECONNRESET) @@ -167,17 +166,17 @@ zmq::stream_engine_t::~stream_engine_t () // the only user. if (metadata != NULL) { if (metadata->drop_ref ()) { - LIBZMQ_DELETE(metadata); + LIBZMQ_DELETE (metadata); } } - LIBZMQ_DELETE(encoder); - LIBZMQ_DELETE(decoder); - LIBZMQ_DELETE(mechanism); + LIBZMQ_DELETE (encoder); + LIBZMQ_DELETE (decoder); + LIBZMQ_DELETE (mechanism); } void zmq::stream_engine_t::plug (io_thread_t *io_thread_, - session_base_t *session_) + session_base_t *session_) { zmq_assert (!plugged); plugged = true; @@ -186,7 +185,7 @@ void zmq::stream_engine_t::plug (io_thread_t *io_thread_, zmq_assert (!session); zmq_assert (session_); session = session_; - socket = session-> get_socket (); + socket = session->get_socket (); // Connect to I/O threads poller object. io_object_t::plug (io_thread_); @@ -208,7 +207,7 @@ void zmq::stream_engine_t::plug (io_thread_t *io_thread_, process_msg = &stream_engine_t::push_raw_msg_to_session; properties_t properties; - if (init_properties(properties)) { + if (init_properties (properties)) { // Compile metadata. zmq_assert (metadata == NULL); metadata = new (std::nothrow) metadata_t (properties); @@ -219,23 +218,22 @@ void zmq::stream_engine_t::plug (io_thread_t *io_thread_, // For raw sockets, send an initial 0-length message to the // application so that it knows a peer has connected. msg_t connector; - connector.init(); + connector.init (); push_raw_msg_to_session (&connector); - connector.close(); + connector.close (); session->flush (); } - } - else { + } else { // start optional timer, to prevent handshake hanging on no input set_handshake_timer (); // Send the 'length' and 'flags' fields of the routing id message. // The 'length' field is encoded in the long format. outpos = greeting_send; - outpos [outsize++] = 0xff; - put_uint64 (&outpos [outsize], options.routing_id_size + 1); + outpos[outsize++] = 0xff; + put_uint64 (&outpos[outsize], options.routing_id_size + 1); outsize += 8; - outpos [outsize++] = 0x7f; + outpos[outsize++] = 0x7f; } set_pollin (handle); @@ -303,9 +301,8 @@ void zmq::stream_engine_t::in_event () return; } - // If there's no data to process in the buffer... + // If there's no data to process in the buffer... if (!insize) { - // Retrieve the buffer and read as much data as possible. // Note that buffer can be arbitrarily large. However, we assume // the underlying TCP layer has fixed buffer size and thus the @@ -328,9 +325,9 @@ void zmq::stream_engine_t::in_event () } // Adjust input size - insize = static_cast (rc); + insize = static_cast (rc); // Adjust buffer size to received bytes - decoder->resize_buffer(insize); + decoder->resize_buffer (insize); } int rc = 0; @@ -352,7 +349,7 @@ void zmq::stream_engine_t::in_event () // or the session has rejected the message. if (rc == -1) { if (errno != EAGAIN) { - error(protocol_error); + error (protocol_error); return; } input_stopped = true; @@ -368,7 +365,6 @@ void zmq::stream_engine_t::out_event () // If write buffer is empty, try to read new data from the encoder. if (!outsize) { - // Even when we stop polling as soon as there is no // data to send, the poller may invoke out_event one // more time due to 'speculative write' optimisation. @@ -472,11 +468,9 @@ void zmq::stream_engine_t::restart_input () if (rc == -1 && errno == EAGAIN) session->flush (); - else - if (io_error) + else if (io_error) error (connection_error); - else - if (rc == -1) + else if (rc == -1) error (protocol_error); else { input_stopped = false; @@ -512,7 +506,7 @@ bool zmq::stream_engine_t::handshake () // We have received at least one byte from the peer. // If the first byte is not 0xff, we know that the // peer is using unversioned protocol. - if (greeting_recv [0] != 0xff) + if (greeting_recv[0] != 0xff) break; if (greeting_bytes_read < signature_size) @@ -522,7 +516,7 @@ bool zmq::stream_engine_t::handshake () // with the 'flags' field if a regular message was sent). // Zero indicates this is a header of a routing id message // (i.e. the peer is using the unversioned protocol). - if (!(greeting_recv [9] & 0x01)) + if (!(greeting_recv[9] & 0x01)) break; // The peer is using versioned protocol. @@ -530,7 +524,7 @@ bool zmq::stream_engine_t::handshake () if (outpos + outsize == greeting_send + signature_size) { if (outsize == 0) set_pollout (handle); - outpos [outsize++] = 3; // Major version number + outpos[outsize++] = 3; // Major version number } if (greeting_bytes_read > signature_size) { @@ -539,28 +533,25 @@ bool zmq::stream_engine_t::handshake () set_pollout (handle); // Use ZMTP/2.0 to talk to older peers. - if (greeting_recv [10] == ZMTP_1_0 - || greeting_recv [10] == ZMTP_2_0) - outpos [outsize++] = options.type; + if (greeting_recv[10] == ZMTP_1_0 + || greeting_recv[10] == ZMTP_2_0) + outpos[outsize++] = options.type; else { - outpos [outsize++] = 0; // Minor version number + outpos[outsize++] = 0; // Minor version number memset (outpos + outsize, 0, 20); zmq_assert (options.mechanism == ZMQ_NULL - || options.mechanism == ZMQ_PLAIN - || options.mechanism == ZMQ_CURVE - || options.mechanism == ZMQ_GSSAPI); + || options.mechanism == ZMQ_PLAIN + || options.mechanism == ZMQ_CURVE + || options.mechanism == ZMQ_GSSAPI); if (options.mechanism == ZMQ_NULL) memcpy (outpos + outsize, "NULL", 4); - else - if (options.mechanism == ZMQ_PLAIN) + else if (options.mechanism == ZMQ_PLAIN) memcpy (outpos + outsize, "PLAIN", 5); - else - if (options.mechanism == ZMQ_GSSAPI) + else if (options.mechanism == ZMQ_GSSAPI) memcpy (outpos + outsize, "GSSAPI", 6); - else - if (options.mechanism == ZMQ_CURVE) + else if (options.mechanism == ZMQ_CURVE) memcpy (outpos + outsize, "CURVE", 5); outsize += 20; memset (outpos + outsize, 0, 32); @@ -576,17 +567,18 @@ bool zmq::stream_engine_t::handshake () // Is the peer using ZMTP/1.0 with no revision number? // If so, we send and receive rest of routing id message - if (greeting_recv [0] != 0xff || !(greeting_recv [9] & 0x01)) { + if (greeting_recv[0] != 0xff || !(greeting_recv[9] & 0x01)) { if (session->zap_enabled ()) { - // reject ZMTP 1.0 connections if ZAP is enabled - error (protocol_error); - return false; + // reject ZMTP 1.0 connections if ZAP is enabled + error (protocol_error); + return false; } encoder = new (std::nothrow) v1_encoder_t (out_batch_size); alloc_assert (encoder); - decoder = new (std::nothrow) v1_decoder_t (in_batch_size, options.maxmsgsize); + decoder = + new (std::nothrow) v1_decoder_t (in_batch_size, options.maxmsgsize); alloc_assert (decoder); // We have already sent the message header. @@ -594,7 +586,7 @@ bool zmq::stream_engine_t::handshake () // skip the message header, we simply throw that // header data away. const size_t header_size = options.routing_id_size + 1 >= 255 ? 10 : 2; - unsigned char tmp [10], *bufferp = tmp; + unsigned char tmp[10], *bufferp = tmp; // Prepare the routing id message and load it into encoder. // Then consume bytes we have already sent to the peer. @@ -621,69 +613,67 @@ bool zmq::stream_engine_t::handshake () // We are expecting routing id message. process_msg = &stream_engine_t::process_routing_id_msg; - } - else - if (greeting_recv [revision_pos] == ZMTP_1_0) { + } else if (greeting_recv[revision_pos] == ZMTP_1_0) { if (session->zap_enabled ()) { - // reject ZMTP 1.0 connections if ZAP is enabled - error (protocol_error); - return false; + // reject ZMTP 1.0 connections if ZAP is enabled + error (protocol_error); + return false; } encoder = new (std::nothrow) v1_encoder_t (out_batch_size); alloc_assert (encoder); - decoder = new (std::nothrow) v1_decoder_t ( - in_batch_size, options.maxmsgsize); + decoder = + new (std::nothrow) v1_decoder_t (in_batch_size, options.maxmsgsize); alloc_assert (decoder); - } - else - if (greeting_recv [revision_pos] == ZMTP_2_0) { + } else if (greeting_recv[revision_pos] == ZMTP_2_0) { if (session->zap_enabled ()) { - // reject ZMTP 2.0 connections if ZAP is enabled - error (protocol_error); - return false; + // reject ZMTP 2.0 connections if ZAP is enabled + error (protocol_error); + return false; } encoder = new (std::nothrow) v2_encoder_t (out_batch_size); alloc_assert (encoder); - decoder = new (std::nothrow) v2_decoder_t ( - in_batch_size, options.maxmsgsize); + decoder = + new (std::nothrow) v2_decoder_t (in_batch_size, options.maxmsgsize); alloc_assert (decoder); - } - else { + } else { encoder = new (std::nothrow) v2_encoder_t (out_batch_size); alloc_assert (encoder); - decoder = new (std::nothrow) v2_decoder_t ( - in_batch_size, options.maxmsgsize); + decoder = + new (std::nothrow) v2_decoder_t (in_batch_size, options.maxmsgsize); alloc_assert (decoder); if (options.mechanism == ZMQ_NULL - && memcmp (greeting_recv + 12, "NULL\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) { + && memcmp (greeting_recv + 12, + "NULL\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) + == 0) { mechanism = new (std::nothrow) - null_mechanism_t (session, peer_address, options); + null_mechanism_t (session, peer_address, options); alloc_assert (mechanism); - } - else - if (options.mechanism == ZMQ_PLAIN - && memcmp (greeting_recv + 12, "PLAIN\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) { + } else if (options.mechanism == ZMQ_PLAIN + && memcmp (greeting_recv + 12, + "PLAIN\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) + == 0) { if (options.as_server) mechanism = new (std::nothrow) - plain_server_t (session, peer_address, options); + plain_server_t (session, peer_address, options); else - mechanism = new (std::nothrow) - plain_client_t (session, options); + mechanism = + new (std::nothrow) plain_client_t (session, options); alloc_assert (mechanism); } #ifdef ZMQ_HAVE_CURVE - else - if (options.mechanism == ZMQ_CURVE - && memcmp (greeting_recv + 12, "CURVE\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) { + else if (options.mechanism == ZMQ_CURVE + && memcmp (greeting_recv + 12, + "CURVE\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) + == 0) { if (options.as_server) mechanism = new (std::nothrow) - curve_server_t (session, peer_address, options); + curve_server_t (session, peer_address, options); else mechanism = new (std::nothrow) curve_client_t (session, options); @@ -691,21 +681,23 @@ bool zmq::stream_engine_t::handshake () } #endif #ifdef HAVE_LIBGSSAPI_KRB5 - else - if (options.mechanism == ZMQ_GSSAPI - && memcmp (greeting_recv + 12, "GSSAPI\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0) { + else if (options.mechanism == ZMQ_GSSAPI + && memcmp (greeting_recv + 12, + "GSSAPI\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) + == 0) { if (options.as_server) mechanism = new (std::nothrow) - gssapi_server_t (session, peer_address, options); + gssapi_server_t (session, peer_address, options); else mechanism = - new (std::nothrow) gssapi_client_t (session, options); + new (std::nothrow) gssapi_client_t (session, options); alloc_assert (mechanism); } #endif else { session->get_socket ()->event_handshake_failed_protocol ( - session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_MECHANISM_MISMATCH); + session->get_endpoint (), + ZMQ_PROTOCOL_ERROR_ZMTP_MECHANISM_MISMATCH); error (protocol_error); return false; } @@ -745,8 +737,7 @@ int zmq::stream_engine_t::process_routing_id_msg (msg_t *msg_) msg_->set_flags (msg_t::routing_id); int rc = session->push_msg (msg_); errno_assert (rc == 0); - } - else { + } else { int rc = msg_->close (); errno_assert (rc == 0); rc = msg_->init (); @@ -760,7 +751,7 @@ int zmq::stream_engine_t::process_routing_id_msg (msg_t *msg_) // ZMQ 2.x peers receive published messages. int rc = subscription.init_size (1); errno_assert (rc == 0); - *(unsigned char*) subscription.data () = 1; + *(unsigned char *) subscription.data () = 1; rc = session->push_msg (&subscription); errno_assert (rc == 0); } @@ -777,13 +768,10 @@ int zmq::stream_engine_t::next_handshake_command (msg_t *msg_) if (mechanism->status () == mechanism_t::ready) { mechanism_ready (); return pull_and_encode (msg_); - } - else - if (mechanism->status () == mechanism_t::error) { + } else if (mechanism->status () == mechanism_t::error) { errno = EPROTO; return -1; - } - else { + } else { const int rc = mechanism->next_handshake_command (msg_); if (rc == 0) @@ -800,8 +788,7 @@ int zmq::stream_engine_t::process_handshake_command (msg_t *msg_) if (rc == 0) { if (mechanism->status () == mechanism_t::ready) mechanism_ready (); - else - if (mechanism->status () == mechanism_t::error) { + else if (mechanism->status () == mechanism_t::error) { errno = EPROTO; return -1; } @@ -835,7 +822,7 @@ const char *zmq::stream_engine_t::get_endpoint () const void zmq::stream_engine_t::mechanism_ready () { if (options.heartbeat_interval > 0) { - add_timer(options.heartbeat_interval, heartbeat_ivl_timer_id); + add_timer (options.heartbeat_interval, heartbeat_ivl_timer_id); has_heartbeat_timer = true; } @@ -858,19 +845,18 @@ void zmq::stream_engine_t::mechanism_ready () // Compile metadata. properties_t properties; - init_properties(properties); + init_properties (properties); // Add ZAP properties. - const properties_t& zap_properties = mechanism->get_zap_properties (); - properties.insert(zap_properties.begin (), zap_properties.end ()); + const properties_t &zap_properties = mechanism->get_zap_properties (); + properties.insert (zap_properties.begin (), zap_properties.end ()); // Add ZMTP properties. - const properties_t& zmtp_properties = mechanism->get_zmtp_properties (); - properties.insert(zmtp_properties.begin (), zmtp_properties.end ()); + const properties_t &zmtp_properties = mechanism->get_zmtp_properties (); + properties.insert (zmtp_properties.begin (), zmtp_properties.end ()); zmq_assert (metadata == NULL); - if (!properties.empty ()) - { + if (!properties.empty ()) { metadata = new (std::nothrow) metadata_t (properties); alloc_assert (metadata); } @@ -890,10 +876,11 @@ int zmq::stream_engine_t::push_msg_to_session (msg_t *msg_) return session->push_msg (msg_); } -int zmq::stream_engine_t::push_raw_msg_to_session (msg_t *msg_) { - if (metadata && metadata != msg_->metadata()) - msg_->set_metadata(metadata); - return push_msg_to_session(msg_); +int zmq::stream_engine_t::push_raw_msg_to_session (msg_t *msg_) +{ + if (metadata && metadata != msg_->metadata ()) + msg_->set_metadata (metadata); + return push_msg_to_session (msg_); } int zmq::stream_engine_t::write_credential (msg_t *msg_) @@ -937,20 +924,20 @@ int zmq::stream_engine_t::decode_and_push (msg_t *msg_) if (mechanism->decode (msg_) == -1) return -1; - if(has_timeout_timer) { + if (has_timeout_timer) { has_timeout_timer = false; - cancel_timer(heartbeat_timeout_timer_id); + cancel_timer (heartbeat_timeout_timer_id); } - if(has_ttl_timer) { + if (has_ttl_timer) { has_ttl_timer = false; - cancel_timer(heartbeat_ttl_timer_id); + cancel_timer (heartbeat_ttl_timer_id); } - if(msg_->flags() & msg_t::command) { - uint8_t cmd_id = *((uint8_t*)msg_->data()); - if(cmd_id == 4) - process_heartbeat_message(msg_); + if (msg_->flags () & msg_t::command) { + uint8_t cmd_id = *((uint8_t *) msg_->data ()); + if (cmd_id == 4) + process_heartbeat_message (msg_); } if (metadata) @@ -977,9 +964,9 @@ void zmq::stream_engine_t::error (error_reason_t reason) // For raw sockets, send a final 0-length message to the application // so that it knows the peer has been disconnected. msg_t terminator; - terminator.init(); + terminator.init (); (this->*process_msg) (&terminator); - terminator.close(); + terminator.close (); } zmq_assert (session); #ifdef ZMQ_BUILD_DRAFT_API @@ -1008,102 +995,100 @@ void zmq::stream_engine_t::set_handshake_timer () } } -bool zmq::stream_engine_t::init_properties (properties_t & properties) { - if (peer_address.empty()) return false; - properties.ZMQ_MAP_INSERT_OR_EMPLACE ( - ZMQ_MSG_PROPERTY_PEER_ADDRESS, peer_address); +bool zmq::stream_engine_t::init_properties (properties_t &properties) +{ + if (peer_address.empty ()) + return false; + properties.ZMQ_MAP_INSERT_OR_EMPLACE (ZMQ_MSG_PROPERTY_PEER_ADDRESS, + peer_address); // Private property to support deprecated SRCFD std::ostringstream stream; - stream << (int)s; - std::string fd_string = stream.str(); - properties.ZMQ_MAP_INSERT_OR_EMPLACE ("__fd", ZMQ_MOVE(fd_string)); + stream << (int) s; + std::string fd_string = stream.str (); + properties.ZMQ_MAP_INSERT_OR_EMPLACE ("__fd", ZMQ_MOVE (fd_string)); return true; } void zmq::stream_engine_t::timer_event (int id_) { - if(id_ == handshake_timer_id) { + if (id_ == handshake_timer_id) { has_handshake_timer = false; // handshake timer expired before handshake completed, so engine fail error (timeout_error); - } - else if(id_ == heartbeat_ivl_timer_id) { + } else if (id_ == heartbeat_ivl_timer_id) { next_msg = &stream_engine_t::produce_ping_message; - out_event(); - add_timer(options.heartbeat_interval, heartbeat_ivl_timer_id); - } - else if(id_ == heartbeat_ttl_timer_id) { + out_event (); + add_timer (options.heartbeat_interval, heartbeat_ivl_timer_id); + } else if (id_ == heartbeat_ttl_timer_id) { has_ttl_timer = false; - error(timeout_error); - } - else if(id_ == heartbeat_timeout_timer_id) { + error (timeout_error); + } else if (id_ == heartbeat_timeout_timer_id) { has_timeout_timer = false; - error(timeout_error); - } - else + error (timeout_error); + } else // There are no other valid timer ids! - assert(false); + assert (false); } -int zmq::stream_engine_t::produce_ping_message(msg_t * msg_) +int zmq::stream_engine_t::produce_ping_message (msg_t *msg_) { int rc = 0; zmq_assert (mechanism != NULL); // 16-bit TTL + \4PING == 7 - rc = msg_->init_size(7); - errno_assert(rc == 0); - msg_->set_flags(msg_t::command); + rc = msg_->init_size (7); + errno_assert (rc == 0); + msg_->set_flags (msg_t::command); // Copy in the command message - memcpy(msg_->data(), "\4PING", 5); + memcpy (msg_->data (), "\4PING", 5); - uint16_t ttl_val = htons(options.heartbeat_ttl); - memcpy(((uint8_t*)msg_->data()) + 5, &ttl_val, sizeof(ttl_val)); + uint16_t ttl_val = htons (options.heartbeat_ttl); + memcpy (((uint8_t *) msg_->data ()) + 5, &ttl_val, sizeof (ttl_val)); rc = mechanism->encode (msg_); next_msg = &stream_engine_t::pull_and_encode; - if(!has_timeout_timer && heartbeat_timeout > 0) { - add_timer(heartbeat_timeout, heartbeat_timeout_timer_id); + if (!has_timeout_timer && heartbeat_timeout > 0) { + add_timer (heartbeat_timeout, heartbeat_timeout_timer_id); has_timeout_timer = true; } return rc; } -int zmq::stream_engine_t::produce_pong_message(msg_t * msg_) +int zmq::stream_engine_t::produce_pong_message (msg_t *msg_) { int rc = 0; zmq_assert (mechanism != NULL); - rc = msg_->init_size(5); - errno_assert(rc == 0); - msg_->set_flags(msg_t::command); + rc = msg_->init_size (5); + errno_assert (rc == 0); + msg_->set_flags (msg_t::command); - memcpy(msg_->data(), "\4PONG", 5); + memcpy (msg_->data (), "\4PONG", 5); rc = mechanism->encode (msg_); next_msg = &stream_engine_t::pull_and_encode; return rc; } -int zmq::stream_engine_t::process_heartbeat_message(msg_t * msg_) +int zmq::stream_engine_t::process_heartbeat_message (msg_t *msg_) { - if(memcmp(msg_->data(), "\4PING", 5) == 0) { + if (memcmp (msg_->data (), "\4PING", 5) == 0) { uint16_t remote_heartbeat_ttl; // Get the remote heartbeat TTL to setup the timer - memcpy(&remote_heartbeat_ttl, (uint8_t*)msg_->data() + 5, 2); - remote_heartbeat_ttl = ntohs(remote_heartbeat_ttl); + memcpy (&remote_heartbeat_ttl, (uint8_t *) msg_->data () + 5, 2); + remote_heartbeat_ttl = ntohs (remote_heartbeat_ttl); // The remote heartbeat is in 10ths of a second // so we multiply it by 100 to get the timer interval in ms. remote_heartbeat_ttl *= 100; - if(!has_ttl_timer && remote_heartbeat_ttl > 0) { - add_timer(remote_heartbeat_ttl, heartbeat_ttl_timer_id); + if (!has_ttl_timer && remote_heartbeat_ttl > 0) { + add_timer (remote_heartbeat_ttl, heartbeat_ttl_timer_id); has_ttl_timer = true; } next_msg = &stream_engine_t::produce_pong_message; - out_event(); + out_event (); } return 0; diff --git a/src/stream_engine.hpp b/src/stream_engine.hpp index fac8df6a8d..8398ffe370 100644 --- a/src/stream_engine.hpp +++ b/src/stream_engine.hpp @@ -43,191 +43,196 @@ namespace zmq { - // Protocol revisions - enum - { - ZMTP_1_0 = 0, - ZMTP_2_0 = 1 - }; +// Protocol revisions +enum +{ + ZMTP_1_0 = 0, + ZMTP_2_0 = 1 +}; - class io_thread_t; - class msg_t; - class session_base_t; - class mechanism_t; +class io_thread_t; +class msg_t; +class session_base_t; +class mechanism_t; - // This engine handles any socket with SOCK_STREAM semantics, - // e.g. TCP socket or an UNIX domain socket. +// This engine handles any socket with SOCK_STREAM semantics, +// e.g. TCP socket or an UNIX domain socket. - class stream_engine_t : public io_object_t, public i_engine +class stream_engine_t : public io_object_t, public i_engine +{ + public: + enum error_reason_t { - public: - - enum error_reason_t { - protocol_error, - connection_error, - timeout_error - }; - - stream_engine_t (fd_t fd_, const options_t &options_, - const std::string &endpoint); - ~stream_engine_t (); + protocol_error, + connection_error, + timeout_error + }; - // i_engine interface implementation. - void plug (zmq::io_thread_t *io_thread_, - zmq::session_base_t *session_); - void terminate (); - void restart_input (); - void restart_output (); - void zap_msg_available (); - const char *get_endpoint () const; + stream_engine_t (fd_t fd_, + const options_t &options_, + const std::string &endpoint); + ~stream_engine_t (); - // i_poll_events interface implementation. - void in_event (); - void out_event (); - void timer_event (int id_); + // i_engine interface implementation. + void plug (zmq::io_thread_t *io_thread_, zmq::session_base_t *session_); + void terminate (); + void restart_input (); + void restart_output (); + void zap_msg_available (); + const char *get_endpoint () const; - private: - // Unplug the engine from the session. - void unplug (); + // i_poll_events interface implementation. + void in_event (); + void out_event (); + void timer_event (int id_); - // Function to handle network disconnections. - void error (error_reason_t reason); + private: + // Unplug the engine from the session. + void unplug (); - // Receives the greeting message from the peer. - int receive_greeting (); + // Function to handle network disconnections. + void error (error_reason_t reason); - // Detects the protocol used by the peer. - bool handshake (); + // Receives the greeting message from the peer. + int receive_greeting (); - int routing_id_msg (msg_t *msg_); - int process_routing_id_msg (msg_t *msg_); + // Detects the protocol used by the peer. + bool handshake (); - int next_handshake_command (msg_t *msg); - int process_handshake_command (msg_t *msg); + int routing_id_msg (msg_t *msg_); + int process_routing_id_msg (msg_t *msg_); - int pull_msg_from_session (msg_t *msg_); - int push_msg_to_session (msg_t *msg); + int next_handshake_command (msg_t *msg); + int process_handshake_command (msg_t *msg); - int push_raw_msg_to_session (msg_t *msg); + int pull_msg_from_session (msg_t *msg_); + int push_msg_to_session (msg_t *msg); - int write_credential (msg_t *msg_); - int pull_and_encode (msg_t *msg_); - int decode_and_push (msg_t *msg_); - int push_one_then_decode_and_push (msg_t *msg_); + int push_raw_msg_to_session (msg_t *msg); - void mechanism_ready (); + int write_credential (msg_t *msg_); + int pull_and_encode (msg_t *msg_); + int decode_and_push (msg_t *msg_); + int push_one_then_decode_and_push (msg_t *msg_); - size_t add_property (unsigned char *ptr, - const char *name, const void *value, size_t value_len); + void mechanism_ready (); - void set_handshake_timer(); + size_t add_property (unsigned char *ptr, + const char *name, + const void *value, + size_t value_len); - typedef metadata_t::dict_t properties_t; - bool init_properties (properties_t & properties); + void set_handshake_timer (); - int produce_ping_message(msg_t * msg_); - int process_heartbeat_message(msg_t * msg_); - int produce_pong_message(msg_t * msg_); + typedef metadata_t::dict_t properties_t; + bool init_properties (properties_t &properties); - // Underlying socket. - fd_t s; + int produce_ping_message (msg_t *msg_); + int process_heartbeat_message (msg_t *msg_); + int produce_pong_message (msg_t *msg_); - // True iff this is server's engine. - bool as_server; + // Underlying socket. + fd_t s; - msg_t tx_msg; + // True iff this is server's engine. + bool as_server; - handle_t handle; + msg_t tx_msg; - unsigned char *inpos; - size_t insize; - i_decoder *decoder; + handle_t handle; - unsigned char *outpos; - size_t outsize; - i_encoder *encoder; + unsigned char *inpos; + size_t insize; + i_decoder *decoder; - // Metadata to be attached to received messages. May be NULL. - metadata_t *metadata; + unsigned char *outpos; + size_t outsize; + i_encoder *encoder; - // When true, we are still trying to determine whether - // the peer is using versioned protocol, and if so, which - // version. When false, normal message flow has started. - bool handshaking; + // Metadata to be attached to received messages. May be NULL. + metadata_t *metadata; - static const size_t signature_size = 10; + // When true, we are still trying to determine whether + // the peer is using versioned protocol, and if so, which + // version. When false, normal message flow has started. + bool handshaking; - // Size of ZMTP/1.0 and ZMTP/2.0 greeting message - static const size_t v2_greeting_size = 12; + static const size_t signature_size = 10; - // Size of ZMTP/3.0 greeting message - static const size_t v3_greeting_size = 64; + // Size of ZMTP/1.0 and ZMTP/2.0 greeting message + static const size_t v2_greeting_size = 12; - // Expected greeting size. - size_t greeting_size; + // Size of ZMTP/3.0 greeting message + static const size_t v3_greeting_size = 64; - // Greeting received from, and sent to peer - unsigned char greeting_recv [v3_greeting_size]; - unsigned char greeting_send [v3_greeting_size]; + // Expected greeting size. + size_t greeting_size; - // Size of greeting received so far - unsigned int greeting_bytes_read; + // Greeting received from, and sent to peer + unsigned char greeting_recv[v3_greeting_size]; + unsigned char greeting_send[v3_greeting_size]; - // The session this engine is attached to. - zmq::session_base_t *session; + // Size of greeting received so far + unsigned int greeting_bytes_read; - options_t options; + // The session this engine is attached to. + zmq::session_base_t *session; - // String representation of endpoint - std::string endpoint; + options_t options; - bool plugged; + // String representation of endpoint + std::string endpoint; - int (stream_engine_t::*next_msg) (msg_t *msg_); + bool plugged; - int (stream_engine_t::*process_msg) (msg_t *msg_); + int (stream_engine_t::*next_msg) (msg_t *msg_); - bool io_error; + int (stream_engine_t::*process_msg) (msg_t *msg_); - // Indicates whether the engine is to inject a phantom - // subscription message into the incoming stream. - // Needed to support old peers. - bool subscription_required; + bool io_error; - mechanism_t *mechanism; + // Indicates whether the engine is to inject a phantom + // subscription message into the incoming stream. + // Needed to support old peers. + bool subscription_required; - // True iff the engine couldn't consume the last decoded message. - bool input_stopped; + mechanism_t *mechanism; - // True iff the engine doesn't have any message to encode. - bool output_stopped; + // True iff the engine couldn't consume the last decoded message. + bool input_stopped; - // ID of the handshake timer - enum {handshake_timer_id = 0x40}; + // True iff the engine doesn't have any message to encode. + bool output_stopped; - // True is linger timer is running. - bool has_handshake_timer; + // ID of the handshake timer + enum + { + handshake_timer_id = 0x40 + }; - // Heartbeat stuff - enum { - heartbeat_ivl_timer_id = 0x80, - heartbeat_timeout_timer_id = 0x81, - heartbeat_ttl_timer_id = 0x82 - }; - bool has_ttl_timer; - bool has_timeout_timer; - bool has_heartbeat_timer; - int heartbeat_timeout; + // True is linger timer is running. + bool has_handshake_timer; - // Socket - zmq::socket_base_t *socket; + // Heartbeat stuff + enum + { + heartbeat_ivl_timer_id = 0x80, + heartbeat_timeout_timer_id = 0x81, + heartbeat_ttl_timer_id = 0x82 + }; + bool has_ttl_timer; + bool has_timeout_timer; + bool has_heartbeat_timer; + int heartbeat_timeout; - std::string peer_address; + // Socket + zmq::socket_base_t *socket; - stream_engine_t (const stream_engine_t&); - const stream_engine_t &operator = (const stream_engine_t&); - }; + std::string peer_address; + stream_engine_t (const stream_engine_t &); + const stream_engine_t &operator= (const stream_engine_t &); +}; } #endif diff --git a/src/sub.cpp b/src/sub.cpp index e8718e58c5..35875259f8 100644 --- a/src/sub.cpp +++ b/src/sub.cpp @@ -45,8 +45,9 @@ zmq::sub_t::~sub_t () { } -int zmq::sub_t::xsetsockopt (int option_, const void *optval_, - size_t optvallen_) +int zmq::sub_t::xsetsockopt (int option_, + const void *optval_, + size_t optvallen_) { if (option_ != ZMQ_SUBSCRIBE && option_ != ZMQ_UNSUBSCRIBE) { errno = EINVAL; @@ -57,11 +58,10 @@ int zmq::sub_t::xsetsockopt (int option_, const void *optval_, msg_t msg; int rc = msg.init_size (optvallen_ + 1); errno_assert (rc == 0); - unsigned char *data = (unsigned char*) msg.data (); + unsigned char *data = (unsigned char *) msg.data (); if (option_ == ZMQ_SUBSCRIBE) *data = 1; - else - if (option_ == ZMQ_UNSUBSCRIBE) + else if (option_ == ZMQ_UNSUBSCRIBE) *data = 0; // We explicitly allow a NULL subscription with size zero if (optvallen_) { diff --git a/src/sub.hpp b/src/sub.hpp index d913493312..8ecb5f71e6 100644 --- a/src/sub.hpp +++ b/src/sub.hpp @@ -34,31 +34,26 @@ namespace zmq { +class ctx_t; +class msg_t; +class io_thread_t; +class socket_base_t; - class ctx_t; - class msg_t; - class io_thread_t; - class socket_base_t; - - class sub_t : public xsub_t - { - public: - - sub_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~sub_t (); - - protected: - - int xsetsockopt (int option_, const void *optval_, size_t optvallen_); - int xsend (zmq::msg_t *msg_); - bool xhas_out (); - - private: - - sub_t (const sub_t&); - const sub_t &operator = (const sub_t&); - }; - +class sub_t : public xsub_t +{ + public: + sub_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~sub_t (); + + protected: + int xsetsockopt (int option_, const void *optval_, size_t optvallen_); + int xsend (zmq::msg_t *msg_); + bool xhas_out (); + + private: + sub_t (const sub_t &); + const sub_t &operator= (const sub_t &); +}; } #endif diff --git a/src/tcp.cpp b/src/tcp.cpp index 7682cfa0c4..aabd8ecb48 100644 --- a/src/tcp.cpp +++ b/src/tcp.cpp @@ -51,8 +51,8 @@ int zmq::tune_tcp_socket (fd_t s_) // so using Nagle wouldn't improve throughput in anyway, but it would // hurt latency. int nodelay = 1; - int rc = setsockopt (s_, IPPROTO_TCP, TCP_NODELAY, (char*) &nodelay, - sizeof (int)); + int rc = setsockopt (s_, IPPROTO_TCP, TCP_NODELAY, (char *) &nodelay, + sizeof (int)); tcp_assert_tuning_error (s_, rc); if (rc != 0) return rc; @@ -60,8 +60,8 @@ int zmq::tune_tcp_socket (fd_t s_) #ifdef ZMQ_HAVE_OPENVMS // Disable delayed acknowledgements as they hurt latency significantly. int nodelack = 1; - rc = setsockopt (s_, IPPROTO_TCP, TCP_NODELACK, (char*) &nodelack, - sizeof (int)); + rc = setsockopt (s_, IPPROTO_TCP, TCP_NODELACK, (char *) &nodelack, + sizeof (int)); tcp_assert_tuning_error (s_, rc); #endif return rc; @@ -70,7 +70,7 @@ int zmq::tune_tcp_socket (fd_t s_) int zmq::set_tcp_send_buffer (fd_t sockfd_, int bufsize_) { const int rc = setsockopt (sockfd_, SOL_SOCKET, SO_SNDBUF, - (char*) &bufsize_, sizeof bufsize_); + (char *) &bufsize_, sizeof bufsize_); tcp_assert_tuning_error (sockfd_, rc); return rc; } @@ -78,13 +78,16 @@ int zmq::set_tcp_send_buffer (fd_t sockfd_, int bufsize_) int zmq::set_tcp_receive_buffer (fd_t sockfd_, int bufsize_) { const int rc = setsockopt (sockfd_, SOL_SOCKET, SO_RCVBUF, - (char *) &bufsize_, sizeof bufsize_); + (char *) &bufsize_, sizeof bufsize_); tcp_assert_tuning_error (sockfd_, rc); return rc; } -int zmq::tune_tcp_keepalives (fd_t s_, int keepalive_, int keepalive_cnt_, - int keepalive_idle_, int keepalive_intvl_) +int zmq::tune_tcp_keepalives (fd_t s_, + int keepalive_, + int keepalive_cnt_, + int keepalive_idle_, + int keepalive_intvl_) { // These options are used only under certain #ifdefs below. LIBZMQ_UNUSED (keepalive_); @@ -101,13 +104,14 @@ int zmq::tune_tcp_keepalives (fd_t s_, int keepalive_, int keepalive_cnt_, if (keepalive_ != -1) { tcp_keepalive keepalive_opts; keepalive_opts.onoff = keepalive_; - keepalive_opts.keepalivetime = keepalive_idle_ != -1 ? - keepalive_idle_ * 1000 : 7200000; - keepalive_opts.keepaliveinterval = keepalive_intvl_ != -1 ? - keepalive_intvl_ * 1000 : 1000; + keepalive_opts.keepalivetime = + keepalive_idle_ != -1 ? keepalive_idle_ * 1000 : 7200000; + keepalive_opts.keepaliveinterval = + keepalive_intvl_ != -1 ? keepalive_intvl_ * 1000 : 1000; DWORD num_bytes_returned; int rc = WSAIoctl (s_, SIO_KEEPALIVE_VALS, &keepalive_opts, - sizeof (keepalive_opts), NULL, 0, &num_bytes_returned, NULL, NULL); + sizeof (keepalive_opts), NULL, 0, + &num_bytes_returned, NULL, NULL); tcp_assert_tuning_error (s_, rc); if (rc == SOCKET_ERROR) return rc; @@ -115,16 +119,16 @@ int zmq::tune_tcp_keepalives (fd_t s_, int keepalive_, int keepalive_cnt_, #else #ifdef ZMQ_HAVE_SO_KEEPALIVE if (keepalive_ != -1) { - int rc = setsockopt (s_, SOL_SOCKET, SO_KEEPALIVE, - (char*) &keepalive_, sizeof (int)); + int rc = setsockopt (s_, SOL_SOCKET, SO_KEEPALIVE, (char *) &keepalive_, + sizeof (int)); tcp_assert_tuning_error (s_, rc); if (rc != 0) return rc; #ifdef ZMQ_HAVE_TCP_KEEPCNT if (keepalive_cnt_ != -1) { - int rc = setsockopt (s_, IPPROTO_TCP, TCP_KEEPCNT, - &keepalive_cnt_, sizeof (int)); + int rc = setsockopt (s_, IPPROTO_TCP, TCP_KEEPCNT, &keepalive_cnt_, + sizeof (int)); tcp_assert_tuning_error (s_, rc); if (rc != 0) return rc; @@ -134,7 +138,7 @@ int zmq::tune_tcp_keepalives (fd_t s_, int keepalive_, int keepalive_cnt_, #ifdef ZMQ_HAVE_TCP_KEEPIDLE if (keepalive_idle_ != -1) { int rc = setsockopt (s_, IPPROTO_TCP, TCP_KEEPIDLE, - &keepalive_idle_, sizeof (int)); + &keepalive_idle_, sizeof (int)); tcp_assert_tuning_error (s_, rc); if (rc != 0) return rc; @@ -143,7 +147,7 @@ int zmq::tune_tcp_keepalives (fd_t s_, int keepalive_, int keepalive_cnt_, #ifdef ZMQ_HAVE_TCP_KEEPALIVE if (keepalive_idle_ != -1) { int rc = setsockopt (s_, IPPROTO_TCP, TCP_KEEPALIVE, - &keepalive_idle_, sizeof (int)); + &keepalive_idle_, sizeof (int)); tcp_assert_tuning_error (s_, rc); if (rc != 0) return rc; @@ -154,7 +158,7 @@ int zmq::tune_tcp_keepalives (fd_t s_, int keepalive_, int keepalive_cnt_, #ifdef ZMQ_HAVE_TCP_KEEPINTVL if (keepalive_intvl_ != -1) { int rc = setsockopt (s_, IPPROTO_TCP, TCP_KEEPINTVL, - &keepalive_intvl_, sizeof (int)); + &keepalive_intvl_, sizeof (int)); tcp_assert_tuning_error (s_, rc); if (rc != 0) return rc; @@ -163,7 +167,7 @@ int zmq::tune_tcp_keepalives (fd_t s_, int keepalive_, int keepalive_cnt_, } #endif // ZMQ_HAVE_SO_KEEPALIVE #endif // ZMQ_HAVE_WINDOWS - + return 0; } @@ -174,28 +178,28 @@ int zmq::tune_tcp_maxrt (fd_t sockfd_, int timeout_) LIBZMQ_UNUSED (sockfd_); -#if defined (ZMQ_HAVE_WINDOWS) && defined (TCP_MAXRT) +#if defined(ZMQ_HAVE_WINDOWS) && defined(TCP_MAXRT) // msdn says it's supported in >= Vista, >= Windows Server 2003 - timeout_ /= 1000; // in seconds - int rc = setsockopt (sockfd_, IPPROTO_TCP, TCP_MAXRT, (char*) &timeout_, - sizeof (timeout_)); + timeout_ /= 1000; // in seconds + int rc = setsockopt (sockfd_, IPPROTO_TCP, TCP_MAXRT, (char *) &timeout_, + sizeof (timeout_)); tcp_assert_tuning_error (sockfd_, rc); return rc; // FIXME: should be ZMQ_HAVE_TCP_USER_TIMEOUT -#elif defined (TCP_USER_TIMEOUT) +#elif defined(TCP_USER_TIMEOUT) int rc = setsockopt (sockfd_, IPPROTO_TCP, TCP_USER_TIMEOUT, &timeout_, - sizeof (timeout_)); + sizeof (timeout_)); tcp_assert_tuning_error (sockfd_, rc); return rc; #endif return 0; } - int zmq::tcp_write (fd_t s_, const void *data_, size_t size_) +int zmq::tcp_write (fd_t s_, const void *data_, size_t size_) { #ifdef ZMQ_HAVE_WINDOWS - int nbytes = send (s_, (char*) data_, (int) size_, 0); + int nbytes = send (s_, (char *) data_, (int) size_, 0); // If not a single byte can be written to the socket in non-blocking mode // we'll get an error (this may happen during the speculative write). @@ -204,14 +208,10 @@ int zmq::tune_tcp_maxrt (fd_t sockfd_, int timeout_) return 0; // Signalise peer failure. - if (nbytes == SOCKET_ERROR && ( - last_error == WSAENETDOWN || - last_error == WSAENETRESET || - last_error == WSAEHOSTUNREACH || - last_error == WSAECONNABORTED || - last_error == WSAETIMEDOUT || - last_error == WSAECONNRESET - )) + if (nbytes == SOCKET_ERROR + && (last_error == WSAENETDOWN || last_error == WSAENETRESET + || last_error == WSAEHOSTUNREACH || last_error == WSAECONNABORTED + || last_error == WSAETIMEDOUT || last_error == WSAECONNRESET)) return -1; // Circumvent a Windows bug: @@ -229,25 +229,20 @@ int zmq::tune_tcp_maxrt (fd_t sockfd_, int timeout_) // Several errors are OK. When speculative write is being done we may not // be able to write a single byte from the socket. Also, SIGSTOP issued // by a debugging tool can result in EINTR error. - if (nbytes == -1 && (errno == EAGAIN || errno == EWOULDBLOCK || - errno == EINTR)) + if (nbytes == -1 + && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) return 0; // Signalise peer failure. if (nbytes == -1) { - errno_assert (errno != EACCES - && errno != EBADF - && errno != EDESTADDRREQ - && errno != EFAULT - && errno != EISCONN - && errno != EMSGSIZE - && errno != ENOMEM - && errno != ENOTSOCK - && errno != EOPNOTSUPP); + errno_assert (errno != EACCES && errno != EBADF && errno != EDESTADDRREQ + && errno != EFAULT && errno != EISCONN + && errno != EMSGSIZE && errno != ENOMEM + && errno != ENOTSOCK && errno != EOPNOTSUPP); return -1; } - return static_cast (nbytes); + return static_cast (nbytes); #endif } @@ -256,7 +251,7 @@ int zmq::tcp_read (fd_t s_, void *data_, size_t size_) { #ifdef ZMQ_HAVE_WINDOWS - const int rc = recv (s_, (char*) data_, (int) size_, 0); + const int rc = recv (s_, (char *) data_, (int) size_, 0); // If not a single byte can be read from the socket in non-blocking mode // we'll get an error (this may happen during the speculative read). @@ -264,15 +259,12 @@ int zmq::tcp_read (fd_t s_, void *data_, size_t size_) const int last_error = WSAGetLastError (); if (last_error == WSAEWOULDBLOCK) { errno = EAGAIN; - } - else { - wsa_assert (last_error == WSAENETDOWN || - last_error == WSAENETRESET || - last_error == WSAECONNABORTED || - last_error == WSAETIMEDOUT || - last_error == WSAECONNRESET || - last_error == WSAECONNREFUSED || - last_error == WSAENOTCONN); + } else { + wsa_assert ( + last_error == WSAENETDOWN || last_error == WSAENETRESET + || last_error == WSAECONNABORTED || last_error == WSAETIMEDOUT + || last_error == WSAECONNRESET || last_error == WSAECONNREFUSED + || last_error == WSAENOTCONN); errno = wsa_error_to_errno (last_error); } } @@ -287,15 +279,13 @@ int zmq::tcp_read (fd_t s_, void *data_, size_t size_) // be able to read a single byte from the socket. Also, SIGSTOP issued // by a debugging tool can result in EINTR error. if (rc == -1) { - errno_assert (errno != EBADF - && errno != EFAULT - && errno != ENOMEM - && errno != ENOTSOCK); + errno_assert (errno != EBADF && errno != EFAULT && errno != ENOMEM + && errno != ENOTSOCK); if (errno == EWOULDBLOCK || errno == EINTR) errno = EAGAIN; } - return static_cast (rc); + return static_cast (rc); #endif } @@ -312,26 +302,20 @@ void zmq::tcp_assert_tuning_error (zmq::fd_t s_, int rc_) #else socklen_t len = sizeof err; #endif - - int rc = getsockopt (s_, SOL_SOCKET, SO_ERROR, (char*) &err, &len); - + + int rc = getsockopt (s_, SOL_SOCKET, SO_ERROR, (char *) &err, &len); + // Assert if the error was caused by 0MQ bug. // Networking problems are OK. No need to assert. #ifdef ZMQ_HAVE_WINDOWS zmq_assert (rc == 0); if (err != 0) { - wsa_assert (err == WSAECONNREFUSED - || err == WSAECONNRESET - || err == WSAECONNABORTED - || err == WSAEINTR - || err == WSAETIMEDOUT - || err == WSAEHOSTUNREACH - || err == WSAENETUNREACH - || err == WSAENETDOWN - || err == WSAENETRESET - || err == WSAEACCES - || err == WSAEINVAL - || err == WSAEADDRINUSE); + wsa_assert (err == WSAECONNREFUSED || err == WSAECONNRESET + || err == WSAECONNABORTED || err == WSAEINTR + || err == WSAETIMEDOUT || err == WSAEHOSTUNREACH + || err == WSAENETUNREACH || err == WSAENETDOWN + || err == WSAENETRESET || err == WSAEACCES + || err == WSAEINVAL || err == WSAEADDRINUSE); } #else // Following code should handle both Berkeley-derived socket @@ -340,17 +324,11 @@ void zmq::tcp_assert_tuning_error (zmq::fd_t s_, int rc_) err = errno; if (err != 0) { errno = err; - errno_assert ( - errno == ECONNREFUSED || - errno == ECONNRESET || - errno == ECONNABORTED || - errno == EINTR || - errno == ETIMEDOUT || - errno == EHOSTUNREACH || - errno == ENETUNREACH || - errno == ENETDOWN || - errno == ENETRESET || - errno == EINVAL); + errno_assert (errno == ECONNREFUSED || errno == ECONNRESET + || errno == ECONNABORTED || errno == EINTR + || errno == ETIMEDOUT || errno == EHOSTUNREACH + || errno == ENETUNREACH || errno == ENETDOWN + || errno == ENETRESET || errno == EINVAL); } #endif } diff --git a/src/tcp.hpp b/src/tcp.hpp index 4d18a3aee2..842b0e4e4c 100644 --- a/src/tcp.hpp +++ b/src/tcp.hpp @@ -34,36 +34,38 @@ namespace zmq { - - // Tunes the supplied TCP socket for the best latency. - int tune_tcp_socket (fd_t s_); - - // Sets the socket send buffer size. - int set_tcp_send_buffer (fd_t sockfd_, int bufsize_); - - // Sets the socket receive buffer size. - int set_tcp_receive_buffer (fd_t sockfd_, int bufsize_); - - // Tunes TCP keep-alives - int tune_tcp_keepalives (fd_t s_, int keepalive_, int keepalive_cnt_, - int keepalive_idle_, int keepalive_intvl_); - - // Tunes TCP max retransmit timeout - int tune_tcp_maxrt (fd_t sockfd_, int timeout_); - - // Writes data to the socket. Returns the number of bytes actually - // written (even zero is to be considered to be a success). In case - // of error or orderly shutdown by the other peer -1 is returned. - int tcp_write (fd_t s_, const void *data_, size_t size_); - - // Reads data from the socket (up to 'size' bytes). - // Returns the number of bytes actually read or -1 on error. - // Zero indicates the peer has closed the connection. - int tcp_read (fd_t s_, void *data_, size_t size_); - - // Asserts that an internal error did not occur. Does not assert - // on network errors such as reset or aborted connections. - void tcp_assert_tuning_error (fd_t s_, int rc_); +// Tunes the supplied TCP socket for the best latency. +int tune_tcp_socket (fd_t s_); + +// Sets the socket send buffer size. +int set_tcp_send_buffer (fd_t sockfd_, int bufsize_); + +// Sets the socket receive buffer size. +int set_tcp_receive_buffer (fd_t sockfd_, int bufsize_); + +// Tunes TCP keep-alives +int tune_tcp_keepalives (fd_t s_, + int keepalive_, + int keepalive_cnt_, + int keepalive_idle_, + int keepalive_intvl_); + +// Tunes TCP max retransmit timeout +int tune_tcp_maxrt (fd_t sockfd_, int timeout_); + +// Writes data to the socket. Returns the number of bytes actually +// written (even zero is to be considered to be a success). In case +// of error or orderly shutdown by the other peer -1 is returned. +int tcp_write (fd_t s_, const void *data_, size_t size_); + +// Reads data from the socket (up to 'size' bytes). +// Returns the number of bytes actually read or -1 on error. +// Zero indicates the peer has closed the connection. +int tcp_read (fd_t s_, void *data_, size_t size_); + +// Asserts that an internal error did not occur. Does not assert +// on network errors such as reset or aborted connections. +void tcp_assert_tuning_error (fd_t s_, int rc_); } #endif diff --git a/src/tcp_address.cpp b/src/tcp_address.cpp index 12c2339513..deeb3d037c 100644 --- a/src/tcp_address.cpp +++ b/src/tcp_address.cpp @@ -52,7 +52,9 @@ #include // On Solaris platform, network interface name can be queried by ioctl. -int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_) +int zmq::tcp_address_t::resolve_nic_name (const char *nic_, + bool ipv6_, + bool is_src_) { // TODO: Unused parameter, IPv6 support not implemented for Solaris. LIBZMQ_UNUSED (ipv6_); @@ -65,12 +67,12 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ lifnum ifn; ifn.lifn_family = AF_INET; ifn.lifn_flags = 0; - int rc = ioctl (fd, SIOCGLIFNUM, (char*) &ifn); + int rc = ioctl (fd, SIOCGLIFNUM, (char *) &ifn); errno_assert (rc != -1); // Allocate memory to get interface names. const size_t ifr_size = sizeof (struct lifreq) * ifn.lifn_count; - char *ifr = (char*) malloc (ifr_size); + char *ifr = (char *) malloc (ifr_size); alloc_assert (ifr); // Retrieve interface names. @@ -79,22 +81,21 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ ifc.lifc_flags = 0; ifc.lifc_len = ifr_size; ifc.lifc_buf = ifr; - rc = ioctl (fd, SIOCGLIFCONF, (char*) &ifc); + rc = ioctl (fd, SIOCGLIFCONF, (char *) &ifc); errno_assert (rc != -1); // Find the interface with the specified name and AF_INET family. bool found = false; lifreq *ifrp = ifc.lifc_req; - for (int n = 0; n < (int) (ifc.lifc_len / sizeof (lifreq)); - n ++, ifrp ++) { + for (int n = 0; n < (int) (ifc.lifc_len / sizeof (lifreq)); n++, ifrp++) { if (!strcmp (nic_, ifrp->lifr_name)) { - rc = ioctl (fd, SIOCGLIFADDR, (char*) ifrp); + rc = ioctl (fd, SIOCGLIFADDR, (char *) ifrp); errno_assert (rc != -1); if (ifrp->lifr_addr.ss_family == AF_INET) { if (is_src_) - source_address.ipv4 = *(sockaddr_in*) &ifrp->lifr_addr; + source_address.ipv4 = *(sockaddr_in *) &ifrp->lifr_addr; else - address.ipv4 = *(sockaddr_in*) &ifrp->lifr_addr; + address.ipv4 = *(sockaddr_in *) &ifrp->lifr_addr; found = true; break; } @@ -115,12 +116,13 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ #elif defined ZMQ_HAVE_AIX || defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_ANDROID #include -int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_) +int zmq::tcp_address_t::resolve_nic_name (const char *nic_, + bool ipv6_, + bool is_src_) { #if defined ZMQ_HAVE_AIX || defined ZMQ_HAVE_HPUX // IPv6 support not implemented for AIX or HP/UX. - if (ipv6_) - { + if (ipv6_) { errno = ENODEV; return -1; } @@ -133,10 +135,10 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ struct ifreq ifr; // Copy interface name for ioctl get. - strncpy (ifr.ifr_name, nic_, sizeof (ifr.ifr_name) ); + strncpy (ifr.ifr_name, nic_, sizeof (ifr.ifr_name)); // Fetch interface address. - const int rc = ioctl (sd, SIOCGIFADDR, (caddr_t) &ifr, sizeof (ifr) ); + const int rc = ioctl (sd, SIOCGIFADDR, (caddr_t) &ifr, sizeof (ifr)); // Clean up. close (sd); @@ -148,8 +150,7 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ const int family = ifr.ifr_addr.sa_family; if (family == (ipv6_ ? AF_INET6 : AF_INET) - && !strcmp (nic_, ifr.ifr_name)) - { + && !strcmp (nic_, ifr.ifr_name)) { if (is_src_) memcpy (&source_address, &ifr.ifr_addr, (family == AF_INET) ? sizeof (struct sockaddr_in) @@ -158,9 +159,7 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ memcpy (&address, &ifr.ifr_addr, (family == AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct sockaddr_in6)); - } - else - { + } else { errno = ENODEV; return -1; } @@ -168,17 +167,19 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ return 0; } -#elif ((defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\ - defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_OPENBSD ||\ - defined ZMQ_HAVE_QNXNTO || defined ZMQ_HAVE_NETBSD ||\ - defined ZMQ_HAVE_DRAGONFLY || defined ZMQ_HAVE_GNU)\ - && defined ZMQ_HAVE_IFADDRS) +#elif ((defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD \ + || defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_OPENBSD \ + || defined ZMQ_HAVE_QNXNTO || defined ZMQ_HAVE_NETBSD \ + || defined ZMQ_HAVE_DRAGONFLY || defined ZMQ_HAVE_GNU) \ + && defined ZMQ_HAVE_IFADDRS) #include // On these platforms, network interface name can be queried // using getifaddrs function. -int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_) +int zmq::tcp_address_t::resolve_nic_name (const char *nic_, + bool ipv6_, + bool is_src_) { // Get the addresses. ifaddrs *ifa = NULL; @@ -192,7 +193,7 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ usleep ((backoff_msec << i) * 1000); } - if (rc != 0 && ((errno == EINVAL) || (errno==EOPNOTSUPP))) { + if (rc != 0 && ((errno == EINVAL) || (errno == EOPNOTSUPP))) { // Windows Subsystem for Linux compatibility LIBZMQ_UNUSED (nic_); LIBZMQ_UNUSED (ipv6_); @@ -211,7 +212,7 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ const int family = ifp->ifa_addr->sa_family; if (family == (ipv6_ ? AF_INET6 : AF_INET) - && !strcmp (nic_, ifp->ifa_name)) { + && !strcmp (nic_, ifp->ifa_name)) { if (is_src_) memcpy (&source_address, ifp->ifa_addr, (family == AF_INET) ? sizeof (struct sockaddr_in) @@ -239,22 +240,24 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ #include -int zmq::tcp_address_t::get_interface_name(unsigned long index, char ** dest) const { +int zmq::tcp_address_t::get_interface_name (unsigned long index, + char **dest) const +{ #ifdef ZMQ_HAVE_WINDOWS_UWP - char * buffer = (char*)malloc(1024); + char *buffer = (char *) malloc (1024); #else - char * buffer = (char*)malloc(IF_MAX_STRING_SIZE); + char *buffer = (char *) malloc (IF_MAX_STRING_SIZE); #endif - alloc_assert(buffer); + alloc_assert (buffer); - char * if_name_result = NULL; + char *if_name_result = NULL; -#if !defined ZMQ_HAVE_WINDOWS_TARGET_XP && !defined ZMQ_HAVE_WINDOWS_UWP - if_name_result = if_indextoname(index, buffer); +#if !defined ZMQ_HAVE_WINDOWS_TARGET_XP && !defined ZMQ_HAVE_WINDOWS_UWP + if_name_result = if_indextoname (index, buffer); #endif if (if_name_result == NULL) { - free(buffer); + free (buffer); return -1; } @@ -262,23 +265,19 @@ int zmq::tcp_address_t::get_interface_name(unsigned long index, char ** dest) co return 0; } -int zmq::tcp_address_t::wchar_to_utf8(const WCHAR * src, char ** dest) const { +int zmq::tcp_address_t::wchar_to_utf8 (const WCHAR *src, char **dest) const +{ int rc; - int buffer_len = WideCharToMultiByte(CP_UTF8, 0, - src, -1, - NULL, 0, - NULL, 0); + int buffer_len = + WideCharToMultiByte (CP_UTF8, 0, src, -1, NULL, 0, NULL, 0); - char * buffer = (char*) malloc(buffer_len); - alloc_assert(buffer); + char *buffer = (char *) malloc (buffer_len); + alloc_assert (buffer); - rc = WideCharToMultiByte(CP_UTF8, 0, - src, -1, - buffer, buffer_len, - NULL, 0); + rc = WideCharToMultiByte (CP_UTF8, 0, src, -1, buffer, buffer_len, NULL, 0); if (rc == 0) { - free(buffer); + free (buffer); return -1; } @@ -286,30 +285,32 @@ int zmq::tcp_address_t::wchar_to_utf8(const WCHAR * src, char ** dest) const { return 0; } -int zmq::tcp_address_t::resolve_nic_name(const char *nic_, bool ipv6_, bool is_src_) +int zmq::tcp_address_t::resolve_nic_name (const char *nic_, + bool ipv6_, + bool is_src_) { int rc; bool found = false; const int max_attempts = 10; int iterations = 0; - IP_ADAPTER_ADDRESSES * addresses = NULL; - IP_ADAPTER_ADDRESSES * current_addresses = NULL; - unsigned long out_buf_len = sizeof(IP_ADAPTER_ADDRESSES); + IP_ADAPTER_ADDRESSES *addresses = NULL; + IP_ADAPTER_ADDRESSES *current_addresses = NULL; + unsigned long out_buf_len = sizeof (IP_ADAPTER_ADDRESSES); do { - addresses = (IP_ADAPTER_ADDRESSES *) malloc(out_buf_len); - alloc_assert(addresses); - - rc = GetAdaptersAddresses(AF_UNSPEC, - GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, - NULL, - addresses, &out_buf_len); + addresses = (IP_ADAPTER_ADDRESSES *) malloc (out_buf_len); + alloc_assert (addresses); + + rc = + GetAdaptersAddresses (AF_UNSPEC, + GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST + | GAA_FLAG_SKIP_DNS_SERVER, + NULL, addresses, &out_buf_len); if (rc == ERROR_BUFFER_OVERFLOW) { - free(addresses); + free (addresses); addresses = NULL; - } - else { + } else { break; } iterations++; @@ -318,35 +319,40 @@ int zmq::tcp_address_t::resolve_nic_name(const char *nic_, bool ipv6_, bool is_s if (rc == 0) { current_addresses = addresses; while (current_addresses) { - char * if_name = NULL; - char * if_friendly_name = NULL; + char *if_name = NULL; + char *if_friendly_name = NULL; int str_rc1, str_rc2; - str_rc1 = get_interface_name(current_addresses->IfIndex, &if_name); - str_rc2 = wchar_to_utf8(current_addresses->FriendlyName, &if_friendly_name); + str_rc1 = get_interface_name (current_addresses->IfIndex, &if_name); + str_rc2 = wchar_to_utf8 (current_addresses->FriendlyName, + &if_friendly_name); // Find a network adapter by its "name" or "friendly name" - if ( - ((str_rc1 == 0) && (!strcmp(nic_, if_name))) - || ((str_rc2 == 0) && (!strcmp(nic_, if_friendly_name))) - ) { - + if (((str_rc1 == 0) && (!strcmp (nic_, if_name))) + || ((str_rc2 == 0) && (!strcmp (nic_, if_friendly_name)))) { // Iterate over all unicast addresses bound to the current network interface - IP_ADAPTER_UNICAST_ADDRESS * unicast_address = current_addresses->FirstUnicastAddress; - IP_ADAPTER_UNICAST_ADDRESS * current_unicast_address = unicast_address; + IP_ADAPTER_UNICAST_ADDRESS *unicast_address = + current_addresses->FirstUnicastAddress; + IP_ADAPTER_UNICAST_ADDRESS *current_unicast_address = + unicast_address; while (current_unicast_address) { - ADDRESS_FAMILY family = current_unicast_address->Address.lpSockaddr->sa_family; + ADDRESS_FAMILY family = + current_unicast_address->Address.lpSockaddr->sa_family; if (family == (ipv6_ ? AF_INET6 : AF_INET)) { if (is_src_) - memcpy(&source_address, current_unicast_address->Address.lpSockaddr, - (family == AF_INET) ? sizeof(struct sockaddr_in) - : sizeof(struct sockaddr_in6)); + memcpy (&source_address, + current_unicast_address->Address.lpSockaddr, + (family == AF_INET) + ? sizeof (struct sockaddr_in) + : sizeof (struct sockaddr_in6)); else - memcpy(&address, current_unicast_address->Address.lpSockaddr, - (family == AF_INET) ? sizeof(struct sockaddr_in) - : sizeof(struct sockaddr_in6)); + memcpy (&address, + current_unicast_address->Address.lpSockaddr, + (family == AF_INET) + ? sizeof (struct sockaddr_in) + : sizeof (struct sockaddr_in6)); found = true; break; } @@ -354,16 +360,19 @@ int zmq::tcp_address_t::resolve_nic_name(const char *nic_, bool ipv6_, bool is_s current_unicast_address = current_unicast_address->Next; } - if (found) break; + if (found) + break; } - if (str_rc1 == 0) free(if_name); - if (str_rc2 == 0) free(if_friendly_name); + if (str_rc1 == 0) + free (if_name); + if (str_rc2 == 0) + free (if_friendly_name); current_addresses = current_addresses->Next; } - free(addresses); + free (addresses); } if (!found) { @@ -376,7 +385,9 @@ int zmq::tcp_address_t::resolve_nic_name(const char *nic_, bool ipv6_, bool is_s #else // On other platforms we assume there are no sane interface names. -int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_) +int zmq::tcp_address_t::resolve_nic_name (const char *nic_, + bool ipv6_, + bool is_src_) { LIBZMQ_UNUSED (nic_); LIBZMQ_UNUSED (ipv6_); @@ -387,26 +398,27 @@ int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_ #endif -int zmq::tcp_address_t::resolve_interface (const char *interface_, bool ipv6_, bool is_src_) +int zmq::tcp_address_t::resolve_interface (const char *interface_, + bool ipv6_, + bool is_src_) { // Initialize temporary output pointers with storage address. sockaddr_storage ss; - sockaddr *out_addr = (sockaddr*) &ss; + sockaddr *out_addr = (sockaddr *) &ss; size_t out_addrlen; // Initialise IP-format family/port and populate temporary output pointers // with the address. if (ipv6_) { sockaddr_in6 ip6_addr; - memset (&ip6_addr, 0, sizeof (ip6_addr) ); + memset (&ip6_addr, 0, sizeof (ip6_addr)); ip6_addr.sin6_family = AF_INET6; - memcpy (&ip6_addr.sin6_addr, &in6addr_any, sizeof (in6addr_any) ); + memcpy (&ip6_addr.sin6_addr, &in6addr_any, sizeof (in6addr_any)); out_addrlen = sizeof (ip6_addr); memcpy (out_addr, &ip6_addr, out_addrlen); - } - else { + } else { sockaddr_in ip4_addr; - memset (&ip4_addr, 0, sizeof (ip4_addr) ); + memset (&ip4_addr, 0, sizeof (ip4_addr)); ip4_addr.sin_family = AF_INET; ip4_addr.sin_addr.s_addr = htonl (INADDR_ANY); out_addrlen = sizeof (ip4_addr); @@ -414,7 +426,7 @@ int zmq::tcp_address_t::resolve_interface (const char *interface_, bool ipv6_, b } // "*" resolves to INADDR_ANY or in6addr_any. if (strcmp (interface_, "*") == 0) { - zmq_assert (out_addrlen <= sizeof (address) ); + zmq_assert (out_addrlen <= sizeof (address)); if (is_src_) memcpy (&source_address, out_addr, out_addrlen); else @@ -427,7 +439,7 @@ int zmq::tcp_address_t::resolve_interface (const char *interface_, bool ipv6_, b if (rc == 0 || errno != ENODEV) return rc; - // There's no such interface name. Assume literal address. + // There's no such interface name. Assume literal address. #if defined ZMQ_HAVE_OPENVMS && defined __ia64 __addrinfo64 *res = NULL; __addrinfo64 req; @@ -435,11 +447,11 @@ int zmq::tcp_address_t::resolve_interface (const char *interface_, bool ipv6_, b addrinfo *res = NULL; addrinfo req; #endif - memset (&req, 0, sizeof (req) ); + memset (&req, 0, sizeof (req)); // Choose IPv4 or IPv6 protocol family. Note that IPv6 allows for // IPv4-in-IPv6 addresses. - req.ai_family = ipv6_? AF_INET6: AF_INET; + req.ai_family = ipv6_ ? AF_INET6 : AF_INET; // Arbitrary, not used in the output, but avoids duplicate results. req.ai_socktype = SOCK_STREAM; @@ -459,14 +471,14 @@ int zmq::tcp_address_t::resolve_interface (const char *interface_, bool ipv6_, b // Resolve the literal address. Some of the error info is lost in case // of error, however, there's no way to report EAI errors via errno. - rc = getaddrinfo(interface_, NULL, &req, &res); + rc = getaddrinfo (interface_, NULL, &req, &res); #if defined AI_V4MAPPED // Some OS do have AI_V4MAPPED defined but it is not supported in getaddrinfo() // returning EAI_BADFLAGS. Detect this and retry if (rc == EAI_BADFLAGS && (req.ai_flags & AI_V4MAPPED)) { req.ai_flags &= ~AI_V4MAPPED; - rc = getaddrinfo(interface_, NULL, &req, &res); + rc = getaddrinfo (interface_, NULL, &req, &res); } #endif @@ -475,7 +487,7 @@ int zmq::tcp_address_t::resolve_interface (const char *interface_, bool ipv6_, b // with ZMQ_IPv6 socket option. if ((req.ai_family == AF_INET6) && (rc == WSAHOST_NOT_FOUND)) { req.ai_family = AF_INET; - rc = getaddrinfo(interface_, NULL, &req, &res); + rc = getaddrinfo (interface_, NULL, &req, &res); } #endif @@ -486,7 +498,7 @@ int zmq::tcp_address_t::resolve_interface (const char *interface_, bool ipv6_, b // Use the first result. zmq_assert (res != NULL); - zmq_assert ((size_t) res->ai_addrlen <= sizeof (address) ); + zmq_assert ((size_t) res->ai_addrlen <= sizeof (address)); if (is_src_) memcpy (&source_address, res->ai_addr, res->ai_addrlen); else @@ -498,19 +510,21 @@ int zmq::tcp_address_t::resolve_interface (const char *interface_, bool ipv6_, b return 0; } -int zmq::tcp_address_t::resolve_hostname (const char *hostname_, bool ipv6_, bool is_src_) +int zmq::tcp_address_t::resolve_hostname (const char *hostname_, + bool ipv6_, + bool is_src_) { - // Set up the query. +// Set up the query. #if defined ZMQ_HAVE_OPENVMS && defined __ia64 && __INITIAL_POINTER_SIZE == 64 __addrinfo64 req; #else addrinfo req; #endif - memset (&req, 0, sizeof (req) ); + memset (&req, 0, sizeof (req)); // Choose IPv4 or IPv6 protocol family. Note that IPv6 allows for // IPv4-in-IPv6 addresses. - req.ai_family = ipv6_? AF_INET6: AF_INET; + req.ai_family = ipv6_ ? AF_INET6 : AF_INET; // Need to choose one to avoid duplicate results from getaddrinfo() - this // doesn't really matter, since it's not included in the addr-output. @@ -524,8 +538,8 @@ int zmq::tcp_address_t::resolve_hostname (const char *hostname_, bool ipv6_, boo req.ai_flags |= AI_V4MAPPED; #endif - // Resolve host name. Some of the error info is lost in case of error, - // however, there's no way to report EAI errors via errno. + // Resolve host name. Some of the error info is lost in case of error, + // however, there's no way to report EAI errors via errno. #if defined ZMQ_HAVE_OPENVMS && defined __ia64 && __INITIAL_POINTER_SIZE == 64 __addrinfo64 *res; #else @@ -538,24 +552,24 @@ int zmq::tcp_address_t::resolve_hostname (const char *hostname_, bool ipv6_, boo // returning EAI_BADFLAGS. Detect this and retry if (rc == EAI_BADFLAGS && (req.ai_flags & AI_V4MAPPED)) { req.ai_flags &= ~AI_V4MAPPED; - rc = getaddrinfo(hostname_, NULL, &req, &res); + rc = getaddrinfo (hostname_, NULL, &req, &res); } #endif if (rc) { switch (rc) { - case EAI_MEMORY: - errno = ENOMEM; - break; - default: - errno = EINVAL; - break; + case EAI_MEMORY: + errno = ENOMEM; + break; + default: + errno = EINVAL; + break; } return -1; } // Copy first result to output addr with hostname and service. - zmq_assert ((size_t) res->ai_addrlen <= sizeof (address) ); + zmq_assert ((size_t) res->ai_addrlen <= sizeof (address)); if (is_src_) memcpy (&source_address, res->ai_addr, res->ai_addrlen); else @@ -566,11 +580,10 @@ int zmq::tcp_address_t::resolve_hostname (const char *hostname_, bool ipv6_, boo return 0; } -zmq::tcp_address_t::tcp_address_t () : - _has_src_addr (false) +zmq::tcp_address_t::tcp_address_t () : _has_src_addr (false) { - memset (&address, 0, sizeof (address) ); - memset (&source_address, 0, sizeof (source_address) ); + memset (&address, 0, sizeof (address)); + memset (&source_address, 0, sizeof (source_address)); } zmq::tcp_address_t::tcp_address_t (const sockaddr *sa, socklen_t sa_len) : @@ -578,20 +591,23 @@ zmq::tcp_address_t::tcp_address_t (const sockaddr *sa, socklen_t sa_len) : { zmq_assert (sa && sa_len > 0); - memset (&address, 0, sizeof (address) ); - memset (&source_address, 0, sizeof (source_address) ); - if (sa->sa_family == AF_INET && sa_len >= (socklen_t) sizeof (address.ipv4) ) - memcpy (&address.ipv4, sa, sizeof (address.ipv4) ); - else - if (sa->sa_family == AF_INET6 && sa_len >= (socklen_t) sizeof (address.ipv6) ) - memcpy (&address.ipv6, sa, sizeof (address.ipv6) ); + memset (&address, 0, sizeof (address)); + memset (&source_address, 0, sizeof (source_address)); + if (sa->sa_family == AF_INET && sa_len >= (socklen_t) sizeof (address.ipv4)) + memcpy (&address.ipv4, sa, sizeof (address.ipv4)); + else if (sa->sa_family == AF_INET6 + && sa_len >= (socklen_t) sizeof (address.ipv6)) + memcpy (&address.ipv6, sa, sizeof (address.ipv6)); } zmq::tcp_address_t::~tcp_address_t () { } -int zmq::tcp_address_t::resolve (const char *name_, bool local_, bool ipv6_, bool is_src_) +int zmq::tcp_address_t::resolve (const char *name_, + bool local_, + bool ipv6_, + bool is_src_) { if (!is_src_) { // Test the ';' to know if we have a source address in name_ @@ -618,20 +634,20 @@ int zmq::tcp_address_t::resolve (const char *name_, bool local_, bool ipv6_, boo std::string port_str (delimiter + 1); // Remove square brackets around the address, if any, as used in IPv6 - if (addr_str.size () >= 2 && addr_str [0] == '[' && - addr_str [addr_str.size () - 1] == ']') + if (addr_str.size () >= 2 && addr_str[0] == '[' + && addr_str[addr_str.size () - 1] == ']') addr_str = addr_str.substr (1, addr_str.size () - 2); // Test the '%' to know if we have an interface name / zone_id in the address // Reference: https://tools.ietf.org/html/rfc4007 - std::size_t pos = addr_str.rfind('%'); + std::size_t pos = addr_str.rfind ('%'); uint32_t zone_id = 0; if (pos != std::string::npos) { - std::string if_str = addr_str.substr(pos + 1); - addr_str = addr_str.substr(0, pos); + std::string if_str = addr_str.substr (pos + 1); + addr_str = addr_str.substr (0, pos); if (isalpha (if_str.at (0))) -#if !defined ZMQ_HAVE_WINDOWS_TARGET_XP && !defined ZMQ_HAVE_WINDOWS_UWP - zone_id = if_nametoindex(if_str.c_str()); +#if !defined ZMQ_HAVE_WINDOWS_TARGET_XP && !defined ZMQ_HAVE_WINDOWS_UWP + zone_id = if_nametoindex (if_str.c_str ()); #else // The function 'if_nametoindex' is not supported on Windows XP. // If we are targeting XP using a vxxx_xp toolset then fail. @@ -646,7 +662,6 @@ int zmq::tcp_address_t::resolve (const char *name_, bool local_, bool ipv6_, boo errno = EINVAL; return -1; } - } // Allow 0 specifically, to detect invalid port error in atoi if not @@ -677,16 +692,13 @@ int zmq::tcp_address_t::resolve (const char *name_, bool local_, bool ipv6_, boo if (source_address.generic.sa_family == AF_INET6) { source_address.ipv6.sin6_port = htons (port); source_address.ipv6.sin6_scope_id = zone_id; - } - else + } else source_address.ipv4.sin_port = htons (port); - } - else { + } else { if (address.generic.sa_family == AF_INET6) { address.ipv6.sin6_port = htons (port); address.ipv6.sin6_scope_id = zone_id; - } - else + } else address.ipv4.sin_port = htons (port); } @@ -696,15 +708,16 @@ int zmq::tcp_address_t::resolve (const char *name_, bool local_, bool ipv6_, boo int zmq::tcp_address_t::to_string (std::string &addr_) { if (address.generic.sa_family != AF_INET - && address.generic.sa_family != AF_INET6) { + && address.generic.sa_family != AF_INET6) { addr_.clear (); return -1; } // Not using service resolving because of // https://github.com/zeromq/libzmq/commit/1824574f9b5a8ce786853320e3ea09fe1f822bc4 - char hbuf [NI_MAXHOST]; - int rc = getnameinfo (addr (), addrlen (), hbuf, sizeof (hbuf), NULL, 0, NI_NUMERICHOST); + char hbuf[NI_MAXHOST]; + int rc = getnameinfo (addr (), addrlen (), hbuf, sizeof (hbuf), NULL, 0, + NI_NUMERICHOST); if (rc != 0) { addr_.clear (); return rc; @@ -714,8 +727,7 @@ int zmq::tcp_address_t::to_string (std::string &addr_) std::stringstream s; s << "tcp://[" << hbuf << "]:" << ntohs (address.ipv6.sin6_port); addr_ = s.str (); - } - else { + } else { std::stringstream s; s << "tcp://" << hbuf << ":" << ntohs (address.ipv4.sin_port); addr_ = s.str (); @@ -787,13 +799,11 @@ int zmq::tcp_address_mask_t::resolve (const char *name_, bool ipv6_) errno = EINVAL; return -1; } - } - else + } else addr_str.assign (name_); // Parse address part using standard routines. - const int rc = - tcp_address_t::resolve_hostname (addr_str.c_str (), ipv6_); + const int rc = tcp_address_t::resolve_hostname (addr_str.c_str (), ipv6_); if (rc != 0) return rc; @@ -803,17 +813,12 @@ int zmq::tcp_address_mask_t::resolve (const char *name_, bool ipv6_) address_mask = 128; else address_mask = 32; - } - else - if (mask_str == "0") + } else if (mask_str == "0") address_mask = 0; else { const int mask = atoi (mask_str.c_str ()); - if ( - (mask < 1) || - (address.generic.sa_family == AF_INET6 && mask > 128) || - (address.generic.sa_family != AF_INET6 && mask > 32) - ) { + if ((mask < 1) || (address.generic.sa_family == AF_INET6 && mask > 128) + || (address.generic.sa_family != AF_INET6 && mask > 32)) { errno = EINVAL; return -1; } @@ -826,7 +831,7 @@ int zmq::tcp_address_mask_t::resolve (const char *name_, bool ipv6_) int zmq::tcp_address_mask_t::to_string (std::string &addr_) { if (address.generic.sa_family != AF_INET - && address.generic.sa_family != AF_INET6) { + && address.generic.sa_family != AF_INET6) { addr_.clear (); return -1; } @@ -835,8 +840,9 @@ int zmq::tcp_address_mask_t::to_string (std::string &addr_) return -1; } - char hbuf [NI_MAXHOST]; - int rc = getnameinfo (addr (), addrlen (), hbuf, sizeof (hbuf), NULL, 0, NI_NUMERICHOST); + char hbuf[NI_MAXHOST]; + int rc = getnameinfo (addr (), addrlen (), hbuf, sizeof (hbuf), NULL, 0, + NI_NUMERICHOST); if (rc != 0) { addr_.clear (); return rc; @@ -846,8 +852,7 @@ int zmq::tcp_address_mask_t::to_string (std::string &addr_) std::stringstream s; s << "[" << hbuf << "]/" << address_mask; addr_ = s.str (); - } - else { + } else { std::stringstream s; s << hbuf << "/" << address_mask; addr_ = s.str (); @@ -855,11 +860,11 @@ int zmq::tcp_address_mask_t::to_string (std::string &addr_) return 0; } -bool zmq::tcp_address_mask_t::match_address (const struct sockaddr *ss, const socklen_t ss_len) const +bool zmq::tcp_address_mask_t::match_address (const struct sockaddr *ss, + const socklen_t ss_len) const { - zmq_assert (address_mask != -1 - && ss != NULL - && ss_len >= (socklen_t) sizeof (struct sockaddr)); + zmq_assert (address_mask != -1 && ss != NULL + && ss_len >= (socklen_t) sizeof (struct sockaddr)); if (ss->sa_family != address.generic.sa_family) return false; @@ -869,13 +874,14 @@ bool zmq::tcp_address_mask_t::match_address (const struct sockaddr *ss, const so const uint8_t *our_bytes, *their_bytes; if (ss->sa_family == AF_INET6) { zmq_assert (ss_len == sizeof (struct sockaddr_in6)); - their_bytes = (const uint8_t *) &(((const struct sockaddr_in6 *) ss)->sin6_addr); + their_bytes = (const uint8_t *) &( + ((const struct sockaddr_in6 *) ss)->sin6_addr); our_bytes = (const uint8_t *) &address.ipv6.sin6_addr; mask = sizeof (struct in6_addr) * 8; - } - else { + } else { zmq_assert (ss_len == sizeof (struct sockaddr_in)); - their_bytes = (const uint8_t *) &(((const struct sockaddr_in *) ss)->sin_addr); + their_bytes = + (const uint8_t *) &(((const struct sockaddr_in *) ss)->sin_addr); our_bytes = (const uint8_t *) &address.ipv4.sin_addr; mask = sizeof (struct in_addr) * 8; } @@ -888,7 +894,8 @@ bool zmq::tcp_address_mask_t::match_address (const struct sockaddr *ss, const so const uint8_t last_byte_bits = 0xffU << (8 - mask % 8); if (last_byte_bits) { - if ((their_bytes [full_bytes] & last_byte_bits) != (our_bytes [full_bytes] & last_byte_bits)) + if ((their_bytes[full_bytes] & last_byte_bits) + != (our_bytes[full_bytes] & last_byte_bits)) return false; } } diff --git a/src/tcp_address.hpp b/src/tcp_address.hpp index f853e7443a..8c20a4ceb0 100644 --- a/src/tcp_address.hpp +++ b/src/tcp_address.hpp @@ -37,81 +37,85 @@ namespace zmq { +class tcp_address_t +{ + public: + tcp_address_t (); + tcp_address_t (const sockaddr *sa, socklen_t sa_len); + virtual ~tcp_address_t (); - class tcp_address_t - { - public: - - tcp_address_t (); - tcp_address_t (const sockaddr *sa, socklen_t sa_len); - virtual ~tcp_address_t (); - - // This function translates textual TCP address into an address - // structure. If 'local' is true, names are resolved as local interface - // names. If it is false, names are resolved as remote hostnames. - // If 'ipv6' is true, the name may resolve to IPv6 address. - int resolve (const char *name_, bool local_, bool ipv6_, bool is_src_ = false); + // This function translates textual TCP address into an address + // structure. If 'local' is true, names are resolved as local interface + // names. If it is false, names are resolved as remote hostnames. + // If 'ipv6' is true, the name may resolve to IPv6 address. + int + resolve (const char *name_, bool local_, bool ipv6_, bool is_src_ = false); - // The opposite to resolve() - virtual int to_string (std::string &addr_); + // The opposite to resolve() + virtual int to_string (std::string &addr_); #if defined ZMQ_HAVE_WINDOWS - unsigned short family () const; + unsigned short family () const; #else - sa_family_t family () const; + sa_family_t family () const; #endif - const sockaddr *addr () const; - socklen_t addrlen () const; + const sockaddr *addr () const; + socklen_t addrlen () const; - const sockaddr *src_addr () const; - socklen_t src_addrlen () const; - bool has_src_addr () const; + const sockaddr *src_addr () const; + socklen_t src_addrlen () const; + bool has_src_addr () const; - protected: - int resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_ = false); - int resolve_interface (const char *interface_, bool ipv6_, bool is_src_ = false); - int resolve_hostname (const char *hostname_, bool ipv6_, bool is_src_ = false); + protected: + int resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_ = false); + int resolve_interface (const char *interface_, + bool ipv6_, + bool is_src_ = false); + int + resolve_hostname (const char *hostname_, bool ipv6_, bool is_src_ = false); #if defined ZMQ_HAVE_WINDOWS - int get_interface_name(unsigned long index, char ** dest) const; - int wchar_to_utf8(const WCHAR * src, char ** dest) const; + int get_interface_name (unsigned long index, char **dest) const; + int wchar_to_utf8 (const WCHAR *src, char **dest) const; #endif - union { - sockaddr generic; - sockaddr_in ipv4; - sockaddr_in6 ipv6; - } address; - - union { - sockaddr generic; - sockaddr_in ipv4; - sockaddr_in6 ipv6; - } source_address; - bool _has_src_addr; - }; - - class tcp_address_mask_t : public tcp_address_t + union { - public: - tcp_address_mask_t (); + sockaddr generic; + sockaddr_in ipv4; + sockaddr_in6 ipv6; + } address; - // This function enhances tcp_address_t::resolve() with ability to parse - // additional cidr-like(/xx) mask value at the end of the name string. - // Works only with remote hostnames. - int resolve (const char *name_, bool ipv6_); + union + { + sockaddr generic; + sockaddr_in ipv4; + sockaddr_in6 ipv6; + } source_address; + bool _has_src_addr; +}; + +class tcp_address_mask_t : public tcp_address_t +{ + public: + tcp_address_mask_t (); - // The opposite to resolve() - int to_string (std::string &addr_); + // This function enhances tcp_address_t::resolve() with ability to parse + // additional cidr-like(/xx) mask value at the end of the name string. + // Works only with remote hostnames. + int resolve (const char *name_, bool ipv6_); - int mask () const; + // The opposite to resolve() + int to_string (std::string &addr_); - bool match_address (const struct sockaddr *ss, const socklen_t ss_len) const; + int mask () const; - private: - int address_mask; - }; + bool match_address (const struct sockaddr *ss, + const socklen_t ss_len) const; + private: + int address_mask; +}; } #endif diff --git a/src/tcp_connecter.cpp b/src/tcp_connecter.cpp index 688787353b..4a98a8cb7d 100644 --- a/src/tcp_connecter.cpp +++ b/src/tcp_connecter.cpp @@ -58,13 +58,15 @@ #endif zmq::tcp_connecter_t::tcp_connecter_t (class io_thread_t *io_thread_, - class session_base_t *session_, const options_t &options_, - address_t *addr_, bool delayed_start_) : + class session_base_t *session_, + const options_t &options_, + address_t *addr_, + bool delayed_start_) : own_t (io_thread_, options_), io_object_t (io_thread_), addr (addr_), s (retired_fd), - handle((handle_t)NULL), + handle ((handle_t) NULL), handle_valid (false), delayed_start (delayed_start_), connect_timer_started (false), @@ -145,8 +147,10 @@ void zmq::tcp_connecter_t::out_event () } int rc = tune_tcp_socket (fd); - rc = rc | tune_tcp_keepalives (fd, options.tcp_keepalive, options.tcp_keepalive_cnt, - options.tcp_keepalive_idle, options.tcp_keepalive_intvl); + rc = rc + | tune_tcp_keepalives ( + fd, options.tcp_keepalive, options.tcp_keepalive_cnt, + options.tcp_keepalive_idle, options.tcp_keepalive_intvl); rc = rc | tune_tcp_maxrt (fd, options.tcp_maxrt); if (rc != 0) { close (); @@ -155,8 +159,8 @@ void zmq::tcp_connecter_t::out_event () } // Create the engine object for this connection. - stream_engine_t *engine = new (std::nothrow) - stream_engine_t (fd, options, endpoint); + stream_engine_t *engine = + new (std::nothrow) stream_engine_t (fd, options, endpoint); alloc_assert (engine); // Attach the engine to the corresponding session object. @@ -179,8 +183,7 @@ void zmq::tcp_connecter_t::timer_event (int id_) close (); add_reconnect_timer (); - } - else if (id_ == reconnect_timer_id) { + } else if (id_ == reconnect_timer_id) { reconnect_timer_started = false; start_connecting (); } @@ -199,12 +202,11 @@ void zmq::tcp_connecter_t::start_connecting () } // Connection establishment may be delayed. Poll for its completion. - else - if (rc == -1 && errno == EINPROGRESS) { + else if (rc == -1 && errno == EINPROGRESS) { handle = add_fd (s); handle_valid = true; set_pollout (handle); - socket->event_connect_delayed (endpoint, zmq_errno()); + socket->event_connect_delayed (endpoint, zmq_errno ()); // add userspace connect timeout add_connect_timer (); @@ -237,16 +239,16 @@ void zmq::tcp_connecter_t::add_reconnect_timer () int zmq::tcp_connecter_t::get_new_reconnect_ivl () { // The new interval is the current interval + random value. - const int interval = current_reconnect_ivl + - generate_random () % options.reconnect_ivl; + const int interval = + current_reconnect_ivl + generate_random () % options.reconnect_ivl; // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. - if (options.reconnect_ivl_max > 0 && - options.reconnect_ivl_max > options.reconnect_ivl) + if (options.reconnect_ivl_max > 0 + && options.reconnect_ivl_max > options.reconnect_ivl) // Calculate the next interval current_reconnect_ivl = - std::min (current_reconnect_ivl * 2, options.reconnect_ivl_max); + std::min (current_reconnect_ivl * 2, options.reconnect_ivl_max); return interval; } @@ -256,31 +258,30 @@ int zmq::tcp_connecter_t::open () // Resolve the address if (addr->resolved.tcp_addr != NULL) { - LIBZMQ_DELETE(addr->resolved.tcp_addr); + LIBZMQ_DELETE (addr->resolved.tcp_addr); } addr->resolved.tcp_addr = new (std::nothrow) tcp_address_t (); alloc_assert (addr->resolved.tcp_addr); - int rc = addr->resolved.tcp_addr->resolve ( - addr->address.c_str (), false, options.ipv6); + int rc = addr->resolved.tcp_addr->resolve (addr->address.c_str (), false, + options.ipv6); if (rc != 0) { - LIBZMQ_DELETE(addr->resolved.tcp_addr); + LIBZMQ_DELETE (addr->resolved.tcp_addr); return -1; } zmq_assert (addr->resolved.tcp_addr != NULL); - tcp_address_t * const tcp_addr = addr->resolved.tcp_addr; + tcp_address_t *const tcp_addr = addr->resolved.tcp_addr; // Create the socket. s = open_socket (tcp_addr->family (), SOCK_STREAM, IPPROTO_TCP); // IPv6 address family not supported, try automatic downgrade to IPv4. if (s == zmq::retired_fd && tcp_addr->family () == AF_INET6 - && errno == EAFNOSUPPORT - && options.ipv6) { - rc = addr->resolved.tcp_addr->resolve ( - addr->address.c_str (), false, false); + && errno == EAFNOSUPPORT && options.ipv6) { + rc = addr->resolved.tcp_addr->resolve (addr->address.c_str (), false, + false); if (rc != 0) { - LIBZMQ_DELETE(addr->resolved.tcp_addr); + LIBZMQ_DELETE (addr->resolved.tcp_addr); return -1; } s = open_socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); @@ -328,8 +329,8 @@ int zmq::tcp_connecter_t::open () // using the same source port on the client. int flag = 1; #ifdef ZMQ_HAVE_WINDOWS - rc = setsockopt (s, SOL_SOCKET, SO_REUSEADDR, (const char*) &flag, - sizeof (int)); + rc = setsockopt (s, SOL_SOCKET, SO_REUSEADDR, (const char *) &flag, + sizeof (int)); wsa_assert (rc != SOCKET_ERROR); #else rc = setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int)); @@ -348,10 +349,10 @@ int zmq::tcp_connecter_t::open () if (rc == 0) return 0; - // Translate error codes indicating asynchronous connect has been - // launched to a uniform EINPROGRESS. + // Translate error codes indicating asynchronous connect has been + // launched to a uniform EINPROGRESS. #ifdef ZMQ_HAVE_WINDOWS - const int last_error = WSAGetLastError(); + const int last_error = WSAGetLastError (); if (last_error == WSAEINPROGRESS || last_error == WSAEWOULDBLOCK) errno = EINPROGRESS; else @@ -373,18 +374,15 @@ zmq::fd_t zmq::tcp_connecter_t::connect () socklen_t len = sizeof err; #endif - const int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char*) &err, &len); + const int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char *) &err, &len); // Assert if the error was caused by 0MQ bug. // Networking problems are OK. No need to assert. #ifdef ZMQ_HAVE_WINDOWS zmq_assert (rc == 0); if (err != 0) { - if (err == WSAEBADF || - err == WSAENOPROTOOPT || - err == WSAENOTSOCK || - err == WSAENOBUFS) - { + if (err == WSAEBADF || err == WSAENOPROTOOPT || err == WSAENOTSOCK + || err == WSAENOBUFS) { wsa_assert_no (err); } return retired_fd; @@ -396,11 +394,8 @@ zmq::fd_t zmq::tcp_connecter_t::connect () err = errno; if (err != 0) { errno = err; - errno_assert ( - errno != EBADF && - errno != ENOPROTOOPT && - errno != ENOTSOCK && - errno != ENOBUFS); + errno_assert (errno != EBADF && errno != ENOPROTOOPT + && errno != ENOTSOCK && errno != ENOBUFS); return retired_fd; } #endif diff --git a/src/tcp_connecter.hpp b/src/tcp_connecter.hpp index c4fe7d7cea..a65272eecc 100644 --- a/src/tcp_connecter.hpp +++ b/src/tcp_connecter.hpp @@ -37,98 +37,100 @@ namespace zmq { +class io_thread_t; +class session_base_t; +struct address_t; - class io_thread_t; - class session_base_t; - struct address_t; - - class tcp_connecter_t : public own_t, public io_object_t +class tcp_connecter_t : public own_t, public io_object_t +{ + public: + // If 'delayed_start' is true connecter first waits for a while, + // then starts connection process. + tcp_connecter_t (zmq::io_thread_t *io_thread_, + zmq::session_base_t *session_, + const options_t &options_, + address_t *addr_, + bool delayed_start_); + ~tcp_connecter_t (); + + private: + // ID of the timer used to delay the reconnection. + enum { - public: - - // If 'delayed_start' is true connecter first waits for a while, - // then starts connection process. - tcp_connecter_t (zmq::io_thread_t *io_thread_, - zmq::session_base_t *session_, const options_t &options_, - address_t *addr_, bool delayed_start_); - ~tcp_connecter_t (); - - private: - - // ID of the timer used to delay the reconnection. - enum {reconnect_timer_id = 1, connect_timer_id}; - - // Handlers for incoming commands. - void process_plug (); - void process_term (int linger_); + reconnect_timer_id = 1, + connect_timer_id + }; - // Handlers for I/O events. - void in_event (); - void out_event (); - void timer_event (int id_); + // Handlers for incoming commands. + void process_plug (); + void process_term (int linger_); - // Internal function to start the actual connection establishment. - void start_connecting (); + // Handlers for I/O events. + void in_event (); + void out_event (); + void timer_event (int id_); - // Internal function to add a connect timer - void add_connect_timer(); + // Internal function to start the actual connection establishment. + void start_connecting (); - // Internal function to add a reconnect timer - void add_reconnect_timer(); + // Internal function to add a connect timer + void add_connect_timer (); - // Internal function to return a reconnect backoff delay. - // Will modify the current_reconnect_ivl used for next call - // Returns the currently used interval - int get_new_reconnect_ivl (); + // Internal function to add a reconnect timer + void add_reconnect_timer (); - // Open TCP connecting socket. Returns -1 in case of error, - // 0 if connect was successful immediately. Returns -1 with - // EAGAIN errno if async connect was launched. - int open (); + // Internal function to return a reconnect backoff delay. + // Will modify the current_reconnect_ivl used for next call + // Returns the currently used interval + int get_new_reconnect_ivl (); - // Close the connecting socket. - void close (); + // Open TCP connecting socket. Returns -1 in case of error, + // 0 if connect was successful immediately. Returns -1 with + // EAGAIN errno if async connect was launched. + int open (); - // Get the file descriptor of newly created connection. Returns - // retired_fd if the connection was unsuccessful. - fd_t connect (); + // Close the connecting socket. + void close (); - // Address to connect to. Owned by session_base_t. - address_t *addr; + // Get the file descriptor of newly created connection. Returns + // retired_fd if the connection was unsuccessful. + fd_t connect (); - // Underlying socket. - fd_t s; + // Address to connect to. Owned by session_base_t. + address_t *addr; - // Handle corresponding to the listening socket. - handle_t handle; + // Underlying socket. + fd_t s; - // If true file descriptor is registered with the poller and 'handle' - // contains valid value. - bool handle_valid; + // Handle corresponding to the listening socket. + handle_t handle; - // If true, connecter is waiting a while before trying to connect. - const bool delayed_start; + // If true file descriptor is registered with the poller and 'handle' + // contains valid value. + bool handle_valid; - // True iff a timer has been started. - bool connect_timer_started; - bool reconnect_timer_started; + // If true, connecter is waiting a while before trying to connect. + const bool delayed_start; - // Reference to the session we belong to. - zmq::session_base_t *session; + // True iff a timer has been started. + bool connect_timer_started; + bool reconnect_timer_started; - // Current reconnect ivl, updated for backoff strategy - int current_reconnect_ivl; + // Reference to the session we belong to. + zmq::session_base_t *session; - // String representation of endpoint to connect to - std::string endpoint; + // Current reconnect ivl, updated for backoff strategy + int current_reconnect_ivl; - // Socket - zmq::socket_base_t *socket; + // String representation of endpoint to connect to + std::string endpoint; - tcp_connecter_t (const tcp_connecter_t&); - const tcp_connecter_t &operator = (const tcp_connecter_t&); - }; + // Socket + zmq::socket_base_t *socket; + tcp_connecter_t (const tcp_connecter_t &); + const tcp_connecter_t &operator= (const tcp_connecter_t &); +}; } #endif diff --git a/src/tcp_listener.cpp b/src/tcp_listener.cpp index 7b929d4298..cbddc724df 100644 --- a/src/tcp_listener.cpp +++ b/src/tcp_listener.cpp @@ -58,11 +58,12 @@ #endif zmq::tcp_listener_t::tcp_listener_t (io_thread_t *io_thread_, - socket_base_t *socket_, const options_t &options_) : + socket_base_t *socket_, + const options_t &options_) : own_t (io_thread_, options_), io_object_t (io_thread_), s (retired_fd), - handle((handle_t)NULL), + handle ((handle_t) NULL), socket (socket_) { } @@ -93,22 +94,24 @@ void zmq::tcp_listener_t::in_event () // If connection was reset by the peer in the meantime, just ignore it. // TODO: Handle specific errors like ENFILE/EMFILE etc. if (fd == retired_fd) { - socket->event_accept_failed (endpoint, zmq_errno()); + socket->event_accept_failed (endpoint, zmq_errno ()); return; } int rc = tune_tcp_socket (fd); - rc = rc | tune_tcp_keepalives (fd, options.tcp_keepalive, options.tcp_keepalive_cnt, - options.tcp_keepalive_idle, options.tcp_keepalive_intvl); + rc = rc + | tune_tcp_keepalives ( + fd, options.tcp_keepalive, options.tcp_keepalive_cnt, + options.tcp_keepalive_idle, options.tcp_keepalive_intvl); rc = rc | tune_tcp_maxrt (fd, options.tcp_maxrt); if (rc != 0) { - socket->event_accept_failed (endpoint, zmq_errno()); + socket->event_accept_failed (endpoint, zmq_errno ()); return; } // Create the engine object for this connection. - stream_engine_t *engine = new (std::nothrow) - stream_engine_t (fd, options, endpoint); + stream_engine_t *engine = + new (std::nothrow) stream_engine_t (fd, options, endpoint); alloc_assert (engine); // Choose I/O thread to run connecter in. Given that we are already @@ -117,8 +120,8 @@ void zmq::tcp_listener_t::in_event () zmq_assert (io_thread); // Create and launch a session object. - session_base_t *session = session_base_t::create (io_thread, false, socket, - options, NULL); + session_base_t *session = + session_base_t::create (io_thread, false, socket, options, NULL); errno_assert (session); session->inc_seqnum (); launch_child (session); @@ -180,8 +183,7 @@ int zmq::tcp_listener_t::set_address (const char *addr_) // IPv6 address family not supported, try automatic downgrade to IPv4. if (s == zmq::retired_fd && address.family () == AF_INET6 - && errno == EAFNOSUPPORT - && options.ipv6) { + && errno == EAFNOSUPPORT && options.ipv6) { rc = address.resolve (addr_, true, false); if (rc != 0) return rc; @@ -225,8 +227,8 @@ int zmq::tcp_listener_t::set_address (const char *addr_) // Allow reusing of the address. int flag = 1; #ifdef ZMQ_HAVE_WINDOWS - rc = setsockopt (s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, - (const char*) &flag, sizeof (int)); + rc = setsockopt (s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char *) &flag, + sizeof (int)); wsa_assert (rc != SOCKET_ERROR); #else rc = setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int)); @@ -289,11 +291,9 @@ zmq::fd_t zmq::tcp_listener_t::accept () #ifdef ZMQ_HAVE_WINDOWS if (sock == INVALID_SOCKET) { - const int last_error = WSAGetLastError(); - wsa_assert (last_error == WSAEWOULDBLOCK || - last_error == WSAECONNRESET || - last_error == WSAEMFILE || - last_error == WSAENOBUFS); + const int last_error = WSAGetLastError (); + wsa_assert (last_error == WSAEWOULDBLOCK || last_error == WSAECONNRESET + || last_error == WSAEMFILE || last_error == WSAENOBUFS); return retired_fd; } #if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP @@ -303,15 +303,16 @@ zmq::fd_t zmq::tcp_listener_t::accept () #endif #else if (sock == -1) { - errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || - errno == EINTR || errno == ECONNABORTED || errno == EPROTO || - errno == ENOBUFS || errno == ENOMEM || errno == EMFILE || - errno == ENFILE); + errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR + || errno == ECONNABORTED || errno == EPROTO + || errno == ENOBUFS || errno == ENOMEM || errno == EMFILE + || errno == ENFILE); return retired_fd; } #endif -#if (!defined ZMQ_HAVE_SOCK_CLOEXEC || !defined HAVE_ACCEPT4) && defined FD_CLOEXEC +#if (!defined ZMQ_HAVE_SOCK_CLOEXEC || !defined HAVE_ACCEPT4) \ + && defined FD_CLOEXEC // Race condition can cause socket not to be closed (if fork happens // between accept and this point). int rc = fcntl (sock, F_SETFD, FD_CLOEXEC); @@ -320,8 +321,10 @@ zmq::fd_t zmq::tcp_listener_t::accept () if (!options.tcp_accept_filters.empty ()) { bool matched = false; - for (options_t::tcp_accept_filters_t::size_type i = 0; i != options.tcp_accept_filters.size (); ++i) { - if (options.tcp_accept_filters[i].match_address ((struct sockaddr *) &ss, ss_len)) { + for (options_t::tcp_accept_filters_t::size_type i = 0; + i != options.tcp_accept_filters.size (); ++i) { + if (options.tcp_accept_filters[i].match_address ( + (struct sockaddr *) &ss, ss_len)) { matched = true; break; } diff --git a/src/tcp_listener.hpp b/src/tcp_listener.hpp index 2b3ccff7e2..d82848bfad 100644 --- a/src/tcp_listener.hpp +++ b/src/tcp_listener.hpp @@ -38,61 +38,58 @@ namespace zmq { +class io_thread_t; +class socket_base_t; - class io_thread_t; - class socket_base_t; - - class tcp_listener_t : public own_t, public io_object_t - { - public: - - tcp_listener_t (zmq::io_thread_t *io_thread_, - zmq::socket_base_t *socket_, const options_t &options_); - ~tcp_listener_t (); - - // Set address to listen on. - int set_address (const char *addr_); - - // Get the bound address for use with wildcard - int get_address (std::string &addr_); +class tcp_listener_t : public own_t, public io_object_t +{ + public: + tcp_listener_t (zmq::io_thread_t *io_thread_, + zmq::socket_base_t *socket_, + const options_t &options_); + ~tcp_listener_t (); - private: + // Set address to listen on. + int set_address (const char *addr_); - // Handlers for incoming commands. - void process_plug (); - void process_term (int linger_); + // Get the bound address for use with wildcard + int get_address (std::string &addr_); - // Handlers for I/O events. - void in_event (); + private: + // Handlers for incoming commands. + void process_plug (); + void process_term (int linger_); - // Close the listening socket. - void close (); + // Handlers for I/O events. + void in_event (); - // Accept the new connection. Returns the file descriptor of the - // newly created connection. The function may return retired_fd - // if the connection was dropped while waiting in the listen backlog - // or was denied because of accept filters. - fd_t accept (); + // Close the listening socket. + void close (); - // Address to listen on. - tcp_address_t address; + // Accept the new connection. Returns the file descriptor of the + // newly created connection. The function may return retired_fd + // if the connection was dropped while waiting in the listen backlog + // or was denied because of accept filters. + fd_t accept (); - // Underlying socket. - fd_t s; + // Address to listen on. + tcp_address_t address; - // Handle corresponding to the listening socket. - handle_t handle; + // Underlying socket. + fd_t s; - // Socket the listener belongs to. - zmq::socket_base_t *socket; + // Handle corresponding to the listening socket. + handle_t handle; - // String representation of endpoint to bind to - std::string endpoint; + // Socket the listener belongs to. + zmq::socket_base_t *socket; - tcp_listener_t (const tcp_listener_t&); - const tcp_listener_t &operator = (const tcp_listener_t&); - }; + // String representation of endpoint to bind to + std::string endpoint; + tcp_listener_t (const tcp_listener_t &); + const tcp_listener_t &operator= (const tcp_listener_t &); +}; } #endif diff --git a/src/thread.cpp b/src/thread.cpp index 4fc59c3ebe..6588104263 100644 --- a/src/thread.cpp +++ b/src/thread.cpp @@ -34,18 +34,17 @@ #ifdef ZMQ_HAVE_WINDOWS -extern "C" -{ +extern "C" { #if defined _WIN32_WCE - static DWORD thread_routine (LPVOID arg_) +static DWORD thread_routine (LPVOID arg_) #else - static unsigned int __stdcall thread_routine (void *arg_) +static unsigned int __stdcall thread_routine (void *arg_) #endif - { - zmq::thread_t *self = (zmq::thread_t*) arg_; - self->tfn (self->arg); - return 0; - } +{ + zmq::thread_t *self = (zmq::thread_t *) arg_; + self->tfn (self->arg); + return 0; +} } void zmq::thread_t::start (thread_fn *tfn_, void *arg_) @@ -53,11 +52,11 @@ void zmq::thread_t::start (thread_fn *tfn_, void *arg_) tfn = tfn_; arg = arg_; #if defined _WIN32_WCE - descriptor = (HANDLE) CreateThread (NULL, 0, - &::thread_routine, this, 0 , NULL); + descriptor = + (HANDLE) CreateThread (NULL, 0, &::thread_routine, this, 0, NULL); #else - descriptor = (HANDLE) _beginthreadex (NULL, 0, - &::thread_routine, this, 0 , NULL); + descriptor = + (HANDLE) _beginthreadex (NULL, 0, &::thread_routine, this, 0, NULL); #endif win_assert (descriptor != NULL); } @@ -70,7 +69,8 @@ void zmq::thread_t::stop () win_assert (rc2 != 0); } -void zmq::thread_t::setSchedulingParameters(int priority_, int schedulingPolicy_, const std::set& affinity_cpus_) +void zmq::thread_t::setSchedulingParameters ( + int priority_, int schedulingPolicy_, const std::set &affinity_cpus_) { // not implemented LIBZMQ_UNUSED (priority_); @@ -78,7 +78,7 @@ void zmq::thread_t::setSchedulingParameters(int priority_, int schedulingPolicy_ LIBZMQ_UNUSED (affinity_cpus_); } -void zmq::thread_t::setThreadName(const char *name_) +void zmq::thread_t::setThreadName (const char *name_) { // not implemented LIBZMQ_UNUSED (name_); @@ -91,24 +91,23 @@ void zmq::thread_t::setThreadName(const char *name_) #include #include -extern "C" +extern "C" { +static void *thread_routine (void *arg_) { - static void *thread_routine (void *arg_) - { #if !defined ZMQ_HAVE_OPENVMS && !defined ZMQ_HAVE_ANDROID - // Following code will guarantee more predictable latencies as it'll - // disallow any signal handling in the I/O thread. - sigset_t signal_set; - int rc = sigfillset (&signal_set); - errno_assert (rc == 0); - rc = pthread_sigmask (SIG_BLOCK, &signal_set, NULL); - posix_assert (rc); + // Following code will guarantee more predictable latencies as it'll + // disallow any signal handling in the I/O thread. + sigset_t signal_set; + int rc = sigfillset (&signal_set); + errno_assert (rc == 0); + rc = pthread_sigmask (SIG_BLOCK, &signal_set, NULL); + posix_assert (rc); #endif - zmq::thread_t *self = (zmq::thread_t*) arg_; - self->applySchedulingParameters(); - self->tfn (self->arg); - return NULL; - } + zmq::thread_t *self = (zmq::thread_t *) arg_; + self->applySchedulingParameters (); + self->tfn (self->arg); + return NULL; +} } void zmq::thread_t::start (thread_fn *tfn_, void *arg_) @@ -125,29 +124,32 @@ void zmq::thread_t::stop () posix_assert (rc); } -void zmq::thread_t::setSchedulingParameters(int priority_, int schedulingPolicy_, const std::set& affinity_cpus_) +void zmq::thread_t::setSchedulingParameters ( + int priority_, int schedulingPolicy_, const std::set &affinity_cpus_) { - thread_priority=priority_; - thread_sched_policy=schedulingPolicy_; - thread_affinity_cpus=affinity_cpus_; + thread_priority = priority_; + thread_sched_policy = schedulingPolicy_; + thread_affinity_cpus = affinity_cpus_; } -void zmq::thread_t::applySchedulingParameters() // to be called in secondary thread context +void zmq::thread_t:: + applySchedulingParameters () // to be called in secondary thread context { -#if defined _POSIX_THREAD_PRIORITY_SCHEDULING && _POSIX_THREAD_PRIORITY_SCHEDULING >= 0 +#if defined _POSIX_THREAD_PRIORITY_SCHEDULING \ + && _POSIX_THREAD_PRIORITY_SCHEDULING >= 0 int policy = 0; struct sched_param param; -#if _POSIX_THREAD_PRIORITY_SCHEDULING == 0 && defined _SC_THREAD_PRIORITY_SCHEDULING - if (sysconf(_SC_THREAD_PRIORITY_SCHEDULING) < 0) { +#if _POSIX_THREAD_PRIORITY_SCHEDULING == 0 \ + && defined _SC_THREAD_PRIORITY_SCHEDULING + if (sysconf (_SC_THREAD_PRIORITY_SCHEDULING) < 0) { return; } #endif - int rc = pthread_getschedparam(descriptor, &policy, ¶m); + int rc = pthread_getschedparam (descriptor, &policy, ¶m); posix_assert (rc); - if(thread_sched_policy != ZMQ_THREAD_SCHED_POLICY_DFLT) - { + if (thread_sched_policy != ZMQ_THREAD_SCHED_POLICY_DFLT) { policy = thread_sched_policy; } @@ -156,62 +158,64 @@ void zmq::thread_t::applySchedulingParameters() // to be called in secon SCHED_RR policies, and the priority 0 for the remaining policies." Other policies may use the "nice value" in place of the priority: */ - bool use_nice_instead_priority = (policy != SCHED_FIFO) && (policy != SCHED_RR); + bool use_nice_instead_priority = + (policy != SCHED_FIFO) && (policy != SCHED_RR); - if(thread_priority != ZMQ_THREAD_PRIORITY_DFLT) - { + if (thread_priority != ZMQ_THREAD_PRIORITY_DFLT) { if (use_nice_instead_priority) - param.sched_priority = 0; // this is the only supported priority for most scheduling policies + param.sched_priority = + 0; // this is the only supported priority for most scheduling policies else - param.sched_priority = thread_priority; // user should provide a value between 1 and 99 + param.sched_priority = + thread_priority; // user should provide a value between 1 and 99 } #ifdef __NetBSD__ - if(policy == SCHED_OTHER) param.sched_priority = -1; + if (policy == SCHED_OTHER) + param.sched_priority = -1; #endif - rc = pthread_setschedparam(descriptor, policy, ¶m); + rc = pthread_setschedparam (descriptor, policy, ¶m); -#if defined(__FreeBSD_kernel__) || defined (__FreeBSD__) +#if defined(__FreeBSD_kernel__) || defined(__FreeBSD__) // If this feature is unavailable at run-time, don't abort. - if(rc == ENOSYS) return; + if (rc == ENOSYS) + return; #endif posix_assert (rc); - if (use_nice_instead_priority && - thread_priority != ZMQ_THREAD_PRIORITY_DFLT) - { + if (use_nice_instead_priority + && thread_priority != ZMQ_THREAD_PRIORITY_DFLT) { // assume the user wants to decrease the thread's nice value // i.e., increase the chance of this thread being scheduled: try setting that to // maximum priority. - rc = nice(-20); + rc = nice (-20); errno_assert (rc != -1); // IMPORTANT: EPERM is typically returned for unprivileged processes: that's because // CAP_SYS_NICE capability is required or RLIMIT_NICE resource limit should be changed to avoid EPERM! - } #ifdef ZMQ_HAVE_PTHREAD_SET_AFFINITY - if (!thread_affinity_cpus.empty()) - { + if (!thread_affinity_cpus.empty ()) { cpu_set_t cpuset; - CPU_ZERO(&cpuset); - for (std::set::const_iterator it = thread_affinity_cpus.begin(); it != thread_affinity_cpus.end(); it++) - { - CPU_SET( (int)(*it) , &cpuset ); + CPU_ZERO (&cpuset); + for (std::set::const_iterator it = thread_affinity_cpus.begin (); + it != thread_affinity_cpus.end (); it++) { + CPU_SET ((int) (*it), &cpuset); } - rc = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset); + rc = + pthread_setaffinity_np (pthread_self (), sizeof (cpu_set_t), &cpuset); posix_assert (rc); } #endif #endif } -void zmq::thread_t::setThreadName(const char *name_) +void zmq::thread_t::setThreadName (const char *name_) { -/* The thread name is a cosmetic string, added to ease debugging of + /* The thread name is a cosmetic string, added to ease debugging of * multi-threaded applications. It is not a big issue if this value * can not be set for any reason (such as Permission denied in some * cases where the application changes its EUID, etc.) The value of @@ -222,16 +226,19 @@ void zmq::thread_t::setThreadName(const char *name_) return; #if defined(ZMQ_HAVE_PTHREAD_SETNAME_1) - int rc = pthread_setname_np(name_); - if(rc) return; + int rc = pthread_setname_np (name_); + if (rc) + return; #elif defined(ZMQ_HAVE_PTHREAD_SETNAME_2) - int rc = pthread_setname_np(descriptor, name_); - if(rc) return; + int rc = pthread_setname_np (descriptor, name_); + if (rc) + return; #elif defined(ZMQ_HAVE_PTHREAD_SETNAME_3) - int rc = pthread_setname_np(descriptor, name_, NULL); - if(rc) return; + int rc = pthread_setname_np (descriptor, name_, NULL); + if (rc) + return; #elif defined(ZMQ_HAVE_PTHREAD_SET_NAME) - pthread_set_name_np(descriptor, name_); + pthread_set_name_np (descriptor, name_); #endif } diff --git a/src/thread.hpp b/src/thread.hpp index 150b31d16d..8d7329ab09 100644 --- a/src/thread.hpp +++ b/src/thread.hpp @@ -37,66 +37,64 @@ namespace zmq { +typedef void(thread_fn) (void *); - typedef void (thread_fn) (void*); +// Class encapsulating OS thread. Thread initiation/termination is done +// using special functions rather than in constructor/destructor so that +// thread isn't created during object construction by accident, causing +// newly created thread to access half-initialised object. Same applies +// to the destruction process: Thread should be terminated before object +// destruction begins, otherwise it can access half-destructed object. - // Class encapsulating OS thread. Thread initiation/termination is done - // using special functions rather than in constructor/destructor so that - // thread isn't created during object construction by accident, causing - // newly created thread to access half-initialised object. Same applies - // to the destruction process: Thread should be terminated before object - // destruction begins, otherwise it can access half-destructed object. - - class thread_t +class thread_t +{ + public: + inline thread_t () : + tfn (NULL), + arg (NULL), + thread_priority (ZMQ_THREAD_PRIORITY_DFLT), + thread_sched_policy (ZMQ_THREAD_SCHED_POLICY_DFLT) { - public: - - inline thread_t () - : tfn(NULL) - , arg(NULL) - , thread_priority(ZMQ_THREAD_PRIORITY_DFLT) - , thread_sched_policy(ZMQ_THREAD_SCHED_POLICY_DFLT) - { - } + } - // Creates OS thread. 'tfn' is main thread function. It'll be passed - // 'arg' as an argument. - void start (thread_fn *tfn_, void *arg_); + // Creates OS thread. 'tfn' is main thread function. It'll be passed + // 'arg' as an argument. + void start (thread_fn *tfn_, void *arg_); - // Waits for thread termination. - void stop (); + // Waits for thread termination. + void stop (); - // Sets the thread scheduling parameters. Only implemented for - // pthread. Has no effect on other platforms. - void setSchedulingParameters(int priority_, int schedulingPolicy_, const std::set& affinity_cpus_); + // Sets the thread scheduling parameters. Only implemented for + // pthread. Has no effect on other platforms. + void setSchedulingParameters (int priority_, + int schedulingPolicy_, + const std::set &affinity_cpus_); - // Sets the thread name, 16 characters max including terminating NUL. - // Only implemented for pthread. Has no effect on other platforms. - void setThreadName(const char *name_); + // Sets the thread name, 16 characters max including terminating NUL. + // Only implemented for pthread. Has no effect on other platforms. + void setThreadName (const char *name_); - // These are internal members. They should be private, however then - // they would not be accessible from the main C routine of the thread. - void applySchedulingParameters(); - thread_fn *tfn; - void *arg; - - private: + // These are internal members. They should be private, however then + // they would not be accessible from the main C routine of the thread. + void applySchedulingParameters (); + thread_fn *tfn; + void *arg; + private: #ifdef ZMQ_HAVE_WINDOWS - HANDLE descriptor; + HANDLE descriptor; #else - pthread_t descriptor; + pthread_t descriptor; #endif - // Thread scheduling parameters. - int thread_priority; - int thread_sched_policy; - std::set thread_affinity_cpus; - - thread_t (const thread_t&); - const thread_t &operator = (const thread_t&); - }; + // Thread scheduling parameters. + int thread_priority; + int thread_sched_policy; + std::set thread_affinity_cpus; + thread_t (const thread_t &); + const thread_t &operator= (const thread_t &); +}; } #endif diff --git a/src/timers.hpp b/src/timers.hpp index b7c5ce655c..e1bc32d49d 100644 --- a/src/timers.hpp +++ b/src/timers.hpp @@ -38,73 +38,72 @@ along with this program. If not, see . namespace zmq { - typedef void (timers_timer_fn)( - int timer_id, void *arg); +typedef void(timers_timer_fn) (int timer_id, void *arg); - class timers_t - { - public: - timers_t (); - ~timers_t (); - - // Add timer to the set, timer repeats forever, or until cancel is called. - // Returns a timer_id that is used to cancel the timer. - // Returns -1 if there was an error. - int add (size_t interval, timers_timer_fn handler, void* arg); +class timers_t +{ + public: + timers_t (); + ~timers_t (); - // Set the interval of the timer. - // This method is slow, cancelling exsting and adding a new timer yield better performance. - // Returns 0 on success and -1 on error. - int set_interval (int timer_id, size_t interval); + // Add timer to the set, timer repeats forever, or until cancel is called. + // Returns a timer_id that is used to cancel the timer. + // Returns -1 if there was an error. + int add (size_t interval, timers_timer_fn handler, void *arg); - // Reset the timer. - // This method is slow, cancelling exsting and adding a new timer yield better performance. - // Returns 0 on success and -1 on error. - int reset (int timer_id); + // Set the interval of the timer. + // This method is slow, cancelling exsting and adding a new timer yield better performance. + // Returns 0 on success and -1 on error. + int set_interval (int timer_id, size_t interval); - // Cancel a timer. - // Returns 0 on success and -1 on error. - int cancel (int timer_id); + // Reset the timer. + // This method is slow, cancelling exsting and adding a new timer yield better performance. + // Returns 0 on success and -1 on error. + int reset (int timer_id); - // Returns the time in millisecond until the next timer. - // Returns -1 if no timer is due. - long timeout (); + // Cancel a timer. + // Returns 0 on success and -1 on error. + int cancel (int timer_id); - // Execute timers. - // Return 0 if all succeed and -1 if error. - int execute (); + // Returns the time in millisecond until the next timer. + // Returns -1 if no timer is due. + long timeout (); - // Return false if object is not a timers class. - bool check_tag (); + // Execute timers. + // Return 0 if all succeed and -1 if error. + int execute (); - private: + // Return false if object is not a timers class. + bool check_tag (); - // Used to check whether the object is a timers class. - uint32_t tag; + private: + // Used to check whether the object is a timers class. + uint32_t tag; - int next_timer_id; + int next_timer_id; - // Clock instance. - clock_t clock; + // Clock instance. + clock_t clock; - typedef struct timer_t { - int timer_id; - size_t interval; - timers_timer_fn *handler; - void *arg; - } timer_t; + typedef struct timer_t + { + int timer_id; + size_t interval; + timers_timer_fn *handler; + void *arg; + } timer_t; - typedef std::multimap timersmap_t; - timersmap_t timers; + typedef std::multimap timersmap_t; + timersmap_t timers; - typedef std::set cancelled_timers_t; - cancelled_timers_t cancelled_timers; + typedef std::set cancelled_timers_t; + cancelled_timers_t cancelled_timers; - timers_t (const timers_t&); - const timers_t &operator = (const timers_t&); + timers_t (const timers_t &); + const timers_t &operator= (const timers_t &); - struct match_by_id; - }; - } + struct match_by_id; +}; +} - #endif +#endif diff --git a/src/tipc_address.cpp b/src/tipc_address.cpp index 8bbe10e5fa..44020b2967 100644 --- a/src/tipc_address.cpp +++ b/src/tipc_address.cpp @@ -67,14 +67,13 @@ int zmq::tipc_address_t::resolve (const char *name) const int res = sscanf (name, "{%u,%u,%u}", &type, &lower, &upper); /* Fetch optional domain suffix. */ - if ((domain = strchr(name, '@'))) { - if (sscanf(domain, "@%u.%u.%u%c", &z, &c, &n, &eof) != 3) + if ((domain = strchr (name, '@'))) { + if (sscanf (domain, "@%u.%u.%u%c", &z, &c, &n, &eof) != 3) return EINVAL; } if (res == 3) goto nameseq; - else - if (res == 2 && type > TIPC_RESERVED_TYPES) { + else if (res == 2 && type > TIPC_RESERVED_TYPES) { address.family = AF_TIPC; address.addrtype = TIPC_ADDR_NAME; address.addr.name.name.type = type; @@ -82,8 +81,7 @@ int zmq::tipc_address_t::resolve (const char *name) address.addr.name.domain = tipc_addr (z, c, n); address.scope = 0; return 0; - } - else + } else return EINVAL; nameseq: if (type < TIPC_RESERVED_TYPES || upper < lower) @@ -104,7 +102,8 @@ int zmq::tipc_address_t::to_string (std::string &addr_) return -1; } std::stringstream s; - s << "tipc://" << "{" << address.addr.nameseq.type; + s << "tipc://" + << "{" << address.addr.nameseq.type; s << ", " << address.addr.nameseq.lower; s << ", " << address.addr.nameseq.upper << "}"; addr_ = s.str (); @@ -113,7 +112,7 @@ int zmq::tipc_address_t::to_string (std::string &addr_) const sockaddr *zmq::tipc_address_t::addr () const { - return (sockaddr*) &address; + return (sockaddr *) &address; } socklen_t zmq::tipc_address_t::addrlen () const diff --git a/src/tipc_address.hpp b/src/tipc_address.hpp index 4a379b00ef..287d91bc48 100644 --- a/src/tipc_address.hpp +++ b/src/tipc_address.hpp @@ -41,35 +41,30 @@ namespace zmq { +class tipc_address_t +{ + public: + tipc_address_t (); + tipc_address_t (const sockaddr *sa, socklen_t sa_len); + ~tipc_address_t (); - class tipc_address_t - { - public: - - tipc_address_t (); - tipc_address_t (const sockaddr *sa, socklen_t sa_len); - ~tipc_address_t (); - - // This function sets up the address "{type, lower, upper}" for TIPC transport - int resolve (const char *name); - - // The opposite to resolve() - int to_string (std::string &addr_); - - const sockaddr *addr () const; - socklen_t addrlen () const; + // This function sets up the address "{type, lower, upper}" for TIPC transport + int resolve (const char *name); - private: + // The opposite to resolve() + int to_string (std::string &addr_); - struct sockaddr_tipc address; + const sockaddr *addr () const; + socklen_t addrlen () const; - tipc_address_t (const tipc_address_t&); - const tipc_address_t &operator = (const tipc_address_t&); - }; + private: + struct sockaddr_tipc address; + tipc_address_t (const tipc_address_t &); + const tipc_address_t &operator= (const tipc_address_t &); +}; } #endif #endif - diff --git a/src/tipc_connecter.cpp b/src/tipc_connecter.cpp index 92f35fec89..58b9b5ab78 100644 --- a/src/tipc_connecter.cpp +++ b/src/tipc_connecter.cpp @@ -51,8 +51,10 @@ #include zmq::tipc_connecter_t::tipc_connecter_t (class io_thread_t *io_thread_, - class session_base_t *session_, const options_t &options_, - const address_t *addr_, bool delayed_start_) : + class session_base_t *session_, + const options_t &options_, + const address_t *addr_, + bool delayed_start_) : own_t (io_thread_, options_), io_object_t (io_thread_), addr (addr_), @@ -61,12 +63,12 @@ zmq::tipc_connecter_t::tipc_connecter_t (class io_thread_t *io_thread_, delayed_start (delayed_start_), timer_started (false), session (session_), - current_reconnect_ivl(options.reconnect_ivl) + current_reconnect_ivl (options.reconnect_ivl) { zmq_assert (addr); zmq_assert (addr->protocol == "tipc"); addr->to_string (endpoint); - socket = session-> get_socket(); + socket = session->get_socket (); } zmq::tipc_connecter_t::~tipc_connecter_t () @@ -89,7 +91,7 @@ void zmq::tipc_connecter_t::process_term (int linger_) if (timer_started) { cancel_timer (reconnect_timer_id); timer_started = false; - } + } if (handle_valid) { rm_fd (handle); @@ -119,11 +121,12 @@ void zmq::tipc_connecter_t::out_event () // Handle the error condition by attempt to reconnect. if (fd == retired_fd) { close (); - add_reconnect_timer(); + add_reconnect_timer (); return; } // Create the engine object for this connection. - stream_engine_t *engine = new (std::nothrow) stream_engine_t (fd, options, endpoint); + stream_engine_t *engine = + new (std::nothrow) stream_engine_t (fd, options, endpoint); alloc_assert (engine); // Attach the engine to the corresponding session object. @@ -155,12 +158,11 @@ void zmq::tipc_connecter_t::start_connecting () } // Connection establishment may be delayed. Poll for its completion. - else - if (rc == -1 && errno == EINPROGRESS) { + else if (rc == -1 && errno == EINPROGRESS) { handle = add_fd (s); handle_valid = true; set_pollout (handle); - socket->event_connect_delayed (endpoint, zmq_errno()); + socket->event_connect_delayed (endpoint, zmq_errno ()); } // Handle any other error condition by eventual reconnect. @@ -171,9 +173,9 @@ void zmq::tipc_connecter_t::start_connecting () } } -void zmq::tipc_connecter_t::add_reconnect_timer() +void zmq::tipc_connecter_t::add_reconnect_timer () { - int rc_ivl = get_new_reconnect_ivl(); + int rc_ivl = get_new_reconnect_ivl (); add_timer (rc_ivl, reconnect_timer_id); socket->event_connect_retried (endpoint, rc_ivl); timer_started = true; @@ -182,21 +184,20 @@ void zmq::tipc_connecter_t::add_reconnect_timer() int zmq::tipc_connecter_t::get_new_reconnect_ivl () { // The new interval is the current interval + random value. - int this_interval = current_reconnect_ivl + - (generate_random () % options.reconnect_ivl); + int this_interval = + current_reconnect_ivl + (generate_random () % options.reconnect_ivl); // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. - if (options.reconnect_ivl_max > 0 && - options.reconnect_ivl_max > options.reconnect_ivl) { - + if (options.reconnect_ivl_max > 0 + && options.reconnect_ivl_max > options.reconnect_ivl) { // Calculate the next interval current_reconnect_ivl = current_reconnect_ivl * 2; - if(current_reconnect_ivl >= options.reconnect_ivl_max) { + if (current_reconnect_ivl >= options.reconnect_ivl_max) { current_reconnect_ivl = options.reconnect_ivl_max; } } - return this_interval; + return this_interval; } int zmq::tipc_connecter_t::open () @@ -211,9 +212,8 @@ int zmq::tipc_connecter_t::open () // Set the non-blocking flag. unblock_socket (s); // Connect to the remote peer. - int rc = ::connect ( - s, addr->resolved.tipc_addr->addr (), - addr->resolved.tipc_addr->addrlen ()); + int rc = ::connect (s, addr->resolved.tipc_addr->addr (), + addr->resolved.tipc_addr->addrlen ()); // Connect was successful immediately. if (rc == 0) @@ -245,17 +245,16 @@ zmq::fd_t zmq::tipc_connecter_t::connect () int err = 0; socklen_t len = sizeof (err); - int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char*) &err, &len); + int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char *) &err, &len); if (rc == -1) err = errno; if (err != 0) { - // Assert if the error was caused by 0MQ bug. // Networking problems are OK. No need to assert. errno = err; - errno_assert (errno == ECONNREFUSED || errno == ECONNRESET || - errno == ETIMEDOUT || errno == EHOSTUNREACH || - errno == ENETUNREACH || errno == ENETDOWN); + errno_assert (errno == ECONNREFUSED || errno == ECONNRESET + || errno == ETIMEDOUT || errno == EHOSTUNREACH + || errno == ENETUNREACH || errno == ENETDOWN); return retired_fd; } @@ -265,4 +264,3 @@ zmq::fd_t zmq::tipc_connecter_t::connect () } #endif - diff --git a/src/tipc_connecter.hpp b/src/tipc_connecter.hpp index 867c10ff29..dc79eb8b16 100644 --- a/src/tipc_connecter.hpp +++ b/src/tipc_connecter.hpp @@ -41,97 +41,97 @@ namespace zmq { +class io_thread_t; +class session_base_t; +struct address_t; - class io_thread_t; - class session_base_t; - struct address_t; - - class tipc_connecter_t : public own_t, public io_object_t +class tipc_connecter_t : public own_t, public io_object_t +{ + public: + // If 'delayed_start' is true connecter first waits for a while, + // then starts connection process. + tipc_connecter_t (zmq::io_thread_t *io_thread_, + zmq::session_base_t *session_, + const options_t &options_, + const address_t *addr_, + bool delayed_start_); + ~tipc_connecter_t (); + + private: + // ID of the timer used to delay the reconnection. + enum { - public: - - // If 'delayed_start' is true connecter first waits for a while, - // then starts connection process. - tipc_connecter_t (zmq::io_thread_t *io_thread_, - zmq::session_base_t *session_, const options_t &options_, - const address_t *addr_, bool delayed_start_); - ~tipc_connecter_t (); - - private: - - // ID of the timer used to delay the reconnection. - enum {reconnect_timer_id = 1}; - - // Handlers for incoming commands. - void process_plug (); - void process_term (int linger_); + reconnect_timer_id = 1 + }; - // Handlers for I/O events. - void in_event (); - void out_event (); - void timer_event (int id_); + // Handlers for incoming commands. + void process_plug (); + void process_term (int linger_); - // Internal function to start the actual connection establishment. - void start_connecting (); + // Handlers for I/O events. + void in_event (); + void out_event (); + void timer_event (int id_); - // Internal function to add a reconnect timer - void add_reconnect_timer(); + // Internal function to start the actual connection establishment. + void start_connecting (); - // Close the connecting socket. - void close (); + // Internal function to add a reconnect timer + void add_reconnect_timer (); - // Get the file descriptor of newly created connection. Returns - // retired_fd if the connection was unsuccessful. - fd_t connect (); + // Close the connecting socket. + void close (); - // Address to connect to. Owned by session_base_t. - const address_t *addr; + // Get the file descriptor of newly created connection. Returns + // retired_fd if the connection was unsuccessful. + fd_t connect (); - // Underlying socket. - fd_t s; + // Address to connect to. Owned by session_base_t. + const address_t *addr; - // Handle corresponding to the listening socket. - handle_t handle; + // Underlying socket. + fd_t s; - // If true file descriptor is registered with the poller and 'handle' - // contains valid value. - bool handle_valid; + // Handle corresponding to the listening socket. + handle_t handle; - // If true, connecter is waiting a while before trying to connect. - const bool delayed_start; + // If true file descriptor is registered with the poller and 'handle' + // contains valid value. + bool handle_valid; - // True iff a timer has been started. - bool timer_started; + // If true, connecter is waiting a while before trying to connect. + const bool delayed_start; - // Reference to the session we belong to. - zmq::session_base_t *session; + // True iff a timer has been started. + bool timer_started; - // Current reconnect ivl, updated for backoff strategy - int current_reconnect_ivl; + // Reference to the session we belong to. + zmq::session_base_t *session; - // String representation of endpoint to connect to - std::string endpoint; + // Current reconnect ivl, updated for backoff strategy + int current_reconnect_ivl; - // Socket - zmq::socket_base_t *socket; + // String representation of endpoint to connect to + std::string endpoint; - // Internal function to return a reconnect backoff delay. - // Will modify the current_reconnect_ivl used for next call - // Returns the currently used interval - int get_new_reconnect_ivl (); + // Socket + zmq::socket_base_t *socket; - // Open IPC connecting socket. Returns -1 in case of error, - // 0 if connect was successful immediately. Returns -1 with - // EAGAIN errno if async connect was launched. - int open (); + // Internal function to return a reconnect backoff delay. + // Will modify the current_reconnect_ivl used for next call + // Returns the currently used interval + int get_new_reconnect_ivl (); - tipc_connecter_t (const tipc_connecter_t&); - const tipc_connecter_t &operator = (const tipc_connecter_t&); - }; + // Open IPC connecting socket. Returns -1 in case of error, + // 0 if connect was successful immediately. Returns -1 with + // EAGAIN errno if async connect was launched. + int open (); + tipc_connecter_t (const tipc_connecter_t &); + const tipc_connecter_t &operator= (const tipc_connecter_t &); +}; } #endif #endif - diff --git a/src/tipc_listener.cpp b/src/tipc_listener.cpp index 088346d7f6..4ad8fdae36 100644 --- a/src/tipc_listener.cpp +++ b/src/tipc_listener.cpp @@ -1,4 +1,4 @@ - /* +/* Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. @@ -52,7 +52,8 @@ #include zmq::tipc_listener_t::tipc_listener_t (io_thread_t *io_thread_, - socket_base_t *socket_, const options_t &options_) : + socket_base_t *socket_, + const options_t &options_) : own_t (io_thread_, options_), io_object_t (io_thread_), s (retired_fd), @@ -86,12 +87,13 @@ void zmq::tipc_listener_t::in_event () // If connection was reset by the peer in the meantime, just ignore it. // TODO: Handle specific errors like ENFILE/EMFILE etc. if (fd == retired_fd) { - socket->event_accept_failed (endpoint, zmq_errno()); + socket->event_accept_failed (endpoint, zmq_errno ()); return; } // Create the engine object for this connection. - stream_engine_t *engine = new (std::nothrow) stream_engine_t (fd, options, endpoint); + stream_engine_t *engine = + new (std::nothrow) stream_engine_t (fd, options, endpoint); alloc_assert (engine); // Choose I/O thread to run connecter in. Given that we are already @@ -100,8 +102,8 @@ void zmq::tipc_listener_t::in_event () zmq_assert (io_thread); // Create and launch a session object. - session_base_t *session = session_base_t::create (io_thread, false, socket, - options, NULL); + session_base_t *session = + session_base_t::create (io_thread, false, socket, options, NULL); errno_assert (session); session->inc_seqnum (); launch_child (session); @@ -127,7 +129,7 @@ int zmq::tipc_listener_t::get_address (std::string &addr_) int zmq::tipc_listener_t::set_address (const char *addr_) { //convert str to address struct - int rc = address.resolve(addr_); + int rc = address.resolve (addr_); if (rc != 0) return -1; // Create a listening socket. @@ -172,14 +174,15 @@ zmq::fd_t zmq::tipc_listener_t::accept () // The situation where connection cannot be accepted due to insufficient // resources is considered valid and treated by ignoring the connection. struct sockaddr_storage ss = {}; - socklen_t ss_len = sizeof(ss); + socklen_t ss_len = sizeof (ss); zmq_assert (s != retired_fd); fd_t sock = ::accept (s, (struct sockaddr *) &ss, &ss_len); if (sock == -1) { - errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == ENOBUFS || - errno == EINTR || errno == ECONNABORTED || errno == EPROTO || errno == EMFILE || - errno == ENFILE); + errno_assert (errno == EAGAIN || errno == EWOULDBLOCK + || errno == ENOBUFS || errno == EINTR + || errno == ECONNABORTED || errno == EPROTO + || errno == EMFILE || errno == ENFILE); return retired_fd; } /*FIXME Accept filters?*/ @@ -187,4 +190,3 @@ zmq::fd_t zmq::tipc_listener_t::accept () } #endif - diff --git a/src/tipc_listener.hpp b/src/tipc_listener.hpp index 73f3aa8564..082517f8eb 100644 --- a/src/tipc_listener.hpp +++ b/src/tipc_listener.hpp @@ -44,64 +44,60 @@ namespace zmq { +class io_thread_t; +class socket_base_t; - class io_thread_t; - class socket_base_t; - - class tipc_listener_t : public own_t, public io_object_t - { - public: - - tipc_listener_t (zmq::io_thread_t *io_thread_, - zmq::socket_base_t *socket_, const options_t &options_); - ~tipc_listener_t (); - - // Set address to listen on. - int set_address (const char *addr_); - - // Get the bound address for use with wildcards - int get_address (std::string &addr_); +class tipc_listener_t : public own_t, public io_object_t +{ + public: + tipc_listener_t (zmq::io_thread_t *io_thread_, + zmq::socket_base_t *socket_, + const options_t &options_); + ~tipc_listener_t (); - private: + // Set address to listen on. + int set_address (const char *addr_); - // Handlers for incoming commands. - void process_plug (); - void process_term (int linger_); + // Get the bound address for use with wildcards + int get_address (std::string &addr_); - // Handlers for I/O events. - void in_event (); + private: + // Handlers for incoming commands. + void process_plug (); + void process_term (int linger_); - // Close the listening socket. - void close (); + // Handlers for I/O events. + void in_event (); - // Accept the new connection. Returns the file descriptor of the - // newly created connection. The function may return retired_fd - // if the connection was dropped while waiting in the listen backlog. - fd_t accept (); + // Close the listening socket. + void close (); - // Address to listen on - tipc_address_t address; + // Accept the new connection. Returns the file descriptor of the + // newly created connection. The function may return retired_fd + // if the connection was dropped while waiting in the listen backlog. + fd_t accept (); - // Underlying socket. - fd_t s; + // Address to listen on + tipc_address_t address; + // Underlying socket. + fd_t s; - // Handle corresponding to the listening socket. - handle_t handle; - // Socket the listener belongs to. - zmq::socket_base_t *socket; + // Handle corresponding to the listening socket. + handle_t handle; - // String representation of endpoint to bind to - std::string endpoint; + // Socket the listener belongs to. + zmq::socket_base_t *socket; - tipc_listener_t (const tipc_listener_t&); - const tipc_listener_t &operator = (const tipc_listener_t&); - }; + // String representation of endpoint to bind to + std::string endpoint; + tipc_listener_t (const tipc_listener_t &); + const tipc_listener_t &operator= (const tipc_listener_t &); +}; } #endif #endif - diff --git a/src/trie.cpp b/src/trie.cpp index 4e646731ca..60b513f838 100644 --- a/src/trie.cpp +++ b/src/trie.cpp @@ -37,11 +37,7 @@ #include #include -zmq::trie_t::trie_t () : - refcnt (0), - min (0), - count (0), - live_nodes (0) +zmq::trie_t::trie_t () : refcnt (0), min (0), count (0), live_nodes (0) { } @@ -49,11 +45,10 @@ zmq::trie_t::~trie_t () { if (count == 1) { zmq_assert (next.node); - LIBZMQ_DELETE(next.node); - } - else if (count > 1) { + LIBZMQ_DELETE (next.node); + } else if (count > 1) { for (unsigned short i = 0; i != count; ++i) { - LIBZMQ_DELETE(next.table[i]); + LIBZMQ_DELETE (next.table[i]); } free (next.table); } @@ -69,50 +64,42 @@ bool zmq::trie_t::add (unsigned char *prefix_, size_t size_) unsigned char c = *prefix_; if (c < min || c >= min + count) { - // The character is out of range of currently handled // characters. We have to extend the table. if (!count) { min = c; count = 1; next.node = NULL; - } - else - if (count == 1) { + } else if (count == 1) { unsigned char oldc = min; trie_t *oldp = next.node; count = (min < c ? c - min : min - c) + 1; - next.table = (trie_t**) - malloc (sizeof (trie_t*) * count); + next.table = (trie_t **) malloc (sizeof (trie_t *) * count); alloc_assert (next.table); for (unsigned short i = 0; i != count; ++i) - next.table [i] = 0; + next.table[i] = 0; min = std::min (min, c); - next.table [oldc - min] = oldp; - } - else - if (min < c) { + next.table[oldc - min] = oldp; + } else if (min < c) { // The new character is above the current character range. unsigned short old_count = count; count = c - min + 1; - next.table = (trie_t**) realloc ((void*) next.table, - sizeof (trie_t*) * count); + next.table = (trie_t **) realloc ((void *) next.table, + sizeof (trie_t *) * count); zmq_assert (next.table); for (unsigned short i = old_count; i != count; i++) - next.table [i] = NULL; - } - else { - + next.table[i] = NULL; + } else { // The new character is below the current character range. unsigned short old_count = count; count = (min + old_count) - c; - next.table = (trie_t**) realloc ((void*) next.table, - sizeof (trie_t*) * count); + next.table = (trie_t **) realloc ((void *) next.table, + sizeof (trie_t *) * count); zmq_assert (next.table); memmove (next.table + min - c, next.table, - old_count * sizeof (trie_t*)); + old_count * sizeof (trie_t *)); for (unsigned short i = 0; i != min - c; i++) - next.table [i] = NULL; + next.table[i] = NULL; min = c; } } @@ -126,15 +113,14 @@ bool zmq::trie_t::add (unsigned char *prefix_, size_t size_) zmq_assert (live_nodes == 1); } return next.node->add (prefix_ + 1, size_ - 1); - } - else { - if (!next.table [c - min]) { - next.table [c - min] = new (std::nothrow) trie_t; - alloc_assert (next.table [c - min]); + } else { + if (!next.table[c - min]) { + next.table[c - min] = new (std::nothrow) trie_t; + alloc_assert (next.table[c - min]); ++live_nodes; zmq_assert (live_nodes > 1); } - return next.table [c - min]->add (prefix_ + 1, size_ - 1); + return next.table[c - min]->add (prefix_ + 1, size_ - 1); } } @@ -151,8 +137,7 @@ bool zmq::trie_t::rm (unsigned char *prefix_, size_t size_) if (!count || c < min || c >= min + count) return false; - trie_t *next_node = - count == 1 ? next.node : next.table [c - min]; + trie_t *next_node = count == 1 ? next.node : next.table[c - min]; if (!next_node) return false; @@ -161,7 +146,7 @@ bool zmq::trie_t::rm (unsigned char *prefix_, size_t size_) // Prune redundant nodes if (next_node->is_redundant ()) { - LIBZMQ_DELETE(next_node); + LIBZMQ_DELETE (next_node); zmq_assert (count > 0); if (count == 1) { @@ -170,9 +155,8 @@ bool zmq::trie_t::rm (unsigned char *prefix_, size_t size_) count = 0; --live_nodes; zmq_assert (live_nodes == 0); - } - else { - next.table [c - min] = 0; + } else { + next.table[c - min] = 0; zmq_assert (live_nodes > 1); --live_nodes; @@ -187,28 +171,24 @@ bool zmq::trie_t::rm (unsigned char *prefix_, size_t size_) if (c == min) { // The pruned node is the left-most node ptr in the // node table => keep the right-most node - node = next.table [count - 1]; + node = next.table[count - 1]; min += count - 1; - } - else - if (c == min + count - 1) { + } else if (c == min + count - 1) { // The pruned node is the right-most node ptr in the // node table => keep the left-most node - node = next.table [0]; + node = next.table[0]; } zmq_assert (node); free (next.table); next.node = node; count = 1; - } - else - if (c == min) { + } else if (c == min) { // We can compact the table "from the left". // Find the left-most non-null node ptr, which we'll use as // our new min unsigned char new_min = min; for (unsigned short i = 1; i < count; ++i) { - if (next.table [i]) { + if (next.table[i]) { new_min = i + min; break; } @@ -220,23 +200,21 @@ bool zmq::trie_t::rm (unsigned char *prefix_, size_t size_) zmq_assert (count > new_min - min); count = count - (new_min - min); - next.table = (trie_t**) malloc (sizeof (trie_t*) * count); + next.table = (trie_t **) malloc (sizeof (trie_t *) * count); alloc_assert (next.table); memmove (next.table, old_table + (new_min - min), - sizeof (trie_t*) * count); + sizeof (trie_t *) * count); free (old_table); min = new_min; - } - else - if (c == min + count - 1) { + } else if (c == min + count - 1) { // We can compact the table "from the right". // Find the right-most non-null node ptr, which we'll use to // determine the new table size unsigned short new_count = count; for (unsigned short i = 1; i < count; ++i) { - if (next.table [count - 1 - i]) { + if (next.table[count - 1 - i]) { new_count = count - i; break; } @@ -245,10 +223,10 @@ bool zmq::trie_t::rm (unsigned char *prefix_, size_t size_) count = new_count; trie_t **old_table = next.table; - next.table = (trie_t**) malloc (sizeof (trie_t*) * count); + next.table = (trie_t **) malloc (sizeof (trie_t *) * count); alloc_assert (next.table); - memmove (next.table, old_table, sizeof (trie_t*) * count); + memmove (next.table, old_table, sizeof (trie_t *) * count); free (old_table); } } @@ -262,7 +240,6 @@ bool zmq::trie_t::check (unsigned char *data_, size_t size_) // recursion to get a bit better performance. trie_t *current = this; while (true) { - // We've found a corresponding subscription! if (current->refcnt) return true; @@ -281,7 +258,7 @@ bool zmq::trie_t::check (unsigned char *data_, size_t size_) if (current->count == 1) current = current->next.node; else { - current = current->next.table [c - current->min]; + current = current->next.table[c - current->min]; if (!current) return false; } @@ -290,17 +267,21 @@ bool zmq::trie_t::check (unsigned char *data_, size_t size_) } } -void zmq::trie_t::apply (void (*func_) (unsigned char *data_, size_t size_, - void *arg_), void *arg_) +void zmq::trie_t::apply ( + void (*func_) (unsigned char *data_, size_t size_, void *arg_), void *arg_) { unsigned char *buff = NULL; apply_helper (&buff, 0, 0, func_, arg_); free (buff); } -void zmq::trie_t::apply_helper ( - unsigned char **buff_, size_t buffsize_, size_t maxbuffsize_, - void (*func_) (unsigned char *data_, size_t size_, void *arg_), void *arg_) +void zmq::trie_t::apply_helper (unsigned char **buff_, + size_t buffsize_, + size_t maxbuffsize_, + void (*func_) (unsigned char *data_, + size_t size_, + void *arg_), + void *arg_) { // If this node is a subscription, apply the function. if (refcnt) @@ -309,7 +290,7 @@ void zmq::trie_t::apply_helper ( // Adjust the buffer. if (buffsize_ >= maxbuffsize_) { maxbuffsize_ = buffsize_ + 256; - *buff_ = (unsigned char*) realloc (*buff_, maxbuffsize_); + *buff_ = (unsigned char *) realloc (*buff_, maxbuffsize_); zmq_assert (*buff_); } @@ -319,7 +300,7 @@ void zmq::trie_t::apply_helper ( // If there's one subnode (optimisation). if (count == 1) { - (*buff_) [buffsize_] = min; + (*buff_)[buffsize_] = min; buffsize_++; next.node->apply_helper (buff_, buffsize_, maxbuffsize_, func_, arg_); return; @@ -327,10 +308,10 @@ void zmq::trie_t::apply_helper ( // If there are multiple subnodes. for (unsigned short c = 0; c != count; c++) { - (*buff_) [buffsize_] = min + c; - if (next.table [c]) - next.table [c]->apply_helper (buff_, buffsize_ + 1, maxbuffsize_, - func_, arg_); + (*buff_)[buffsize_] = min + c; + if (next.table[c]) + next.table[c]->apply_helper (buff_, buffsize_ + 1, maxbuffsize_, + func_, arg_); } } diff --git a/src/trie.hpp b/src/trie.hpp index b3a1b3a46f..9f7073f6f4 100644 --- a/src/trie.hpp +++ b/src/trie.hpp @@ -36,51 +36,50 @@ namespace zmq { - - class trie_t +class trie_t +{ + public: + trie_t (); + ~trie_t (); + + // Add key to the trie. Returns true if this is a new item in the trie + // rather than a duplicate. + bool add (unsigned char *prefix_, size_t size_); + + // Remove key from the trie. Returns true if the item is actually + // removed from the trie. + bool rm (unsigned char *prefix_, size_t size_); + + // Check whether particular key is in the trie. + bool check (unsigned char *data_, size_t size_); + + // Apply the function supplied to each subscription in the trie. + void apply (void (*func_) (unsigned char *data_, size_t size_, void *arg_), + void *arg_); + + private: + void apply_helper (unsigned char **buff_, + size_t buffsize_, + size_t maxbuffsize_, + void (*func_) (unsigned char *data_, + size_t size_, + void *arg_), + void *arg_); + bool is_redundant () const; + + uint32_t refcnt; + unsigned char min; + unsigned short count; + unsigned short live_nodes; + union { - public: - - trie_t (); - ~trie_t (); - - // Add key to the trie. Returns true if this is a new item in the trie - // rather than a duplicate. - bool add (unsigned char *prefix_, size_t size_); - - // Remove key from the trie. Returns true if the item is actually - // removed from the trie. - bool rm (unsigned char *prefix_, size_t size_); - - // Check whether particular key is in the trie. - bool check (unsigned char *data_, size_t size_); - - // Apply the function supplied to each subscription in the trie. - void apply (void (*func_) (unsigned char *data_, size_t size_, - void *arg_), void *arg_); - - private: - - void apply_helper ( - unsigned char **buff_, size_t buffsize_, size_t maxbuffsize_, - void (*func_) (unsigned char *data_, size_t size_, void *arg_), - void *arg_); - bool is_redundant () const; - - uint32_t refcnt; - unsigned char min; - unsigned short count; - unsigned short live_nodes; - union { - class trie_t *node; - class trie_t **table; - } next; - - trie_t (const trie_t&); - const trie_t &operator = (const trie_t&); - }; + class trie_t *node; + class trie_t **table; + } next; + trie_t (const trie_t &); + const trie_t &operator= (const trie_t &); +}; } #endif - diff --git a/src/tweetnacl.h b/src/tweetnacl.h index 95f8b2a58c..d0435909c3 100644 --- a/src/tweetnacl.h +++ b/src/tweetnacl.h @@ -30,7 +30,7 @@ #ifndef TWEETNACL_H #define TWEETNACL_H -#if defined (ZMQ_USE_TWEETNACL) +#if defined(ZMQ_USE_TWEETNACL) #define crypto_box_SECRETKEYBYTES 32 #define crypto_box_BOXZEROBYTES 16 @@ -57,15 +57,18 @@ int randombytes_close (void); // Do not call manually! Use random_open from random.hpp int sodium_init (void); -int crypto_box_keypair(u8 *y,u8 *x); -int crypto_box_afternm(u8 *c,const u8 *m,u64 d,const u8 *n,const u8 *k); -int crypto_box_open_afternm(u8 *m,const u8 *c,u64 d,const u8 *n,const u8 *k); -int crypto_box(u8 *c,const u8 *m,u64 d,const u8 *n,const u8 *y,const u8 *x); -int crypto_box_open(u8 *m,const u8 *c,u64 d,const u8 *n,const u8 *y,const u8 *x); -int crypto_box_beforenm(u8 *k,const u8 *y,const u8 *x); -int crypto_scalarmult_base(u8 *q,const u8 *n); -int crypto_secretbox(u8 *c,const u8 *m,u64 d,const u8 *n,const u8 *k); -int crypto_secretbox_open(u8 *m,const u8 *c,u64 d,const u8 *n,const u8 *k); +int crypto_box_keypair (u8 *y, u8 *x); +int crypto_box_afternm (u8 *c, const u8 *m, u64 d, const u8 *n, const u8 *k); +int crypto_box_open_afternm ( + u8 *m, const u8 *c, u64 d, const u8 *n, const u8 *k); +int crypto_box ( + u8 *c, const u8 *m, u64 d, const u8 *n, const u8 *y, const u8 *x); +int crypto_box_open ( + u8 *m, const u8 *c, u64 d, const u8 *n, const u8 *y, const u8 *x); +int crypto_box_beforenm (u8 *k, const u8 *y, const u8 *x); +int crypto_scalarmult_base (u8 *q, const u8 *n); +int crypto_secretbox (u8 *c, const u8 *m, u64 d, const u8 *n, const u8 *k); +int crypto_secretbox_open (u8 *m, const u8 *c, u64 d, const u8 *n, const u8 *k); #ifdef __cplusplus } #endif diff --git a/src/udp_address.cpp b/src/udp_address.cpp index 6c2c50f86e..99887eb616 100644 --- a/src/udp_address.cpp +++ b/src/udp_address.cpp @@ -44,8 +44,7 @@ #include #endif -zmq::udp_address_t::udp_address_t () - : is_multicast(false) +zmq::udp_address_t::udp_address_t () : is_multicast (false) { memset (&bind_address, 0, sizeof bind_address); memset (&dest_address, 0, sizeof dest_address); @@ -93,11 +92,10 @@ int zmq::udp_address_t::resolve (const char *name_, bool bind_) // and if it from 224 to 239, then it can // represent multicast IP. int i = dest_address.sin_addr.s_addr & 0xFF; - if(i >= 224 && i <= 239) { + if (i >= 224 && i <= 239) { multicast = dest_address.sin_addr; is_multicast = true; - } - else + } else is_multicast = false; iface.s_addr = htonl (INADDR_ANY); @@ -132,7 +130,7 @@ bool zmq::udp_address_t::is_mcast () const return is_multicast; } -const sockaddr* zmq::udp_address_t::bind_addr () const +const sockaddr *zmq::udp_address_t::bind_addr () const { return (sockaddr *) &bind_address; } @@ -142,7 +140,7 @@ socklen_t zmq::udp_address_t::bind_addrlen () const return sizeof (sockaddr_in); } -const sockaddr* zmq::udp_address_t::dest_addr () const +const sockaddr *zmq::udp_address_t::dest_addr () const { return (sockaddr *) &dest_address; } diff --git a/src/udp_address.hpp b/src/udp_address.hpp index b3794186cc..836074602b 100644 --- a/src/udp_address.hpp +++ b/src/udp_address.hpp @@ -37,42 +37,41 @@ namespace zmq { - class udp_address_t - { - public: - - udp_address_t (); - virtual ~udp_address_t (); +class udp_address_t +{ + public: + udp_address_t (); + virtual ~udp_address_t (); - int resolve (const char *name_, bool receiver_); + int resolve (const char *name_, bool receiver_); - // The opposite to resolve() - virtual int to_string (std::string &addr_); + // The opposite to resolve() + virtual int to_string (std::string &addr_); #if defined ZMQ_HAVE_WINDOWS - unsigned short family () const; + unsigned short family () const; #else - sa_family_t family () const; + sa_family_t family () const; #endif - const sockaddr *bind_addr () const; - socklen_t bind_addrlen () const; + const sockaddr *bind_addr () const; + socklen_t bind_addrlen () const; - const sockaddr *dest_addr () const; - socklen_t dest_addrlen () const; + const sockaddr *dest_addr () const; + socklen_t dest_addrlen () const; - bool is_mcast () const; + bool is_mcast () const; - const in_addr multicast_ip () const; - const in_addr interface_ip () const; + const in_addr multicast_ip () const; + const in_addr interface_ip () const; - private: - in_addr multicast; - in_addr iface; - sockaddr_in bind_address; - sockaddr_in dest_address; - bool is_multicast; - std::string address; - }; + private: + in_addr multicast; + in_addr iface; + sockaddr_in bind_address; + sockaddr_in dest_address; + bool is_multicast; + std::string address; +}; } #endif diff --git a/src/udp_engine.cpp b/src/udp_engine.cpp index 00d51b1396..2dcb075333 100644 --- a/src/udp_engine.cpp +++ b/src/udp_engine.cpp @@ -43,19 +43,19 @@ along with this program. If not, see . #include "err.hpp" #include "ip.hpp" -zmq::udp_engine_t::udp_engine_t(const options_t &options_) : +zmq::udp_engine_t::udp_engine_t (const options_t &options_) : plugged (false), - fd(-1), - session(NULL), - handle((handle_t)NULL), - address(NULL), - options(options_), - send_enabled(false), - recv_enabled(false) + fd (-1), + session (NULL), + handle ((handle_t) NULL), + address (NULL), + options (options_), + send_enabled (false), + recv_enabled (false) { } -zmq::udp_engine_t::~udp_engine_t() +zmq::udp_engine_t::~udp_engine_t () { zmq_assert (!plugged); @@ -79,7 +79,8 @@ int zmq::udp_engine_t::init (address_t *address_, bool send_, bool recv_) recv_enabled = recv_; address = address_; - fd = open_socket (address->resolved.udp_addr->family (), SOCK_DGRAM, IPPROTO_UDP); + fd = open_socket (address->resolved.udp_addr->family (), SOCK_DGRAM, + IPPROTO_UDP); if (fd == retired_fd) return -1; @@ -88,7 +89,7 @@ int zmq::udp_engine_t::init (address_t *address_, bool send_, bool recv_) return 0; } -void zmq::udp_engine_t::plug (io_thread_t* io_thread_, session_base_t *session_) +void zmq::udp_engine_t::plug (io_thread_t *io_thread_, session_base_t *session_) { zmq_assert (!plugged); plugged = true; @@ -109,8 +110,7 @@ void zmq::udp_engine_t::plug (io_thread_t* io_thread_, session_base_t *session_) if (!options.raw_socket) { out_address = address->resolved.udp_addr->dest_addr (); out_addrlen = address->resolved.udp_addr->dest_addrlen (); - } - else { + } else { out_address = (sockaddr *) &raw_address; out_addrlen = sizeof (sockaddr_in); } @@ -120,7 +120,8 @@ void zmq::udp_engine_t::plug (io_thread_t* io_thread_, session_base_t *session_) if (recv_enabled) { int on = 1; - int rc = setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof (on)); + int rc = + setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof (on)); #ifdef ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); #else @@ -128,7 +129,7 @@ void zmq::udp_engine_t::plug (io_thread_t* io_thread_, session_base_t *session_) #endif rc = bind (fd, address->resolved.udp_addr->bind_addr (), - address->resolved.udp_addr->bind_addrlen ()); + address->resolved.udp_addr->bind_addrlen ()); #ifdef ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); #else @@ -139,7 +140,8 @@ void zmq::udp_engine_t::plug (io_thread_t* io_thread_, session_base_t *session_) struct ip_mreq mreq; mreq.imr_multiaddr = address->resolved.udp_addr->multicast_ip (); mreq.imr_interface = address->resolved.udp_addr->interface_ip (); - rc = setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &mreq, sizeof (mreq)); + rc = setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, + sizeof (mreq)); #ifdef ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); #else @@ -153,7 +155,7 @@ void zmq::udp_engine_t::plug (io_thread_t* io_thread_, session_base_t *session_) } } -void zmq::udp_engine_t::terminate() +void zmq::udp_engine_t::terminate () { zmq_assert (plugged); plugged = false; @@ -166,18 +168,19 @@ void zmq::udp_engine_t::terminate() delete this; } -void zmq::udp_engine_t::sockaddr_to_msg (zmq::msg_t *msg, sockaddr_in* addr) +void zmq::udp_engine_t::sockaddr_to_msg (zmq::msg_t *msg, sockaddr_in *addr) { - char* name = inet_ntoa(addr->sin_addr); + char *name = inet_ntoa (addr->sin_addr); char port[6]; sprintf (port, "%d", (int) ntohs (addr->sin_port)); - int size = (int) strlen (name) + (int) strlen (port) + 1 + 1; // Colon + NULL + int size = + (int) strlen (name) + (int) strlen (port) + 1 + 1; // Colon + NULL int rc = msg->init_size (size); errno_assert (rc == 0); msg->set_flags (msg_t::more); - char *address = (char*)msg->data (); + char *address = (char *) msg->data (); strcpy (address, name); strcat (address, ":"); @@ -229,7 +232,7 @@ int zmq::udp_engine_t::resolve_raw_address (char *name_, size_t length_) return 0; } -void zmq::udp_engine_t::out_event() +void zmq::udp_engine_t::out_event () { msg_t group_msg; int rc = session->pull_msg (&group_msg); @@ -244,7 +247,7 @@ void zmq::udp_engine_t::out_event() size_t size; if (options.raw_socket) { - rc = resolve_raw_address ((char*) group_msg.data(), group_size); + rc = resolve_raw_address ((char *) group_msg.data (), group_size); // We discard the message if address is not valid if (rc != 0) { @@ -260,8 +263,7 @@ void zmq::udp_engine_t::out_event() size = body_size; memcpy (out_buffer, body_msg.data (), body_size); - } - else { + } else { size = group_size + body_size + 1; // TODO: check if larger than maximum size @@ -277,16 +279,15 @@ void zmq::udp_engine_t::out_event() errno_assert (rc == 0); #ifdef ZMQ_HAVE_WINDOWS - rc = sendto (fd, (const char *) out_buffer, (int) size, 0, - out_address, (int) out_addrlen); + rc = sendto (fd, (const char *) out_buffer, (int) size, 0, out_address, + (int) out_addrlen); wsa_assert (rc != SOCKET_ERROR); #else rc = sendto (fd, out_buffer, size, 0, out_address, out_addrlen); errno_assert (rc != -1); #endif - } - else - reset_pollout (handle); + } else + reset_pollout (handle); } const char *zmq::udp_engine_t::get_endpoint () const @@ -294,41 +295,38 @@ const char *zmq::udp_engine_t::get_endpoint () const return ""; } -void zmq::udp_engine_t::restart_output() +void zmq::udp_engine_t::restart_output () { // If we don't support send we just drop all messages if (!send_enabled) { msg_t msg; while (session->pull_msg (&msg) == 0) msg.close (); - } - else { - set_pollout(handle); + } else { + set_pollout (handle); out_event (); } } -void zmq::udp_engine_t::in_event() +void zmq::udp_engine_t::in_event () { - struct sockaddr_in in_address; - socklen_t in_addrlen = sizeof(sockaddr_in); + struct sockaddr_in in_address; + socklen_t in_addrlen = sizeof (sockaddr_in); #ifdef ZMQ_HAVE_WINDOWS - int nbytes = recvfrom(fd, (char*) in_buffer, MAX_UDP_MSG, 0, (sockaddr*) &in_address, &in_addrlen); - const int last_error = WSAGetLastError(); + int nbytes = recvfrom (fd, (char *) in_buffer, MAX_UDP_MSG, 0, + (sockaddr *) &in_address, &in_addrlen); + const int last_error = WSAGetLastError (); if (nbytes == SOCKET_ERROR) { - wsa_assert( - last_error == WSAENETDOWN || - last_error == WSAENETRESET || - last_error == WSAEWOULDBLOCK); + wsa_assert (last_error == WSAENETDOWN || last_error == WSAENETRESET + || last_error == WSAEWOULDBLOCK); return; } #else - int nbytes = recvfrom(fd, in_buffer, MAX_UDP_MSG, 0, (sockaddr*) &in_address, &in_addrlen); + int nbytes = recvfrom (fd, in_buffer, MAX_UDP_MSG, 0, + (sockaddr *) &in_address, &in_addrlen); if (nbytes == -1) { - errno_assert(errno != EBADF - && errno != EFAULT - && errno != ENOMEM - && errno != ENOTSOCK); + errno_assert (errno != EBADF && errno != EFAULT && errno != ENOMEM + && errno != ENOTSOCK); return; } #endif @@ -342,9 +340,8 @@ void zmq::udp_engine_t::in_event() body_size = nbytes; body_offset = 0; - } - else { - char* group_buffer = (char *)in_buffer + 1; + } else { + char *group_buffer = (char *) in_buffer + 1; int group_size = in_buffer[0]; rc = msg.init_size (group_size); @@ -384,7 +381,7 @@ void zmq::udp_engine_t::in_event() session->flush (); } -void zmq::udp_engine_t::restart_input() +void zmq::udp_engine_t::restart_input () { if (!recv_enabled) return; diff --git a/src/udp_engine.hpp b/src/udp_engine.hpp index 233d05f652..1a02c52443 100644 --- a/src/udp_engine.hpp +++ b/src/udp_engine.hpp @@ -12,62 +12,62 @@ namespace zmq { - class io_thread_t; - class session_base_t; +class io_thread_t; +class session_base_t; - class udp_engine_t : public io_object_t, public i_engine - { - public: - udp_engine_t (const options_t &options_); - ~udp_engine_t (); +class udp_engine_t : public io_object_t, public i_engine +{ + public: + udp_engine_t (const options_t &options_); + ~udp_engine_t (); - int init (address_t *address_, bool send_, bool recv_); + int init (address_t *address_, bool send_, bool recv_); - // i_engine interface implementation. - // Plug the engine to the session. - void plug (zmq::io_thread_t *io_thread_, class session_base_t *session_); + // i_engine interface implementation. + // Plug the engine to the session. + void plug (zmq::io_thread_t *io_thread_, class session_base_t *session_); - // Terminate and deallocate the engine. Note that 'detached' - // events are not fired on termination. - void terminate (); + // Terminate and deallocate the engine. Note that 'detached' + // events are not fired on termination. + void terminate (); - // This method is called by the session to signalise that more - // messages can be written to the pipe. - void restart_input (); + // This method is called by the session to signalise that more + // messages can be written to the pipe. + void restart_input (); - // This method is called by the session to signalise that there - // are messages to send available. - void restart_output (); + // This method is called by the session to signalise that there + // are messages to send available. + void restart_output (); - void zap_msg_available () {}; + void zap_msg_available (){}; - void in_event (); - void out_event (); + void in_event (); + void out_event (); - const char *get_endpoint () const; + const char *get_endpoint () const; - private: - int resolve_raw_address (char *addr_, size_t length_); - void sockaddr_to_msg (zmq::msg_t *msg, sockaddr_in* addr); + private: + int resolve_raw_address (char *addr_, size_t length_); + void sockaddr_to_msg (zmq::msg_t *msg, sockaddr_in *addr); - bool plugged; + bool plugged; - fd_t fd; - session_base_t* session; - handle_t handle; - address_t *address; + fd_t fd; + session_base_t *session; + handle_t handle; + address_t *address; - options_t options; + options_t options; - sockaddr_in raw_address; - const struct sockaddr* out_address; - socklen_t out_addrlen; + sockaddr_in raw_address; + const struct sockaddr *out_address; + socklen_t out_addrlen; - unsigned char out_buffer[MAX_UDP_MSG]; - unsigned char in_buffer[MAX_UDP_MSG]; - bool send_enabled; - bool recv_enabled; - }; + unsigned char out_buffer[MAX_UDP_MSG]; + unsigned char in_buffer[MAX_UDP_MSG]; + bool send_enabled; + bool recv_enabled; +}; } #endif diff --git a/src/v1_decoder.cpp b/src/v1_decoder.cpp index 7744d6eafa..8964569c2c 100644 --- a/src/v1_decoder.cpp +++ b/src/v1_decoder.cpp @@ -39,8 +39,8 @@ #include "err.hpp" zmq::v1_decoder_t::v1_decoder_t (size_t bufsize_, int64_t maxmsgsize_) : - c_single_allocator(bufsize_), - decoder_base_t (this), + c_single_allocator (bufsize_), + decoder_base_t (this), maxmsgsize (maxmsgsize_) { int rc = in_progress.init (); @@ -56,7 +56,7 @@ zmq::v1_decoder_t::~v1_decoder_t () errno_assert (rc == 0); } -int zmq::v1_decoder_t::one_byte_size_ready (unsigned char const*) +int zmq::v1_decoder_t::one_byte_size_ready (unsigned char const *) { // First byte of size is read. If it is 0xff read 8-byte size. // Otherwise allocate the buffer for message data and read the @@ -64,7 +64,6 @@ int zmq::v1_decoder_t::one_byte_size_ready (unsigned char const*) if (*tmpbuf == 0xff) next_step (tmpbuf, 8, &v1_decoder_t::eight_byte_size_ready); else { - // There has to be at least one byte (the flags) in the message). if (!*tmpbuf) { errno = EPROTO; @@ -76,8 +75,8 @@ int zmq::v1_decoder_t::one_byte_size_ready (unsigned char const*) return -1; } - int rc = in_progress.close(); - assert(rc == 0); + int rc = in_progress.close (); + assert (rc == 0); rc = in_progress.init_size (*tmpbuf - 1); if (rc != 0) { errno_assert (errno == ENOMEM); @@ -92,7 +91,7 @@ int zmq::v1_decoder_t::one_byte_size_ready (unsigned char const*) return 0; } -int zmq::v1_decoder_t::eight_byte_size_ready (unsigned char const*) +int zmq::v1_decoder_t::eight_byte_size_ready (unsigned char const *) { // 8-byte payload length is read. Allocate the buffer // for message body and read the message data into it. @@ -111,15 +110,15 @@ int zmq::v1_decoder_t::eight_byte_size_ready (unsigned char const*) } // Message size must fit within range of size_t data type. - if (payload_length - 1 > std::numeric_limits ::max ()) { + if (payload_length - 1 > std::numeric_limits::max ()) { errno = EMSGSIZE; return -1; } - const size_t msg_size = static_cast (payload_length - 1); + const size_t msg_size = static_cast (payload_length - 1); - int rc = in_progress.close(); - assert(rc == 0); + int rc = in_progress.close (); + assert (rc == 0); rc = in_progress.init_size (msg_size); if (rc != 0) { errno_assert (errno == ENOMEM); @@ -133,18 +132,18 @@ int zmq::v1_decoder_t::eight_byte_size_ready (unsigned char const*) return 0; } -int zmq::v1_decoder_t::flags_ready (unsigned char const*) +int zmq::v1_decoder_t::flags_ready (unsigned char const *) { // Store the flags from the wire into the message structure. - in_progress.set_flags (tmpbuf [0] & msg_t::more); + in_progress.set_flags (tmpbuf[0] & msg_t::more); next_step (in_progress.data (), in_progress.size (), - &v1_decoder_t::message_ready); + &v1_decoder_t::message_ready); return 0; } -int zmq::v1_decoder_t::message_ready (unsigned char const*) +int zmq::v1_decoder_t::message_ready (unsigned char const *) { // Message is completely read. Push it further and start reading // new message. (in_progress is a 0-byte message after this point.) diff --git a/src/v1_decoder.hpp b/src/v1_decoder.hpp index 99afffd623..8ccc9c5608 100644 --- a/src/v1_decoder.hpp +++ b/src/v1_decoder.hpp @@ -34,36 +34,31 @@ namespace zmq { - // Decoder for ZMTP/1.0 protocol. Converts data batches into messages. +// Decoder for ZMTP/1.0 protocol. Converts data batches into messages. - class v1_decoder_t : - public zmq::c_single_allocator, - public decoder_base_t - { - public: - - v1_decoder_t (size_t bufsize_, int64_t maxmsgsize_); - ~v1_decoder_t (); - - virtual msg_t *msg () { return &in_progress; } - - private: +class v1_decoder_t : public zmq::c_single_allocator, + public decoder_base_t +{ + public: + v1_decoder_t (size_t bufsize_, int64_t maxmsgsize_); + ~v1_decoder_t (); - int one_byte_size_ready (unsigned char const*); - int eight_byte_size_ready (unsigned char const*); - int flags_ready (unsigned char const*); - int message_ready (unsigned char const*); + virtual msg_t *msg () { return &in_progress; } - unsigned char tmpbuf [8]; - msg_t in_progress; + private: + int one_byte_size_ready (unsigned char const *); + int eight_byte_size_ready (unsigned char const *); + int flags_ready (unsigned char const *); + int message_ready (unsigned char const *); - int64_t maxmsgsize; + unsigned char tmpbuf[8]; + msg_t in_progress; - v1_decoder_t (const v1_decoder_t&); - void operator = (const v1_decoder_t&); - }; + int64_t maxmsgsize; + v1_decoder_t (const v1_decoder_t &); + void operator= (const v1_decoder_t &); +}; } #endif - diff --git a/src/v1_encoder.cpp b/src/v1_encoder.cpp index 391e499e65..c7e37c63c0 100644 --- a/src/v1_encoder.cpp +++ b/src/v1_encoder.cpp @@ -34,7 +34,7 @@ #include "wire.hpp" zmq::v1_encoder_t::v1_encoder_t (size_t bufsize_) : - encoder_base_t (bufsize_) + encoder_base_t (bufsize_) { // Write 0 bytes to the batch and go to message_ready state. next_step (NULL, 0, &v1_encoder_t::message_ready, true); @@ -48,7 +48,7 @@ void zmq::v1_encoder_t::size_ready () { // Write message body into the buffer. next_step (in_progress->data (), in_progress->size (), - &v1_encoder_t::message_ready, true); + &v1_encoder_t::message_ready, true); } void zmq::v1_encoder_t::message_ready () @@ -63,14 +63,13 @@ void zmq::v1_encoder_t::message_ready () // For longer messages write 0xff escape character followed by 8-byte // message size. In both cases 'flags' field follows. if (size < 255) { - tmpbuf [0] = (unsigned char) size; - tmpbuf [1] = (in_progress->flags () & msg_t::more); + tmpbuf[0] = (unsigned char) size; + tmpbuf[1] = (in_progress->flags () & msg_t::more); next_step (tmpbuf, 2, &v1_encoder_t::size_ready, false); - } - else { - tmpbuf [0] = 0xff; + } else { + tmpbuf[0] = 0xff; put_uint64 (tmpbuf + 1, size); - tmpbuf [9] = (in_progress->flags () & msg_t::more); + tmpbuf[9] = (in_progress->flags () & msg_t::more); next_step (tmpbuf, 10, &v1_encoder_t::size_ready, false); } } diff --git a/src/v1_encoder.hpp b/src/v1_encoder.hpp index 25e7997171..974740e7b0 100644 --- a/src/v1_encoder.hpp +++ b/src/v1_encoder.hpp @@ -34,26 +34,23 @@ namespace zmq { - // Encoder for ZMTP/1.0 protocol. Converts messages into data batches. +// Encoder for ZMTP/1.0 protocol. Converts messages into data batches. - class v1_encoder_t : public encoder_base_t - { - public: - - v1_encoder_t (size_t bufsize_); - ~v1_encoder_t (); - - private: +class v1_encoder_t : public encoder_base_t +{ + public: + v1_encoder_t (size_t bufsize_); + ~v1_encoder_t (); - void size_ready (); - void message_ready (); + private: + void size_ready (); + void message_ready (); - unsigned char tmpbuf [10]; + unsigned char tmpbuf[10]; - v1_encoder_t (const v1_encoder_t&); - const v1_encoder_t &operator = (const v1_encoder_t&); - }; + v1_encoder_t (const v1_encoder_t &); + const v1_encoder_t &operator= (const v1_encoder_t &); +}; } #endif - diff --git a/src/v2_decoder.cpp b/src/v2_decoder.cpp index 0754541f0e..6d3e503fd4 100644 --- a/src/v2_decoder.cpp +++ b/src/v2_decoder.cpp @@ -39,8 +39,8 @@ #include "err.hpp" zmq::v2_decoder_t::v2_decoder_t (size_t bufsize_, int64_t maxmsgsize_) : - shared_message_memory_allocator( bufsize_), - decoder_base_t (this), + shared_message_memory_allocator (bufsize_), + decoder_base_t (this), msg_flags (0), maxmsgsize (maxmsgsize_) { @@ -57,17 +57,17 @@ zmq::v2_decoder_t::~v2_decoder_t () errno_assert (rc == 0); } -int zmq::v2_decoder_t::flags_ready (unsigned char const*) +int zmq::v2_decoder_t::flags_ready (unsigned char const *) { msg_flags = 0; - if (tmpbuf [0] & v2_protocol_t::more_flag) + if (tmpbuf[0] & v2_protocol_t::more_flag) msg_flags |= msg_t::more; - if (tmpbuf [0] & v2_protocol_t::command_flag) + if (tmpbuf[0] & v2_protocol_t::command_flag) msg_flags |= msg_t::command; // The payload length is either one or eight bytes, // depending on whether the 'large' bit is set. - if (tmpbuf [0] & v2_protocol_t::large_flag) + if (tmpbuf[0] & v2_protocol_t::large_flag) next_step (tmpbuf, 8, &v2_decoder_t::eight_byte_size_ready); else next_step (tmpbuf, 1, &v2_decoder_t::one_byte_size_ready); @@ -75,59 +75,60 @@ int zmq::v2_decoder_t::flags_ready (unsigned char const*) return 0; } -int zmq::v2_decoder_t::one_byte_size_ready (unsigned char const* read_from) +int zmq::v2_decoder_t::one_byte_size_ready (unsigned char const *read_from) { - return size_ready(tmpbuf[0], read_from); + return size_ready (tmpbuf[0], read_from); } -int zmq::v2_decoder_t::eight_byte_size_ready (unsigned char const* read_from) { +int zmq::v2_decoder_t::eight_byte_size_ready (unsigned char const *read_from) +{ // The payload size is encoded as 64-bit unsigned integer. // The most significant byte comes first. - const uint64_t msg_size = get_uint64(tmpbuf); + const uint64_t msg_size = get_uint64 (tmpbuf); - return size_ready(msg_size, read_from); + return size_ready (msg_size, read_from); } -int zmq::v2_decoder_t::size_ready(uint64_t msg_size, unsigned char const* read_pos) { +int zmq::v2_decoder_t::size_ready (uint64_t msg_size, + unsigned char const *read_pos) +{ // Message size must not exceed the maximum allowed size. if (maxmsgsize >= 0) - if (unlikely (msg_size > static_cast (maxmsgsize))) { + if (unlikely (msg_size > static_cast (maxmsgsize))) { errno = EMSGSIZE; return -1; } // Message size must fit into size_t data type. - if (unlikely (msg_size != static_cast (msg_size))) { + if (unlikely (msg_size != static_cast (msg_size))) { errno = EMSGSIZE; return -1; } - int rc = in_progress.close(); - assert(rc == 0); + int rc = in_progress.close (); + assert (rc == 0); // the current message can exceed the current buffer. We have to copy the buffer // data into a new message and complete it in the next receive. - if (unlikely ((unsigned char*)read_pos + msg_size > (data() + size()))) - { + if (unlikely ((unsigned char *) read_pos + msg_size + > (data () + size ()))) { // a new message has started, but the size would exceed the pre-allocated arena // this happens every time when a message does not fit completely into the buffer - rc = in_progress.init_size (static_cast (msg_size)); - } - else - { + rc = in_progress.init_size (static_cast (msg_size)); + } else { // construct message using n bytes from the buffer as storage // increase buffer ref count // if the message will be a large message, pass a valid refcnt memory location as well - rc = in_progress.init ((unsigned char *) read_pos, static_cast (msg_size), - shared_message_memory_allocator::call_dec_ref, buffer(), - provide_content ()); + rc = in_progress.init ((unsigned char *) read_pos, + static_cast (msg_size), + shared_message_memory_allocator::call_dec_ref, + buffer (), provide_content ()); // For small messages, data has been copied and refcount does not have to be increased - if (in_progress.is_zcmsg()) - { - advance_content(); - inc_ref(); + if (in_progress.is_zcmsg ()) { + advance_content (); + inc_ref (); } } @@ -147,12 +148,12 @@ int zmq::v2_decoder_t::size_ready(uint64_t msg_size, unsigned char const* read_p // to the current start address in the buffer because the message // was constructed to use n bytes from the address passed as argument next_step (in_progress.data (), in_progress.size (), - &v2_decoder_t::message_ready); + &v2_decoder_t::message_ready); return 0; } -int zmq::v2_decoder_t::message_ready (unsigned char const*) +int zmq::v2_decoder_t::message_ready (unsigned char const *) { // Message is completely read. Signal this to the caller // and prepare to decode next message. diff --git a/src/v2_decoder.hpp b/src/v2_decoder.hpp index f7a69a10d0..3c47204e13 100644 --- a/src/v2_decoder.hpp +++ b/src/v2_decoder.hpp @@ -35,40 +35,38 @@ namespace zmq { - // Decoder for ZMTP/2.x framing protocol. Converts data stream into messages. - // The class has to inherit from shared_message_memory_allocator because - // the base class calls allocate in its constructor. - class v2_decoder_t : - // inherit first from allocator to ensure that it is constructed before decoder_base_t - public shared_message_memory_allocator, - public decoder_base_t - { - public: - v2_decoder_t (size_t bufsize_, int64_t maxmsgsize_); - virtual ~v2_decoder_t (); - - // i_decoder interface. - virtual msg_t *msg () { return &in_progress; } - - private: +// Decoder for ZMTP/2.x framing protocol. Converts data stream into messages. +// The class has to inherit from shared_message_memory_allocator because +// the base class calls allocate in its constructor. +class v2_decoder_t : + // inherit first from allocator to ensure that it is constructed before decoder_base_t + public shared_message_memory_allocator, + public decoder_base_t +{ + public: + v2_decoder_t (size_t bufsize_, int64_t maxmsgsize_); + virtual ~v2_decoder_t (); - int flags_ready (unsigned char const*); - int one_byte_size_ready (unsigned char const*); - int eight_byte_size_ready (unsigned char const*); - int message_ready (unsigned char const*); + // i_decoder interface. + virtual msg_t *msg () { return &in_progress; } - int size_ready(uint64_t size_, unsigned char const*); + private: + int flags_ready (unsigned char const *); + int one_byte_size_ready (unsigned char const *); + int eight_byte_size_ready (unsigned char const *); + int message_ready (unsigned char const *); - unsigned char tmpbuf [8]; - unsigned char msg_flags; - msg_t in_progress; + int size_ready (uint64_t size_, unsigned char const *); - const int64_t maxmsgsize; + unsigned char tmpbuf[8]; + unsigned char msg_flags; + msg_t in_progress; - v2_decoder_t (const v2_decoder_t&); - void operator = (const v2_decoder_t&); - }; + const int64_t maxmsgsize; + v2_decoder_t (const v2_decoder_t &); + void operator= (const v2_decoder_t &); +}; } #endif diff --git a/src/v2_encoder.cpp b/src/v2_encoder.cpp index d5d2bf4fed..63362301a5 100644 --- a/src/v2_encoder.cpp +++ b/src/v2_encoder.cpp @@ -34,7 +34,7 @@ #include "wire.hpp" zmq::v2_encoder_t::v2_encoder_t (size_t bufsize_) : - encoder_base_t (bufsize_) + encoder_base_t (bufsize_) { // Write 0 bytes to the batch and go to message_ready state. next_step (NULL, 0, &v2_encoder_t::message_ready, true); @@ -47,7 +47,7 @@ zmq::v2_encoder_t::~v2_encoder_t () void zmq::v2_encoder_t::message_ready () { // Encode flags. - unsigned char &protocol_flags = tmpbuf [0]; + unsigned char &protocol_flags = tmpbuf[0]; protocol_flags = 0; if (in_progress->flags () & msg_t::more) protocol_flags |= v2_protocol_t::more_flag; @@ -63,9 +63,8 @@ void zmq::v2_encoder_t::message_ready () if (unlikely (size > 255)) { put_uint64 (tmpbuf + 1, size); next_step (tmpbuf, 9, &v2_encoder_t::size_ready, false); - } - else { - tmpbuf [1] = static_cast (size); + } else { + tmpbuf[1] = static_cast (size); next_step (tmpbuf, 2, &v2_encoder_t::size_ready, false); } } @@ -74,5 +73,5 @@ void zmq::v2_encoder_t::size_ready () { // Write message body into the buffer. next_step (in_progress->data (), in_progress->size (), - &v2_encoder_t::message_ready, true); + &v2_encoder_t::message_ready, true); } diff --git a/src/v2_encoder.hpp b/src/v2_encoder.hpp index 523deae8d7..c7efc604a1 100644 --- a/src/v2_encoder.hpp +++ b/src/v2_encoder.hpp @@ -34,26 +34,23 @@ namespace zmq { - // Encoder for 0MQ framing protocol. Converts messages into data stream. +// Encoder for 0MQ framing protocol. Converts messages into data stream. - class v2_encoder_t : public encoder_base_t - { - public: - - v2_encoder_t (size_t bufsize_); - virtual ~v2_encoder_t (); - - private: +class v2_encoder_t : public encoder_base_t +{ + public: + v2_encoder_t (size_t bufsize_); + virtual ~v2_encoder_t (); - void size_ready (); - void message_ready (); + private: + void size_ready (); + void message_ready (); - unsigned char tmpbuf [9]; + unsigned char tmpbuf[9]; - v2_encoder_t (const v2_encoder_t&); - const v2_encoder_t &operator = (const v2_encoder_t&); - }; + v2_encoder_t (const v2_encoder_t &); + const v2_encoder_t &operator= (const v2_encoder_t &); +}; } #endif - diff --git a/src/v2_protocol.hpp b/src/v2_protocol.hpp index 3780ed2c59..f1297295bc 100644 --- a/src/v2_protocol.hpp +++ b/src/v2_protocol.hpp @@ -32,18 +32,18 @@ namespace zmq { - // Definition of constants for ZMTP/2.0 transport protocol. - class v2_protocol_t +// Definition of constants for ZMTP/2.0 transport protocol. +class v2_protocol_t +{ + public: + // Message flags. + enum { - public: - // Message flags. - enum - { - more_flag = 1, - large_flag = 2, - command_flag = 4 - }; + more_flag = 1, + large_flag = 2, + command_flag = 4 }; +}; } #endif diff --git a/src/vmci.cpp b/src/vmci.cpp index 8d79feaadd..4edd096bec 100644 --- a/src/vmci.cpp +++ b/src/vmci.cpp @@ -35,13 +35,18 @@ #include #include -void zmq::tune_vmci_buffer_size (ctx_t *context_, fd_t sockfd_, uint64_t default_size_, uint64_t min_size_, uint64_t max_size_) +void zmq::tune_vmci_buffer_size (ctx_t *context_, + fd_t sockfd_, + uint64_t default_size_, + uint64_t min_size_, + uint64_t max_size_) { int family = context_->get_vmci_socket_family (); assert (family != -1); if (default_size_ != 0) { - int rc = setsockopt (sockfd_, family, SO_VMCI_BUFFER_SIZE, (char*) &default_size_, sizeof default_size_); + int rc = setsockopt (sockfd_, family, SO_VMCI_BUFFER_SIZE, + (char *) &default_size_, sizeof default_size_); #if defined ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); #else @@ -50,7 +55,8 @@ void zmq::tune_vmci_buffer_size (ctx_t *context_, fd_t sockfd_, uint64_t default } if (min_size_ != 0) { - int rc = setsockopt (sockfd_, family, SO_VMCI_BUFFER_SIZE, (char*) &min_size_, sizeof min_size_); + int rc = setsockopt (sockfd_, family, SO_VMCI_BUFFER_SIZE, + (char *) &min_size_, sizeof min_size_); #if defined ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); #else @@ -59,7 +65,8 @@ void zmq::tune_vmci_buffer_size (ctx_t *context_, fd_t sockfd_, uint64_t default } if (max_size_ != 0) { - int rc = setsockopt (sockfd_, family, SO_VMCI_BUFFER_SIZE, (char*) &max_size_, sizeof max_size_); + int rc = setsockopt (sockfd_, family, SO_VMCI_BUFFER_SIZE, + (char *) &max_size_, sizeof max_size_); #if defined ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); #else @@ -69,15 +76,20 @@ void zmq::tune_vmci_buffer_size (ctx_t *context_, fd_t sockfd_, uint64_t default } #if defined ZMQ_HAVE_WINDOWS -void zmq::tune_vmci_connect_timeout (ctx_t *context_, fd_t sockfd_, DWORD timeout_) +void zmq::tune_vmci_connect_timeout (ctx_t *context_, + fd_t sockfd_, + DWORD timeout_) #else -void zmq::tune_vmci_connect_timeout (ctx_t *context_, fd_t sockfd_, struct timeval timeout_) +void zmq::tune_vmci_connect_timeout (ctx_t *context_, + fd_t sockfd_, + struct timeval timeout_) #endif { int family = context_->get_vmci_socket_family (); assert (family != -1); - int rc = setsockopt (sockfd_, family, SO_VMCI_CONNECT_TIMEOUT, (char*) &timeout_, sizeof timeout_); + int rc = setsockopt (sockfd_, family, SO_VMCI_CONNECT_TIMEOUT, + (char *) &timeout_, sizeof timeout_); #if defined ZMQ_HAVE_WINDOWS wsa_assert (rc != SOCKET_ERROR); #else diff --git a/src/vmci.hpp b/src/vmci.hpp index 77f1ff3d6a..16a0c7346a 100644 --- a/src/vmci.hpp +++ b/src/vmci.hpp @@ -46,12 +46,18 @@ namespace zmq { - void tune_vmci_buffer_size (ctx_t *context_, fd_t sockfd_, uint64_t default_size_, uint64_t min_size_, uint64_t max_size_); +void tune_vmci_buffer_size (ctx_t *context_, + fd_t sockfd_, + uint64_t default_size_, + uint64_t min_size_, + uint64_t max_size_); #if defined ZMQ_HAVE_WINDOWS - void tune_vmci_connect_timeout (ctx_t *context_, fd_t sockfd_, DWORD timeout_); +void tune_vmci_connect_timeout (ctx_t *context_, fd_t sockfd_, DWORD timeout_); #else - void tune_vmci_connect_timeout (ctx_t *context_, fd_t sockfd_, struct timeval timeout_); +void tune_vmci_connect_timeout (ctx_t *context_, + fd_t sockfd_, + struct timeval timeout_); #endif } diff --git a/src/vmci_address.cpp b/src/vmci_address.cpp index 841f61389c..cf97d99cbd 100644 --- a/src/vmci_address.cpp +++ b/src/vmci_address.cpp @@ -39,27 +39,28 @@ #include "err.hpp" -zmq::vmci_address_t::vmci_address_t(ctx_t *parent_) : - parent(parent_) +zmq::vmci_address_t::vmci_address_t (ctx_t *parent_) : parent (parent_) { memset (&address, 0, sizeof address); } -zmq::vmci_address_t::vmci_address_t(const sockaddr *sa, socklen_t sa_len, ctx_t *parent_) : - parent(parent_) +zmq::vmci_address_t::vmci_address_t (const sockaddr *sa, + socklen_t sa_len, + ctx_t *parent_) : + parent (parent_) { zmq_assert (sa && sa_len > 0); memset (&address, 0, sizeof address); - if (sa->sa_family == parent->get_vmci_socket_family()) - memcpy(&address, sa, sa_len); + if (sa->sa_family == parent->get_vmci_socket_family ()) + memcpy (&address, sa, sa_len); } zmq::vmci_address_t::~vmci_address_t () { } -int zmq::vmci_address_t::resolve(const char *path_) +int zmq::vmci_address_t::resolve (const char *path_) { // Find the ':' at end that separates address from the port number. const char *delimiter = strrchr (path_, ':'); @@ -75,25 +76,23 @@ int zmq::vmci_address_t::resolve(const char *path_) unsigned int cid = VMADDR_CID_ANY; unsigned int port = VMADDR_PORT_ANY; - if (!addr_str.length()) { + if (!addr_str.length ()) { errno = EINVAL; return -1; - } - else if (addr_str == "@") { - cid = VMCISock_GetLocalCID(); + } else if (addr_str == "@") { + cid = VMCISock_GetLocalCID (); if (cid == VMADDR_CID_ANY) { errno = ENODEV; return -1; } - } - else if (addr_str != "*" && addr_str != "-1") { - const char *begin = addr_str.c_str(); + } else if (addr_str != "*" && addr_str != "-1") { + const char *begin = addr_str.c_str (); char *end = NULL; - unsigned long l = strtoul(begin, &end, 10); + unsigned long l = strtoul (begin, &end, 10); - if ((l == 0 && end == begin) || (l == ULONG_MAX && errno == ERANGE) || l > UINT_MAX) - { + if ((l == 0 && end == begin) || (l == ULONG_MAX && errno == ERANGE) + || l > UINT_MAX) { errno = EINVAL; return -1; } @@ -101,16 +100,16 @@ int zmq::vmci_address_t::resolve(const char *path_) cid = static_cast (l); } - if (!port_str.length()) { + if (!port_str.length ()) { errno = EINVAL; return -1; - } - else if (port_str != "*" && port_str != "-1") { - const char *begin = port_str.c_str(); + } else if (port_str != "*" && port_str != "-1") { + const char *begin = port_str.c_str (); char *end = NULL; - unsigned long l = strtoul(begin, &end, 10); + unsigned long l = strtoul (begin, &end, 10); - if ((l == 0 && end == begin) || (l == ULONG_MAX && errno == ERANGE) || l > UINT_MAX) { + if ((l == 0 && end == begin) || (l == ULONG_MAX && errno == ERANGE) + || l > UINT_MAX) { errno = EINVAL; return -1; } @@ -118,7 +117,8 @@ int zmq::vmci_address_t::resolve(const char *path_) port = static_cast (l); } - address.svm_family = static_cast (parent->get_vmci_socket_family()); + address.svm_family = + static_cast (parent->get_vmci_socket_family ()); address.svm_cid = cid; address.svm_port = port; @@ -127,7 +127,7 @@ int zmq::vmci_address_t::resolve(const char *path_) int zmq::vmci_address_t::to_string (std::string &addr_) { - if (address.svm_family != parent->get_vmci_socket_family()) { + if (address.svm_family != parent->get_vmci_socket_family ()) { addr_.clear (); return -1; } @@ -138,9 +138,7 @@ int zmq::vmci_address_t::to_string (std::string &addr_) if (address.svm_cid == VMADDR_CID_ANY) { s << "*"; - } - else - { + } else { s << address.svm_cid; } @@ -148,8 +146,7 @@ int zmq::vmci_address_t::to_string (std::string &addr_) if (address.svm_port == VMADDR_PORT_ANY) { s << "*"; - } - else { + } else { s << address.svm_port; } @@ -159,7 +156,7 @@ int zmq::vmci_address_t::to_string (std::string &addr_) const sockaddr *zmq::vmci_address_t::addr () const { - return reinterpret_cast (&address); + return reinterpret_cast (&address); } socklen_t zmq::vmci_address_t::addrlen () const diff --git a/src/vmci_address.hpp b/src/vmci_address.hpp index 4ffea268ff..6684bf37c8 100644 --- a/src/vmci_address.hpp +++ b/src/vmci_address.hpp @@ -40,30 +40,30 @@ namespace zmq { - class vmci_address_t - { - public: - vmci_address_t (ctx_t *parent_); - vmci_address_t (const sockaddr *sa, socklen_t sa_len, ctx_t *parent_); - ~vmci_address_t (); - - // This function sets up the address for VMCI transport. - int resolve (const char *path_); - - // The opposite to resolve() - int to_string (std::string &addr_); - - const sockaddr *addr () const; - socklen_t addrlen () const; - - private: - struct sockaddr_vm address; - ctx_t *parent; - - vmci_address_t (); - vmci_address_t (const vmci_address_t&); - const vmci_address_t &operator = (const vmci_address_t&); - }; +class vmci_address_t +{ + public: + vmci_address_t (ctx_t *parent_); + vmci_address_t (const sockaddr *sa, socklen_t sa_len, ctx_t *parent_); + ~vmci_address_t (); + + // This function sets up the address for VMCI transport. + int resolve (const char *path_); + + // The opposite to resolve() + int to_string (std::string &addr_); + + const sockaddr *addr () const; + socklen_t addrlen () const; + + private: + struct sockaddr_vm address; + ctx_t *parent; + + vmci_address_t (); + vmci_address_t (const vmci_address_t &); + const vmci_address_t &operator= (const vmci_address_t &); +}; } #endif diff --git a/src/vmci_connecter.cpp b/src/vmci_connecter.cpp index 541818c613..c6863dbc0a 100644 --- a/src/vmci_connecter.cpp +++ b/src/vmci_connecter.cpp @@ -47,8 +47,10 @@ #include "vmci.hpp" zmq::vmci_connecter_t::vmci_connecter_t (class io_thread_t *io_thread_, - class session_base_t *session_, const options_t &options_, - const address_t *addr_, bool delayed_start_) : + class session_base_t *session_, + const options_t &options_, + const address_t *addr_, + bool delayed_start_) : own_t (io_thread_, options_), io_object_t (io_thread_), addr (addr_), @@ -57,12 +59,12 @@ zmq::vmci_connecter_t::vmci_connecter_t (class io_thread_t *io_thread_, delayed_start (delayed_start_), timer_started (false), session (session_), - current_reconnect_ivl(options.reconnect_ivl) + current_reconnect_ivl (options.reconnect_ivl) { zmq_assert (addr); zmq_assert (addr->protocol == "vmci"); addr->to_string (endpoint); - socket = session-> get_socket(); + socket = session->get_socket (); } zmq::vmci_connecter_t::~vmci_connecter_t () @@ -115,17 +117,18 @@ void zmq::vmci_connecter_t::out_event () // Handle the error condition by attempt to reconnect. if (fd == retired_fd) { close (); - add_reconnect_timer(); + add_reconnect_timer (); return; } tune_vmci_buffer_size (this->get_ctx (), fd, options.vmci_buffer_size, - options.vmci_buffer_min_size, options.vmci_buffer_max_size); + options.vmci_buffer_min_size, + options.vmci_buffer_max_size); - if (options.vmci_connect_timeout > 0) - { + if (options.vmci_connect_timeout > 0) { #if defined ZMQ_HAVE_WINDOWS - tune_vmci_connect_timeout (this->get_ctx (), fd, options.vmci_connect_timeout); + tune_vmci_connect_timeout (this->get_ctx (), fd, + options.vmci_connect_timeout); #else struct timeval timeout = {0, options.vmci_connect_timeout * 1000}; tune_vmci_connect_timeout (this->get_ctx (), fd, timeout); @@ -133,8 +136,8 @@ void zmq::vmci_connecter_t::out_event () } // Create the engine object for this connection. - stream_engine_t *engine = new (std::nothrow) - stream_engine_t (fd, options, endpoint); + stream_engine_t *engine = + new (std::nothrow) stream_engine_t (fd, options, endpoint); alloc_assert (engine); // Attach the engine to the corresponding session object. @@ -173,9 +176,9 @@ void zmq::vmci_connecter_t::start_connecting () } } -void zmq::vmci_connecter_t::add_reconnect_timer() +void zmq::vmci_connecter_t::add_reconnect_timer () { - int rc_ivl = get_new_reconnect_ivl(); + int rc_ivl = get_new_reconnect_ivl (); add_timer (rc_ivl, reconnect_timer_id); socket->event_connect_retried (endpoint, rc_ivl); timer_started = true; @@ -184,17 +187,16 @@ void zmq::vmci_connecter_t::add_reconnect_timer() int zmq::vmci_connecter_t::get_new_reconnect_ivl () { // The new interval is the current interval + random value. - int this_interval = current_reconnect_ivl + - (generate_random () % options.reconnect_ivl); + int this_interval = + current_reconnect_ivl + (generate_random () % options.reconnect_ivl); // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. - if (options.reconnect_ivl_max > 0 && - options.reconnect_ivl_max > options.reconnect_ivl) { - + if (options.reconnect_ivl_max > 0 + && options.reconnect_ivl_max > options.reconnect_ivl) { // Calculate the next interval current_reconnect_ivl = current_reconnect_ivl * 2; - if(current_reconnect_ivl >= options.reconnect_ivl_max) { + if (current_reconnect_ivl >= options.reconnect_ivl_max) { current_reconnect_ivl = options.reconnect_ivl_max; } } @@ -213,7 +215,7 @@ int zmq::vmci_connecter_t::open () s = open_socket (family, SOCK_STREAM, 0); #ifdef ZMQ_HAVE_WINDOWS if (s == INVALID_SOCKET) { - errno = wsa_error_to_errno(WSAGetLastError()); + errno = wsa_error_to_errno (WSAGetLastError ()); return -1; } #else @@ -222,9 +224,8 @@ int zmq::vmci_connecter_t::open () #endif // Connect to the remote peer. - int rc = ::connect ( - s, addr->resolved.vmci_addr->addr (), - addr->resolved.vmci_addr->addrlen ()); + int rc = ::connect (s, addr->resolved.vmci_addr->addr (), + addr->resolved.vmci_addr->addrlen ()); // Connect was successful immediately. if (rc == 0) @@ -258,25 +259,19 @@ zmq::fd_t zmq::vmci_connecter_t::connect () #else socklen_t len = sizeof (err); #endif - int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char*) &err, &len); + int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char *) &err, &len); // Assert if the error was caused by 0MQ bug. // Networking problems are OK. No need to assert. #ifdef ZMQ_HAVE_WINDOWS - zmq_assert(rc == 0); + zmq_assert (rc == 0); if (err != 0) { - if (err != WSAECONNREFUSED - && err != WSAETIMEDOUT - && err != WSAECONNABORTED - && err != WSAEHOSTUNREACH - && err != WSAENETUNREACH - && err != WSAENETDOWN - && err != WSAEACCES - && err != WSAEINVAL - && err != WSAEADDRINUSE - && err != WSAECONNRESET) - { - wsa_assert_no(err); + if (err != WSAECONNREFUSED && err != WSAETIMEDOUT + && err != WSAECONNABORTED && err != WSAEHOSTUNREACH + && err != WSAENETUNREACH && err != WSAENETDOWN && err != WSAEACCES + && err != WSAEINVAL && err != WSAEADDRINUSE + && err != WSAECONNRESET) { + wsa_assert_no (err); } return retired_fd; } @@ -287,14 +282,10 @@ zmq::fd_t zmq::vmci_connecter_t::connect () err = errno; if (err != 0) { errno = err; - errno_assert( - errno == ECONNREFUSED || - errno == ECONNRESET || - errno == ETIMEDOUT || - errno == EHOSTUNREACH || - errno == ENETUNREACH || - errno == ENETDOWN || - errno == EINVAL); + errno_assert (errno == ECONNREFUSED || errno == ECONNRESET + || errno == ETIMEDOUT || errno == EHOSTUNREACH + || errno == ENETUNREACH || errno == ENETDOWN + || errno == EINVAL); return retired_fd; } #endif diff --git a/src/vmci_connecter.hpp b/src/vmci_connecter.hpp index 56483aebb0..19276b5f37 100644 --- a/src/vmci_connecter.hpp +++ b/src/vmci_connecter.hpp @@ -41,96 +41,97 @@ namespace zmq { +class io_thread_t; +class session_base_t; +struct address_t; - class io_thread_t; - class session_base_t; - struct address_t; - - class vmci_connecter_t : public own_t, public io_object_t +class vmci_connecter_t : public own_t, public io_object_t +{ + public: + // If 'delayed_start' is true connecter first waits for a while, + // then starts connection process. + vmci_connecter_t (zmq::io_thread_t *io_thread_, + zmq::session_base_t *session_, + const options_t &options_, + const address_t *addr_, + bool delayed_start_); + ~vmci_connecter_t (); + + private: + // ID of the timer used to delay the reconnection. + enum { - public: - - // If 'delayed_start' is true connecter first waits for a while, - // then starts connection process. - vmci_connecter_t (zmq::io_thread_t *io_thread_, - zmq::session_base_t *session_, const options_t &options_, - const address_t *addr_, bool delayed_start_); - ~vmci_connecter_t (); - - private: - - // ID of the timer used to delay the reconnection. - enum {reconnect_timer_id = 1}; + reconnect_timer_id = 1 + }; - // Handlers for incoming commands. - void process_plug (); - void process_term (int linger_); + // Handlers for incoming commands. + void process_plug (); + void process_term (int linger_); - // Handlers for I/O events. - void in_event (); - void out_event (); - void timer_event (int id_); + // Handlers for I/O events. + void in_event (); + void out_event (); + void timer_event (int id_); - // Internal function to start the actual connection establishment. - void start_connecting (); + // Internal function to start the actual connection establishment. + void start_connecting (); - // Internal function to add a reconnect timer - void add_reconnect_timer(); + // Internal function to add a reconnect timer + void add_reconnect_timer (); - // Internal function to return a reconnect backoff delay. - // Will modify the current_reconnect_ivl used for next call - // Returns the currently used interval - int get_new_reconnect_ivl (); + // Internal function to return a reconnect backoff delay. + // Will modify the current_reconnect_ivl used for next call + // Returns the currently used interval + int get_new_reconnect_ivl (); - // Open VMCI connecting socket. Returns -1 in case of error, - // 0 if connect was successful immediately. Returns -1 with - // EAGAIN errno if async connect was launched. - int open (); + // Open VMCI connecting socket. Returns -1 in case of error, + // 0 if connect was successful immediately. Returns -1 with + // EAGAIN errno if async connect was launched. + int open (); - // Close the connecting socket. - void close (); + // Close the connecting socket. + void close (); - // Get the file descriptor of newly created connection. Returns - // retired_fd if the connection was unsuccessful. - fd_t connect (); + // Get the file descriptor of newly created connection. Returns + // retired_fd if the connection was unsuccessful. + fd_t connect (); - // Address to connect to. Owned by session_base_t. - const address_t *addr; + // Address to connect to. Owned by session_base_t. + const address_t *addr; - // Underlying socket. - fd_t s; + // Underlying socket. + fd_t s; - // Handle corresponding to the listening socket. - handle_t handle; + // Handle corresponding to the listening socket. + handle_t handle; - // If true file descriptor is registered with the poller and 'handle' - // contains valid value. - bool handle_valid; + // If true file descriptor is registered with the poller and 'handle' + // contains valid value. + bool handle_valid; - // If true, connecter is waiting a while before trying to connect. - const bool delayed_start; + // If true, connecter is waiting a while before trying to connect. + const bool delayed_start; - // True iff a timer has been started. - bool timer_started; + // True iff a timer has been started. + bool timer_started; - // Reference to the session we belong to. - zmq::session_base_t *session; + // Reference to the session we belong to. + zmq::session_base_t *session; - // Current reconnect ivl, updated for backoff strategy - int current_reconnect_ivl; + // Current reconnect ivl, updated for backoff strategy + int current_reconnect_ivl; - // String representation of endpoint to connect to - std::string endpoint; + // String representation of endpoint to connect to + std::string endpoint; - // Socket - zmq::socket_base_t *socket; + // Socket + zmq::socket_base_t *socket; - vmci_connecter_t (const vmci_connecter_t&); - const vmci_connecter_t &operator = (const vmci_connecter_t&); - }; + vmci_connecter_t (const vmci_connecter_t &); + const vmci_connecter_t &operator= (const vmci_connecter_t &); +}; } #endif #endif - diff --git a/src/vmci_listener.cpp b/src/vmci_listener.cpp index 545f2305b6..207f60f17c 100644 --- a/src/vmci_listener.cpp +++ b/src/vmci_listener.cpp @@ -53,7 +53,8 @@ #endif zmq::vmci_listener_t::vmci_listener_t (io_thread_t *io_thread_, - socket_base_t *socket_, const options_t &options_) : + socket_base_t *socket_, + const options_t &options_) : own_t (io_thread_, options_), io_object_t (io_thread_), s (retired_fd), @@ -86,16 +87,18 @@ void zmq::vmci_listener_t::in_event () // If connection was reset by the peer in the meantime, just ignore it. if (fd == retired_fd) { - socket->event_accept_failed (endpoint, zmq_errno()); + socket->event_accept_failed (endpoint, zmq_errno ()); return; } - tune_vmci_buffer_size (this->get_ctx (), fd, options.vmci_buffer_size, options.vmci_buffer_min_size, options.vmci_buffer_max_size); + tune_vmci_buffer_size (this->get_ctx (), fd, options.vmci_buffer_size, + options.vmci_buffer_min_size, + options.vmci_buffer_max_size); - if (options.vmci_connect_timeout > 0) - { + if (options.vmci_connect_timeout > 0) { #if defined ZMQ_HAVE_WINDOWS - tune_vmci_connect_timeout (this->get_ctx (), fd, options.vmci_connect_timeout); + tune_vmci_connect_timeout (this->get_ctx (), fd, + options.vmci_connect_timeout); #else struct timeval timeout = {0, options.vmci_connect_timeout * 1000}; tune_vmci_connect_timeout (this->get_ctx (), fd, timeout); @@ -103,8 +106,8 @@ void zmq::vmci_listener_t::in_event () } // Create the engine object for this connection. - stream_engine_t *engine = new (std::nothrow) - stream_engine_t (fd, options, endpoint); + stream_engine_t *engine = + new (std::nothrow) stream_engine_t (fd, options, endpoint); alloc_assert (engine); // Choose I/O thread to run connecter in. Given that we are already @@ -113,8 +116,8 @@ void zmq::vmci_listener_t::in_event () zmq_assert (io_thread); // Create and launch a session object. - session_base_t *session = session_base_t::create (io_thread, false, socket, - options, NULL); + session_base_t *session = + session_base_t::create (io_thread, false, socket, options, NULL); errno_assert (session); session->inc_seqnum (); launch_child (session); @@ -146,22 +149,23 @@ int zmq::vmci_listener_t::set_address (const char *addr_) std::string addr (addr_); // Initialise the address structure. - vmci_address_t address(this->get_ctx ()); - int rc = address.resolve (addr.c_str()); + vmci_address_t address (this->get_ctx ()); + int rc = address.resolve (addr.c_str ()); if (rc != 0) return -1; // Create a listening socket. - s = open_socket (this->get_ctx ()->get_vmci_socket_family (), SOCK_STREAM, 0); + s = + open_socket (this->get_ctx ()->get_vmci_socket_family (), SOCK_STREAM, 0); #ifdef ZMQ_HAVE_WINDOWS if (s == INVALID_SOCKET) { - errno = wsa_error_to_errno(WSAGetLastError()); + errno = wsa_error_to_errno (WSAGetLastError ()); return -1; } #if !defined _WIN32_WCE // On Windows, preventing sockets to be inherited by child processes. - BOOL brc = SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0); - win_assert(brc); + BOOL brc = SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0); + win_assert (brc); #endif #else if (s == -1) @@ -174,7 +178,7 @@ int zmq::vmci_listener_t::set_address (const char *addr_) rc = bind (s, address.addr (), address.addrlen ()); #ifdef ZMQ_HAVE_WINDOWS if (rc == SOCKET_ERROR) { - errno = wsa_error_to_errno(WSAGetLastError()); + errno = wsa_error_to_errno (WSAGetLastError ()); goto error; } #else @@ -186,7 +190,7 @@ int zmq::vmci_listener_t::set_address (const char *addr_) rc = listen (s, options.backlog); #ifdef ZMQ_HAVE_WINDOWS if (rc == SOCKET_ERROR) { - errno = wsa_error_to_errno(WSAGetLastError()); + errno = wsa_error_to_errno (WSAGetLastError ()); goto error; } #else @@ -197,7 +201,7 @@ int zmq::vmci_listener_t::set_address (const char *addr_) socket->event_listening (endpoint, s); return 0; - error: +error: int err = errno; close (); errno = err; @@ -228,23 +232,23 @@ zmq::fd_t zmq::vmci_listener_t::accept () #ifdef ZMQ_HAVE_WINDOWS if (sock == INVALID_SOCKET) { - wsa_assert(WSAGetLastError() == WSAEWOULDBLOCK || - WSAGetLastError() == WSAECONNRESET || - WSAGetLastError() == WSAEMFILE || - WSAGetLastError() == WSAENOBUFS); + wsa_assert (WSAGetLastError () == WSAEWOULDBLOCK + || WSAGetLastError () == WSAECONNRESET + || WSAGetLastError () == WSAEMFILE + || WSAGetLastError () == WSAENOBUFS); return retired_fd; } #if !defined _WIN32_WCE // On Windows, preventing sockets to be inherited by child processes. - BOOL brc = SetHandleInformation((HANDLE)sock, HANDLE_FLAG_INHERIT, 0); - win_assert(brc); + BOOL brc = SetHandleInformation ((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); + win_assert (brc); #endif #else if (sock == -1) { - errno_assert(errno == EAGAIN || errno == EWOULDBLOCK || - errno == EINTR || errno == ECONNABORTED || errno == EPROTO || - errno == ENOBUFS || errno == ENOMEM || errno == EMFILE || - errno == ENFILE); + errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR + || errno == ECONNABORTED || errno == EPROTO + || errno == ENOBUFS || errno == ENOMEM || errno == EMFILE + || errno == ENFILE); return retired_fd; } #endif diff --git a/src/vmci_listener.hpp b/src/vmci_listener.hpp index 658ab13d64..0f49fce624 100644 --- a/src/vmci_listener.hpp +++ b/src/vmci_listener.hpp @@ -43,60 +43,56 @@ namespace zmq { +class io_thread_t; +class socket_base_t; - class io_thread_t; - class socket_base_t; - - class vmci_listener_t : public own_t, public io_object_t - { - public: - - vmci_listener_t (zmq::io_thread_t *io_thread_, - zmq::socket_base_t *socket_, const options_t &options_); - ~vmci_listener_t (); - - // Set address to listen on. - int set_address (const char *addr_); - - // Get the bound address for use with wildcards - int get_address (std::string &addr_); +class vmci_listener_t : public own_t, public io_object_t +{ + public: + vmci_listener_t (zmq::io_thread_t *io_thread_, + zmq::socket_base_t *socket_, + const options_t &options_); + ~vmci_listener_t (); - private: + // Set address to listen on. + int set_address (const char *addr_); - // Handlers for incoming commands. - void process_plug (); - void process_term (int linger_); + // Get the bound address for use with wildcards + int get_address (std::string &addr_); - // Handlers for I/O events. - void in_event (); + private: + // Handlers for incoming commands. + void process_plug (); + void process_term (int linger_); - // Close the listening socket. - void close (); + // Handlers for I/O events. + void in_event (); - // Accept the new connection. Returns the file descriptor of the - // newly created connection. The function may return retired_fd - // if the connection was dropped while waiting in the listen backlog. - fd_t accept (); + // Close the listening socket. + void close (); - // Underlying socket. - fd_t s; + // Accept the new connection. Returns the file descriptor of the + // newly created connection. The function may return retired_fd + // if the connection was dropped while waiting in the listen backlog. + fd_t accept (); - // Handle corresponding to the listening socket. - handle_t handle; + // Underlying socket. + fd_t s; - // Socket the listerner belongs to. - zmq::socket_base_t *socket; + // Handle corresponding to the listening socket. + handle_t handle; - // String representation of endpoint to bind to - std::string endpoint; + // Socket the listerner belongs to. + zmq::socket_base_t *socket; - vmci_listener_t (const vmci_listener_t&); - const vmci_listener_t &operator = (const vmci_listener_t&); - }; + // String representation of endpoint to bind to + std::string endpoint; + vmci_listener_t (const vmci_listener_t &); + const vmci_listener_t &operator= (const vmci_listener_t &); +}; } #endif #endif - diff --git a/src/windows.hpp b/src/windows.hpp index 73e280e8e3..6c3839fd28 100644 --- a/src/windows.hpp +++ b/src/windows.hpp @@ -34,7 +34,7 @@ #define _CRT_SECURE_NO_WARNINGS #endif #ifndef NOMINMAX -#define NOMINMAX // Macros min(a,b) and max(a,b) +#define NOMINMAX // Macros min(a,b) and max(a,b) #endif // Set target version to Windows Server 2008, Windows Vista or higher. @@ -44,12 +44,12 @@ #endif #if defined ZMQ_HAVE_WINDOWS_UWP -#define _WIN32_WINNT _WIN32_WINNT_WIN10 +#define _WIN32_WINNT _WIN32_WINNT_WIN10 #endif #ifdef __MINGW32__ // Require Windows XP or higher with MinGW for getaddrinfo(). -#if(_WIN32_WINNT >= 0x0501) +#if (_WIN32_WINNT >= 0x0501) #else #error You need at least Windows XP target #endif @@ -66,14 +66,15 @@ // Workaround missing mstcpip.h in mingw32 (MinGW64 provides this) // __MINGW64_VERSION_MAJOR is only defined when using in mingw-w64 -#if defined __MINGW32__ && !defined SIO_KEEPALIVE_VALS && \ - !defined __MINGW64_VERSION_MAJOR -struct tcp_keepalive { +#if defined __MINGW32__ && !defined SIO_KEEPALIVE_VALS \ + && !defined __MINGW64_VERSION_MAJOR +struct tcp_keepalive +{ u_long onoff; u_long keepalivetime; u_long keepaliveinterval; }; -#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4) +#define SIO_KEEPALIVE_VALS _WSAIOW (IOC_VENDOR, 4) #endif #include @@ -83,7 +84,10 @@ struct tcp_keepalive { #endif #if defined ZMQ_USE_POLL -static inline int poll(struct pollfd *pfd, unsigned long nfds, int timeout) { return WSAPoll(pfd, nfds, timeout); } +static inline int poll (struct pollfd *pfd, unsigned long nfds, int timeout) +{ + return WSAPoll (pfd, nfds, timeout); +} #endif // In MinGW environment AI_NUMERICSERV is not defined. diff --git a/src/wire.hpp b/src/wire.hpp index 95a30e7625..f3158885f8 100644 --- a/src/wire.hpp +++ b/src/wire.hpp @@ -34,75 +34,63 @@ namespace zmq { +// Helper functions to convert different integer types to/from network +// byte order. - // Helper functions to convert different integer types to/from network - // byte order. - - inline void put_uint8 (unsigned char *buffer_, uint8_t value) - { - *buffer_ = value; - } - - inline uint8_t get_uint8 (const unsigned char *buffer_) - { - return *buffer_; - } - - inline void put_uint16 (unsigned char *buffer_, uint16_t value) - { - buffer_ [0] = (unsigned char) (((value) >> 8) & 0xff); - buffer_ [1] = (unsigned char) (value & 0xff); - } - - inline uint16_t get_uint16 (const unsigned char *buffer_) - { - return - (((uint16_t) buffer_ [0]) << 8) | - ((uint16_t) buffer_ [1]); - } - - inline void put_uint32 (unsigned char *buffer_, uint32_t value) - { - buffer_ [0] = (unsigned char) (((value) >> 24) & 0xff); - buffer_ [1] = (unsigned char) (((value) >> 16) & 0xff); - buffer_ [2] = (unsigned char) (((value) >> 8) & 0xff); - buffer_ [3] = (unsigned char) (value & 0xff); - } - - inline uint32_t get_uint32 (const unsigned char *buffer_) - { - return - (((uint32_t) buffer_ [0]) << 24) | - (((uint32_t) buffer_ [1]) << 16) | - (((uint32_t) buffer_ [2]) << 8) | - ((uint32_t) buffer_ [3]); - } - - inline void put_uint64 (unsigned char *buffer_, uint64_t value) - { - buffer_ [0] = (unsigned char) (((value) >> 56) & 0xff); - buffer_ [1] = (unsigned char) (((value) >> 48) & 0xff); - buffer_ [2] = (unsigned char) (((value) >> 40) & 0xff); - buffer_ [3] = (unsigned char) (((value) >> 32) & 0xff); - buffer_ [4] = (unsigned char) (((value) >> 24) & 0xff); - buffer_ [5] = (unsigned char) (((value) >> 16) & 0xff); - buffer_ [6] = (unsigned char) (((value) >> 8) & 0xff); - buffer_ [7] = (unsigned char) (value & 0xff); - } - - inline uint64_t get_uint64 (const unsigned char *buffer_) - { - return - (((uint64_t) buffer_ [0]) << 56) | - (((uint64_t) buffer_ [1]) << 48) | - (((uint64_t) buffer_ [2]) << 40) | - (((uint64_t) buffer_ [3]) << 32) | - (((uint64_t) buffer_ [4]) << 24) | - (((uint64_t) buffer_ [5]) << 16) | - (((uint64_t) buffer_ [6]) << 8) | - ((uint64_t) buffer_ [7]); - } +inline void put_uint8 (unsigned char *buffer_, uint8_t value) +{ + *buffer_ = value; +} + +inline uint8_t get_uint8 (const unsigned char *buffer_) +{ + return *buffer_; +} + +inline void put_uint16 (unsigned char *buffer_, uint16_t value) +{ + buffer_[0] = (unsigned char) (((value) >> 8) & 0xff); + buffer_[1] = (unsigned char) (value & 0xff); +} + +inline uint16_t get_uint16 (const unsigned char *buffer_) +{ + return (((uint16_t) buffer_[0]) << 8) | ((uint16_t) buffer_[1]); +} +inline void put_uint32 (unsigned char *buffer_, uint32_t value) +{ + buffer_[0] = (unsigned char) (((value) >> 24) & 0xff); + buffer_[1] = (unsigned char) (((value) >> 16) & 0xff); + buffer_[2] = (unsigned char) (((value) >> 8) & 0xff); + buffer_[3] = (unsigned char) (value & 0xff); +} + +inline uint32_t get_uint32 (const unsigned char *buffer_) +{ + return (((uint32_t) buffer_[0]) << 24) | (((uint32_t) buffer_[1]) << 16) + | (((uint32_t) buffer_[2]) << 8) | ((uint32_t) buffer_[3]); +} + +inline void put_uint64 (unsigned char *buffer_, uint64_t value) +{ + buffer_[0] = (unsigned char) (((value) >> 56) & 0xff); + buffer_[1] = (unsigned char) (((value) >> 48) & 0xff); + buffer_[2] = (unsigned char) (((value) >> 40) & 0xff); + buffer_[3] = (unsigned char) (((value) >> 32) & 0xff); + buffer_[4] = (unsigned char) (((value) >> 24) & 0xff); + buffer_[5] = (unsigned char) (((value) >> 16) & 0xff); + buffer_[6] = (unsigned char) (((value) >> 8) & 0xff); + buffer_[7] = (unsigned char) (value & 0xff); +} + +inline uint64_t get_uint64 (const unsigned char *buffer_) +{ + return (((uint64_t) buffer_[0]) << 56) | (((uint64_t) buffer_[1]) << 48) + | (((uint64_t) buffer_[2]) << 40) | (((uint64_t) buffer_[3]) << 32) + | (((uint64_t) buffer_[4]) << 24) | (((uint64_t) buffer_[5]) << 16) + | (((uint64_t) buffer_[6]) << 8) | ((uint64_t) buffer_[7]); +} } #endif diff --git a/src/xpub.cpp b/src/xpub.cpp index 7a99dff2fd..b63491cc29 100644 --- a/src/xpub.cpp +++ b/src/xpub.cpp @@ -67,8 +67,7 @@ void zmq::xpub_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_) subscriptions.add (NULL, 0, pipe_); // if welcome message exists, send a copy of it - if (welcome_msg.size () > 0) - { + if (welcome_msg.size () > 0) { msg_t copy; copy.init (); int rc = copy.copy (welcome_msg); @@ -91,10 +90,9 @@ void zmq::xpub_t::xread_activated (pipe_t *pipe_) // Apply the subscription to the trie unsigned char *const data = (unsigned char *) sub.data (); const size_t size = sub.size (); - metadata_t* metadata = sub.metadata(); + metadata_t *metadata = sub.metadata (); if (size > 0 && (*data == 0 || *data == 1)) { - if (manual) - { + if (manual) { // Store manual subscription to use on termination if (*data == 0) manual_subscriptions.rm (data + 1, size - 1, pipe_); @@ -107,9 +105,7 @@ void zmq::xpub_t::xread_activated (pipe_t *pipe_) metadata->add_ref (); pending_metadata.push_back (metadata); pending_flags.push_back (0); - } - else - { + } else { bool unique; if (*data == 0) unique = subscriptions.rm (data + 1, size - 1, pipe_); @@ -119,17 +115,17 @@ void zmq::xpub_t::xread_activated (pipe_t *pipe_) // If the (un)subscription is not a duplicate store it so that it can be // passed to the user on next recv call unless verbose mode is enabled // which makes to pass always these messages. - if (options.type == ZMQ_XPUB && (unique || (*data == 1 && verbose_subs) || - (*data == 0 && verbose_unsubs && verbose_subs))) { - pending_data.push_back (blob_t(data, size)); + if (options.type == ZMQ_XPUB + && (unique || (*data == 1 && verbose_subs) + || (*data == 0 && verbose_unsubs && verbose_subs))) { + pending_data.push_back (blob_t (data, size)); if (metadata) metadata->add_ref (); pending_metadata.push_back (metadata); pending_flags.push_back (0); } } - } - else { + } else { // Process user message coming upstream from xsub socket pending_data.push_back (blob_t (data, size)); if (metadata) @@ -146,58 +142,46 @@ void zmq::xpub_t::xwrite_activated (pipe_t *pipe_) dist.activated (pipe_); } -int zmq::xpub_t::xsetsockopt (int option_, const void *optval_, - size_t optvallen_) +int zmq::xpub_t::xsetsockopt (int option_, + const void *optval_, + size_t optvallen_) { - if (option_ == ZMQ_XPUB_VERBOSE - || option_ == ZMQ_XPUB_VERBOSER - || option_ == ZMQ_XPUB_NODROP - || option_ == ZMQ_XPUB_MANUAL) { - if (optvallen_ != sizeof (int) || *static_cast (optval_) < 0) { + if (option_ == ZMQ_XPUB_VERBOSE || option_ == ZMQ_XPUB_VERBOSER + || option_ == ZMQ_XPUB_NODROP || option_ == ZMQ_XPUB_MANUAL) { + if (optvallen_ != sizeof (int) + || *static_cast (optval_) < 0) { errno = EINVAL; return -1; } if (option_ == ZMQ_XPUB_VERBOSE) { - verbose_subs = (*static_cast (optval_) != 0); + verbose_subs = (*static_cast (optval_) != 0); verbose_unsubs = 0; - } - else - if (option_ == ZMQ_XPUB_VERBOSER) { - verbose_subs = (*static_cast (optval_) != 0); + } else if (option_ == ZMQ_XPUB_VERBOSER) { + verbose_subs = (*static_cast (optval_) != 0); verbose_unsubs = verbose_subs; - } - else - if (option_ == ZMQ_XPUB_NODROP) - lossy = (*static_cast (optval_) == 0); - else - if (option_ == ZMQ_XPUB_MANUAL) - manual = (*static_cast (optval_) != 0); - } - else - if (option_ == ZMQ_SUBSCRIBE && manual) { + } else if (option_ == ZMQ_XPUB_NODROP) + lossy = (*static_cast (optval_) == 0); + else if (option_ == ZMQ_XPUB_MANUAL) + manual = (*static_cast (optval_) != 0); + } else if (option_ == ZMQ_SUBSCRIBE && manual) { if (last_pipe != NULL) - subscriptions.add ((unsigned char *) optval_, optvallen_, last_pipe); - } - else - if (option_ == ZMQ_UNSUBSCRIBE && manual) { + subscriptions.add ((unsigned char *) optval_, optvallen_, + last_pipe); + } else if (option_ == ZMQ_UNSUBSCRIBE && manual) { if (last_pipe != NULL) subscriptions.rm ((unsigned char *) optval_, optvallen_, last_pipe); - } - else - if (option_ == ZMQ_XPUB_WELCOME_MSG) { + } else if (option_ == ZMQ_XPUB_WELCOME_MSG) { welcome_msg.close (); if (optvallen_ > 0) { int rc = welcome_msg.init_size (optvallen_); - errno_assert(rc == 0); + errno_assert (rc == 0); - unsigned char *data = (unsigned char*) welcome_msg.data (); + unsigned char *data = (unsigned char *) welcome_msg.data (); memcpy (data, optval_, optvallen_); - } - else + } else welcome_msg.init (); - } - else { + } else { errno = EINVAL; return -1; } @@ -206,15 +190,14 @@ int zmq::xpub_t::xsetsockopt (int option_, const void *optval_, static void stub (unsigned char *data_, size_t size_, void *arg_) { - LIBZMQ_UNUSED(data_); - LIBZMQ_UNUSED(size_); - LIBZMQ_UNUSED(arg_); + LIBZMQ_UNUSED (data_); + LIBZMQ_UNUSED (size_); + LIBZMQ_UNUSED (arg_); } void zmq::xpub_t::xpipe_terminated (pipe_t *pipe_) { - if (manual) - { + if (manual) { // Remove the pipe from the trie and send corresponding manual // unsubscriptions upstream. manual_subscriptions.rm (pipe_, send_unsubscription, this, false); @@ -222,9 +205,7 @@ void zmq::xpub_t::xpipe_terminated (pipe_t *pipe_) // care of by the manual call above. subscriptions is the real mtrie, // so the pipe must be removed from there or it will be left over. subscriptions.rm (pipe_, stub, NULL, false); - } - else - { + } else { // Remove the pipe from the trie. If there are topics that nobody // is interested in anymore, send corresponding unsubscriptions // upstream. @@ -236,7 +217,7 @@ void zmq::xpub_t::xpipe_terminated (pipe_t *pipe_) void zmq::xpub_t::mark_as_matching (pipe_t *pipe_, void *arg_) { - xpub_t *self = (xpub_t*) arg_; + xpub_t *self = (xpub_t *) arg_; self->dist.match (pipe_); } @@ -246,15 +227,15 @@ int zmq::xpub_t::xsend (msg_t *msg_) // For the first part of multi-part message, find the matching pipes. if (!more) { - subscriptions.match ((unsigned char*) msg_->data (), msg_->size (), - mark_as_matching, this); + subscriptions.match ((unsigned char *) msg_->data (), msg_->size (), + mark_as_matching, this); // If inverted matching is used, reverse the selection now if (options.invert_matching) { - dist.reverse_match(); + dist.reverse_match (); } } - int rc = -1; // Assume we fail + int rc = -1; // Assume we fail if (lossy || dist.check_hwm ()) { if (dist.send_to_matching (msg_) == 0) { // If we are at the end of multi-part message we can mark @@ -262,10 +243,9 @@ int zmq::xpub_t::xsend (msg_t *msg_) if (!msg_more) dist.unmatch (); more = msg_more; - rc = 0; // Yay, sent successfully + rc = 0; // Yay, sent successfully } - } - else + } else errno = EAGAIN; return rc; } @@ -293,15 +273,14 @@ int zmq::xpub_t::xrecv (msg_t *msg_) errno_assert (rc == 0); rc = msg_->init_size (pending_data.front ().size ()); errno_assert (rc == 0); - memcpy (msg_->data (), - pending_data.front ().data (), - pending_data.front ().size ()); + memcpy (msg_->data (), pending_data.front ().data (), + pending_data.front ().size ()); // set metadata only if there is some - if (metadata_t* metadata = pending_metadata.front ()) { + if (metadata_t *metadata = pending_metadata.front ()) { msg_->set_metadata (metadata); // Remove ref corresponding to vector placement - metadata->drop_ref(); + metadata->drop_ref (); } msg_->set_flags (pending_flags.front ()); @@ -316,19 +295,20 @@ bool zmq::xpub_t::xhas_in () return !pending_data.empty (); } -void zmq::xpub_t::send_unsubscription (unsigned char *data_, size_t size_, - void *arg_) +void zmq::xpub_t::send_unsubscription (unsigned char *data_, + size_t size_, + void *arg_) { - xpub_t *self = (xpub_t*) arg_; + xpub_t *self = (xpub_t *) arg_; if (self->options.type != ZMQ_PUB) { // Place the unsubscription to the queue of pending (un)subscriptions // to be retrieved by the user later on. blob_t unsub (size_ + 1); - *unsub.data() = 0; + *unsub.data () = 0; if (size_ > 0) - memcpy (unsub.data() + 1, data_, size_); - self->pending_data.ZMQ_PUSH_OR_EMPLACE_BACK (ZMQ_MOVE(unsub)); + memcpy (unsub.data () + 1, data_, size_); + self->pending_data.ZMQ_PUSH_OR_EMPLACE_BACK (ZMQ_MOVE (unsub)); self->pending_metadata.push_back (NULL); self->pending_flags.push_back (0); diff --git a/src/xpub.hpp b/src/xpub.hpp index 2dac4ea82d..9f3498c650 100644 --- a/src/xpub.hpp +++ b/src/xpub.hpp @@ -41,86 +41,81 @@ namespace zmq { +class ctx_t; +class msg_t; +class pipe_t; +class io_thread_t; - class ctx_t; - class msg_t; - class pipe_t; - class io_thread_t; - - class xpub_t : - public socket_base_t - { - public: - - xpub_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~xpub_t (); - - // Implementations of virtual functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_ = false); - int xsend (zmq::msg_t *msg_); - bool xhas_out (); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - int xsetsockopt (int option_, const void *optval_, size_t optvallen_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - - // Function to be applied to the trie to send all the subscriptions - // upstream. - static void send_unsubscription (unsigned char *data_, size_t size_, - void *arg_); - - // Function to be applied to each matching pipes. - static void mark_as_matching (zmq::pipe_t *pipe_, void *arg_); - - // List of all subscriptions mapped to corresponding pipes. - mtrie_t subscriptions; - - // List of manual subscriptions mapped to corresponding pipes. - mtrie_t manual_subscriptions; - - // Distributor of messages holding the list of outbound pipes. - dist_t dist; - - // If true, send all subscription messages upstream, not just - // unique ones - bool verbose_subs; - - // If true, send all unsubscription messages upstream, not just - // unique ones - bool verbose_unsubs; - - // True if we are in the middle of sending a multi-part message. - bool more; - - // Drop messages if HWM reached, otherwise return with EAGAIN - bool lossy; - - // Subscriptions will not bed added automatically, only after calling set option with ZMQ_SUBSCRIBE or ZMQ_UNSUBSCRIBE - bool manual; - - // Last pipe that sent subscription message, only used if xpub is on manual - pipe_t *last_pipe; - - // Pipes that sent subscriptions messages that have not yet been processed, only used if xpub is on manual - std::deque pending_pipes; - - // Welcome message to send to pipe when attached - msg_t welcome_msg; - - // List of pending (un)subscriptions, ie. those that were already - // applied to the trie, but not yet received by the user. - std::deque pending_data; - std::deque pending_metadata; - std::deque pending_flags; - - xpub_t (const xpub_t&); - const xpub_t &operator = (const xpub_t&); - }; - +class xpub_t : public socket_base_t +{ + public: + xpub_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~xpub_t (); + + // Implementations of virtual functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_ = false); + int xsend (zmq::msg_t *msg_); + bool xhas_out (); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + int xsetsockopt (int option_, const void *optval_, size_t optvallen_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + // Function to be applied to the trie to send all the subscriptions + // upstream. + static void + send_unsubscription (unsigned char *data_, size_t size_, void *arg_); + + // Function to be applied to each matching pipes. + static void mark_as_matching (zmq::pipe_t *pipe_, void *arg_); + + // List of all subscriptions mapped to corresponding pipes. + mtrie_t subscriptions; + + // List of manual subscriptions mapped to corresponding pipes. + mtrie_t manual_subscriptions; + + // Distributor of messages holding the list of outbound pipes. + dist_t dist; + + // If true, send all subscription messages upstream, not just + // unique ones + bool verbose_subs; + + // If true, send all unsubscription messages upstream, not just + // unique ones + bool verbose_unsubs; + + // True if we are in the middle of sending a multi-part message. + bool more; + + // Drop messages if HWM reached, otherwise return with EAGAIN + bool lossy; + + // Subscriptions will not bed added automatically, only after calling set option with ZMQ_SUBSCRIBE or ZMQ_UNSUBSCRIBE + bool manual; + + // Last pipe that sent subscription message, only used if xpub is on manual + pipe_t *last_pipe; + + // Pipes that sent subscriptions messages that have not yet been processed, only used if xpub is on manual + std::deque pending_pipes; + + // Welcome message to send to pipe when attached + msg_t welcome_msg; + + // List of pending (un)subscriptions, ie. those that were already + // applied to the trie, but not yet received by the user. + std::deque pending_data; + std::deque pending_metadata; + std::deque pending_flags; + + xpub_t (const xpub_t &); + const xpub_t &operator= (const xpub_t &); +}; } #endif diff --git a/src/xsub.cpp b/src/xsub.cpp index 2902b50333..6efb968be4 100644 --- a/src/xsub.cpp +++ b/src/xsub.cpp @@ -104,14 +104,11 @@ int zmq::xsub_t::xsend (msg_t *msg_) // when there are forwarding devices involved. subscriptions.add (data + 1, size - 1); return dist.send_to_all (msg_); - } - else - if (size > 0 && *data == 0) { + } else if (size > 0 && *data == 0) { // Process unsubscribe message if (subscriptions.rm (data + 1, size - 1)) return dist.send_to_all (msg_); - } - else + } else // User message sent upstream to XPUB socket return dist.send_to_all (msg_); @@ -145,7 +142,6 @@ int zmq::xsub_t::xrecv (msg_t *msg_) // stream of non-matching messages which breaks the non-blocking recv // semantics. while (true) { - // Get a message using fair queueing algorithm. int rc = fq.recv (msg_); @@ -184,7 +180,6 @@ bool zmq::xsub_t::xhas_in () // TODO: This can result in infinite loop in the case of continuous // stream of non-matching messages. while (true) { - // Get a message using fair queueing algorithm. int rc = fq.recv (&message); @@ -217,22 +212,24 @@ const zmq::blob_t &zmq::xsub_t::get_credential () const bool zmq::xsub_t::match (msg_t *msg_) { - bool matching = subscriptions.check ((unsigned char*) msg_->data (), msg_->size ()); + bool matching = + subscriptions.check ((unsigned char *) msg_->data (), msg_->size ()); return matching ^ options.invert_matching; } -void zmq::xsub_t::send_subscription (unsigned char *data_, size_t size_, - void *arg_) +void zmq::xsub_t::send_subscription (unsigned char *data_, + size_t size_, + void *arg_) { - pipe_t *pipe = (pipe_t*) arg_; + pipe_t *pipe = (pipe_t *) arg_; // Create the subscription message. msg_t msg; int rc = msg.init_size (size_ + 1); errno_assert (rc == 0); - unsigned char *data = (unsigned char*) msg.data (); - data [0] = 1; + unsigned char *data = (unsigned char *) msg.data (); + data[0] = 1; // We explicitly allow a NULL subscription with size zero if (size_) { diff --git a/src/xsub.hpp b/src/xsub.hpp index cc925f04fc..481292cdf4 100644 --- a/src/xsub.hpp +++ b/src/xsub.hpp @@ -38,66 +38,59 @@ namespace zmq { +class ctx_t; +class pipe_t; +class io_thread_t; - class ctx_t; - class pipe_t; - class io_thread_t; - - class xsub_t : - public socket_base_t - { - public: - - xsub_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); - ~xsub_t (); - - protected: - - // Overrides of functions from socket_base_t. - void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); - int xsend (zmq::msg_t *msg_); - bool xhas_out (); - int xrecv (zmq::msg_t *msg_); - bool xhas_in (); - const blob_t &get_credential () const; - void xread_activated (zmq::pipe_t *pipe_); - void xwrite_activated (zmq::pipe_t *pipe_); - void xhiccuped (pipe_t *pipe_); - void xpipe_terminated (zmq::pipe_t *pipe_); - - private: - - // Check whether the message matches at least one subscription. - bool match (zmq::msg_t *msg_); - - // Function to be applied to the trie to send all the subsciptions - // upstream. - static void send_subscription (unsigned char *data_, size_t size_, - void *arg_); - - // Fair queueing object for inbound pipes. - fq_t fq; - - // Object for distributing the subscriptions upstream. - dist_t dist; - - // The repository of subscriptions. - trie_t subscriptions; - - // If true, 'message' contains a matching message to return on the - // next recv call. - bool has_message; - msg_t message; - - // If true, part of a multipart message was already received, but - // there are following parts still waiting. - bool more; - - xsub_t (const xsub_t&); - const xsub_t &operator = (const xsub_t&); - }; - +class xsub_t : public socket_base_t +{ + public: + xsub_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); + ~xsub_t (); + + protected: + // Overrides of functions from socket_base_t. + void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); + int xsend (zmq::msg_t *msg_); + bool xhas_out (); + int xrecv (zmq::msg_t *msg_); + bool xhas_in (); + const blob_t &get_credential () const; + void xread_activated (zmq::pipe_t *pipe_); + void xwrite_activated (zmq::pipe_t *pipe_); + void xhiccuped (pipe_t *pipe_); + void xpipe_terminated (zmq::pipe_t *pipe_); + + private: + // Check whether the message matches at least one subscription. + bool match (zmq::msg_t *msg_); + + // Function to be applied to the trie to send all the subsciptions + // upstream. + static void + send_subscription (unsigned char *data_, size_t size_, void *arg_); + + // Fair queueing object for inbound pipes. + fq_t fq; + + // Object for distributing the subscriptions upstream. + dist_t dist; + + // The repository of subscriptions. + trie_t subscriptions; + + // If true, 'message' contains a matching message to return on the + // next recv call. + bool has_message; + msg_t message; + + // If true, part of a multipart message was already received, but + // there are following parts still waiting. + bool more; + + xsub_t (const xsub_t &); + const xsub_t &operator= (const xsub_t &); +}; } #endif - diff --git a/src/ypipe.hpp b/src/ypipe.hpp index 5321851640..146bd6d029 100644 --- a/src/ypipe.hpp +++ b/src/ypipe.hpp @@ -36,35 +36,31 @@ namespace zmq { - - // Lock-free queue implementation. - // Only a single thread can read from the pipe at any specific moment. - // Only a single thread can write to the pipe at any specific moment. - // T is the type of the object in the queue. - // N is granularity of the pipe, i.e. how many items are needed to - // perform next memory allocation. - - template class ypipe_t : public ypipe_base_t +// Lock-free queue implementation. +// Only a single thread can read from the pipe at any specific moment. +// Only a single thread can write to the pipe at any specific moment. +// T is the type of the object in the queue. +// N is granularity of the pipe, i.e. how many items are needed to +// perform next memory allocation. + +template class ypipe_t : public ypipe_base_t +{ + public: + // Initialises the pipe. + inline ypipe_t () { - public: - - // Initialises the pipe. - inline ypipe_t () - { - // Insert terminator element into the queue. - queue.push (); - - // Let all the pointers to point to the terminator. - // (unless pipe is dead, in which case c is set to NULL). - r = w = f = &queue.back (); - c.set (&queue.back ()); - } + // Insert terminator element into the queue. + queue.push (); - // The destructor doesn't have to be virtual. It is made virtual - // just to keep ICC and code checking tools from complaining. - inline virtual ~ypipe_t () - { - } + // Let all the pointers to point to the terminator. + // (unless pipe is dead, in which case c is set to NULL). + r = w = f = &queue.back (); + c.set (&queue.back ()); + } + + // The destructor doesn't have to be virtual. It is made virtual + // just to keep ICC and code checking tools from complaining. + inline virtual ~ypipe_t () {} // Following function (write) deliberately copies uninitialised data // when used with zmq_msg. Initialising the VSM body for @@ -75,144 +71,141 @@ namespace zmq #pragma message disable(UNINIT) #endif - // Write an item to the pipe. Don't flush it yet. If incomplete is - // set to true the item is assumed to be continued by items - // subsequently written to the pipe. Incomplete items are never - // flushed down the stream. - inline void write (const T &value_, bool incomplete_) - { - // Place the value to the queue, add new terminator element. - queue.back () = value_; - queue.push (); - - // Move the "flush up to here" poiter. - if (!incomplete_) - f = &queue.back (); - } + // Write an item to the pipe. Don't flush it yet. If incomplete is + // set to true the item is assumed to be continued by items + // subsequently written to the pipe. Incomplete items are never + // flushed down the stream. + inline void write (const T &value_, bool incomplete_) + { + // Place the value to the queue, add new terminator element. + queue.back () = value_; + queue.push (); + + // Move the "flush up to here" poiter. + if (!incomplete_) + f = &queue.back (); + } #ifdef ZMQ_HAVE_OPENVMS #pragma message restore #endif - // Pop an incomplete item from the pipe. Returns true if such - // item exists, false otherwise. - inline bool unwrite (T *value_) - { - if (f == &queue.back ()) - return false; - queue.unpush (); - *value_ = queue.back (); + // Pop an incomplete item from the pipe. Returns true if such + // item exists, false otherwise. + inline bool unwrite (T *value_) + { + if (f == &queue.back ()) + return false; + queue.unpush (); + *value_ = queue.back (); + return true; + } + + // Flush all the completed items into the pipe. Returns false if + // the reader thread is sleeping. In that case, caller is obliged to + // wake the reader up before using the pipe again. + inline bool flush () + { + // If there are no un-flushed items, do nothing. + if (w == f) return true; - } - // Flush all the completed items into the pipe. Returns false if - // the reader thread is sleeping. In that case, caller is obliged to - // wake the reader up before using the pipe again. - inline bool flush () - { - // If there are no un-flushed items, do nothing. - if (w == f) - return true; - - // Try to set 'c' to 'f'. - if (c.cas (w, f) != w) { - - // Compare-and-swap was unseccessful because 'c' is NULL. - // This means that the reader is asleep. Therefore we don't - // care about thread-safeness and update c in non-atomic - // manner. We'll return false to let the caller know - // that reader is sleeping. - c.set (f); - w = f; - return false; - } - - // Reader is alive. Nothing special to do now. Just move - // the 'first un-flushed item' pointer to 'f'. + // Try to set 'c' to 'f'. + if (c.cas (w, f) != w) { + // Compare-and-swap was unseccessful because 'c' is NULL. + // This means that the reader is asleep. Therefore we don't + // care about thread-safeness and update c in non-atomic + // manner. We'll return false to let the caller know + // that reader is sleeping. + c.set (f); w = f; - return true; + return false; } - // Check whether item is available for reading. - inline bool check_read () - { - // Was the value prefetched already? If so, return. - if (&queue.front () != r && r) - return true; - - // There's no prefetched value, so let us prefetch more values. - // Prefetching is to simply retrieve the - // pointer from c in atomic fashion. If there are no - // items to prefetch, set c to NULL (using compare-and-swap). - r = c.cas (&queue.front (), NULL); - - // If there are no elements prefetched, exit. - // During pipe's lifetime r should never be NULL, however, - // it can happen during pipe shutdown when items - // are being deallocated. - if (&queue.front () == r || !r) - return false; - - // There was at least one value prefetched. - return true; - } + // Reader is alive. Nothing special to do now. Just move + // the 'first un-flushed item' pointer to 'f'. + w = f; + return true; + } - // Reads an item from the pipe. Returns false if there is no value. - // available. - inline bool read (T *value_) - { - // Try to prefetch a value. - if (!check_read ()) - return false; - - // There was at least one value prefetched. - // Return it to the caller. - *value_ = queue.front (); - queue.pop (); + // Check whether item is available for reading. + inline bool check_read () + { + // Was the value prefetched already? If so, return. + if (&queue.front () != r && r) return true; - } - - // Applies the function fn to the first elemenent in the pipe - // and returns the value returned by the fn. - // The pipe mustn't be empty or the function crashes. - inline bool probe (bool (*fn)(const T &)) - { - bool rc = check_read (); - zmq_assert (rc); - - return (*fn) (queue.front ()); - } - - protected: - - // Allocation-efficient queue to store pipe items. - // Front of the queue points to the first prefetched item, back of - // the pipe points to last un-flushed item. Front is used only by - // reader thread, while back is used only by writer thread. - yqueue_t queue; - - // Points to the first un-flushed item. This variable is used - // exclusively by writer thread. - T *w; - - // Points to the first un-prefetched item. This variable is used - // exclusively by reader thread. - T *r; - - // Points to the first item to be flushed in the future. - T *f; - - // The single point of contention between writer and reader thread. - // Points past the last flushed item. If it is NULL, - // reader is asleep. This pointer should be always accessed using - // atomic operations. - atomic_ptr_t c; - - // Disable copying of ypipe object. - ypipe_t (const ypipe_t&); - const ypipe_t &operator = (const ypipe_t&); - }; + // There's no prefetched value, so let us prefetch more values. + // Prefetching is to simply retrieve the + // pointer from c in atomic fashion. If there are no + // items to prefetch, set c to NULL (using compare-and-swap). + r = c.cas (&queue.front (), NULL); + + // If there are no elements prefetched, exit. + // During pipe's lifetime r should never be NULL, however, + // it can happen during pipe shutdown when items + // are being deallocated. + if (&queue.front () == r || !r) + return false; + + // There was at least one value prefetched. + return true; + } + + // Reads an item from the pipe. Returns false if there is no value. + // available. + inline bool read (T *value_) + { + // Try to prefetch a value. + if (!check_read ()) + return false; + + // There was at least one value prefetched. + // Return it to the caller. + *value_ = queue.front (); + queue.pop (); + return true; + } + + // Applies the function fn to the first elemenent in the pipe + // and returns the value returned by the fn. + // The pipe mustn't be empty or the function crashes. + inline bool probe (bool (*fn) (const T &)) + { + bool rc = check_read (); + zmq_assert (rc); + + return (*fn) (queue.front ()); + } + + protected: + // Allocation-efficient queue to store pipe items. + // Front of the queue points to the first prefetched item, back of + // the pipe points to last un-flushed item. Front is used only by + // reader thread, while back is used only by writer thread. + yqueue_t queue; + + // Points to the first un-flushed item. This variable is used + // exclusively by writer thread. + T *w; + + // Points to the first un-prefetched item. This variable is used + // exclusively by reader thread. + T *r; + + // Points to the first item to be flushed in the future. + T *f; + + // The single point of contention between writer and reader thread. + // Points past the last flushed item. If it is NULL, + // reader is asleep. This pointer should be always accessed using + // atomic operations. + atomic_ptr_t c; + + // Disable copying of ypipe object. + ypipe_t (const ypipe_t &); + const ypipe_t &operator= (const ypipe_t &); +}; } #endif diff --git a/src/ypipe_base.hpp b/src/ypipe_base.hpp index 7b7d5ece42..cb70d138fa 100644 --- a/src/ypipe_base.hpp +++ b/src/ypipe_base.hpp @@ -34,21 +34,21 @@ namespace zmq { - // ypipe_base abstracts ypipe and ypipe_conflate specific - // classes, one is selected according to a the conflate - // socket option - - template class ypipe_base_t - { - public: - virtual ~ypipe_base_t () {} - virtual void write (const T &value_, bool incomplete_) = 0; - virtual bool unwrite (T *value_) = 0; - virtual bool flush () = 0; - virtual bool check_read () = 0; - virtual bool read (T *value_) = 0; - virtual bool probe (bool (*fn)(const T &)) = 0; - }; +// ypipe_base abstracts ypipe and ypipe_conflate specific +// classes, one is selected according to a the conflate +// socket option + +template class ypipe_base_t +{ + public: + virtual ~ypipe_base_t () {} + virtual void write (const T &value_, bool incomplete_) = 0; + virtual bool unwrite (T *value_) = 0; + virtual bool flush () = 0; + virtual bool check_read () = 0; + virtual bool read (T *value_) = 0; + virtual bool probe (bool (*fn) (const T &)) = 0; +}; } #endif diff --git a/src/ypipe_conflate.hpp b/src/ypipe_conflate.hpp index ab903c92ea..88cd506442 100644 --- a/src/ypipe_conflate.hpp +++ b/src/ypipe_conflate.hpp @@ -36,29 +36,22 @@ namespace zmq { +// Adapter for dbuffer, to plug it in instead of a queue for the sake +// of implementing the conflate socket option, which, if set, makes +// the receiving side to discard all incoming messages but the last one. +// +// reader_awake flag is needed here to mimic ypipe delicate behaviour +// around the reader being asleep (see 'c' pointer being NULL in ypipe.hpp) + +template class ypipe_conflate_t : public ypipe_base_t +{ + public: + // Initialises the pipe. + inline ypipe_conflate_t () : reader_awake (false) {} - // Adapter for dbuffer, to plug it in instead of a queue for the sake - // of implementing the conflate socket option, which, if set, makes - // the receiving side to discard all incoming messages but the last one. - // - // reader_awake flag is needed here to mimic ypipe delicate behaviour - // around the reader being asleep (see 'c' pointer being NULL in ypipe.hpp) - - template class ypipe_conflate_t : public ypipe_base_t - { - public: - - // Initialises the pipe. - inline ypipe_conflate_t () - : reader_awake(false) - { - } - - // The destructor doesn't have to be virtual. It is made virtual - // just to keep ICC and code checking tools from complaining. - inline virtual ~ypipe_conflate_t () - { - } + // The destructor doesn't have to be virtual. It is made virtual + // just to keep ICC and code checking tools from complaining. + inline virtual ~ypipe_conflate_t () {} // Following function (write) deliberately copies uninitialised data // when used with zmq_msg. Initialising the VSM body for @@ -68,70 +61,59 @@ namespace zmq #pragma message save #pragma message disable(UNINIT) #endif - inline void write (const T &value_, bool incomplete_) - { - (void)incomplete_; + inline void write (const T &value_, bool incomplete_) + { + (void) incomplete_; - dbuffer.write (value_); - } + dbuffer.write (value_); + } #ifdef ZMQ_HAVE_OPENVMS #pragma message restore #endif - // There are no incomplete items for conflate ypipe - inline bool unwrite (T *) - { + // There are no incomplete items for conflate ypipe + inline bool unwrite (T *) { return false; } + + // Flush is no-op for conflate ypipe. Reader asleep behaviour + // is as of the usual ypipe. + // Returns false if the reader thread is sleeping. In that case, + // caller is obliged to wake the reader up before using the pipe again. + inline bool flush () { return reader_awake; } + + // Check whether item is available for reading. + inline bool check_read () + { + bool res = dbuffer.check_read (); + if (!res) + reader_awake = false; + + return res; + } + + // Reads an item from the pipe. Returns false if there is no value. + // available. + inline bool read (T *value_) + { + if (!check_read ()) return false; - } - - // Flush is no-op for conflate ypipe. Reader asleep behaviour - // is as of the usual ypipe. - // Returns false if the reader thread is sleeping. In that case, - // caller is obliged to wake the reader up before using the pipe again. - inline bool flush () - { - return reader_awake; - } - - // Check whether item is available for reading. - inline bool check_read () - { - bool res = dbuffer.check_read (); - if (!res) - reader_awake = false; - - return res; - } - - // Reads an item from the pipe. Returns false if there is no value. - // available. - inline bool read (T *value_) - { - if (!check_read ()) - return false; - - return dbuffer.read (value_); - } - - // Applies the function fn to the first elemenent in the pipe - // and returns the value returned by the fn. - // The pipe mustn't be empty or the function crashes. - inline bool probe (bool (*fn)(const T &)) - { - return dbuffer.probe (fn); - } - - protected: - - dbuffer_t dbuffer; - bool reader_awake; - - // Disable copying of ypipe object. - ypipe_conflate_t (const ypipe_conflate_t&); - const ypipe_conflate_t &operator = (const ypipe_conflate_t&); - }; + return dbuffer.read (value_); + } + + // Applies the function fn to the first elemenent in the pipe + // and returns the value returned by the fn. + // The pipe mustn't be empty or the function crashes. + inline bool probe (bool (*fn) (const T &)) { return dbuffer.probe (fn); } + + protected: + dbuffer_t dbuffer; + bool reader_awake; + + // Disable copying of ypipe object. + ypipe_conflate_t (const ypipe_conflate_t &); + const ypipe_conflate_t &operator= (const ypipe_conflate_t &); +}; } #endif diff --git a/src/yqueue.hpp b/src/yqueue.hpp index d8afd85b60..82c76fe284 100644 --- a/src/yqueue.hpp +++ b/src/yqueue.hpp @@ -38,188 +38,178 @@ namespace zmq { - - // yqueue is an efficient queue implementation. The main goal is - // to minimise number of allocations/deallocations needed. Thus yqueue - // allocates/deallocates elements in batches of N. - // - // yqueue allows one thread to use push/back function and another one - // to use pop/front functions. However, user must ensure that there's no - // pop on the empty queue and that both threads don't access the same - // element in unsynchronised manner. - // - // T is the type of the object in the queue. - // N is granularity of the queue (how many pushes have to be done till - // actual memory allocation is required). +// yqueue is an efficient queue implementation. The main goal is +// to minimise number of allocations/deallocations needed. Thus yqueue +// allocates/deallocates elements in batches of N. +// +// yqueue allows one thread to use push/back function and another one +// to use pop/front functions. However, user must ensure that there's no +// pop on the empty queue and that both threads don't access the same +// element in unsynchronised manner. +// +// T is the type of the object in the queue. +// N is granularity of the queue (how many pushes have to be done till +// actual memory allocation is required). #ifdef HAVE_POSIX_MEMALIGN - // ALIGN is the memory alignment size to use in the case where we have - // posix_memalign available. Default value is 64, this alignment will - // prevent two queue chunks from occupying the same CPU cache line on - // architectures where cache lines are <= 64 bytes (e.g. most things - // except POWER). - template class yqueue_t +// ALIGN is the memory alignment size to use in the case where we have +// posix_memalign available. Default value is 64, this alignment will +// prevent two queue chunks from occupying the same CPU cache line on +// architectures where cache lines are <= 64 bytes (e.g. most things +// except POWER). +template class yqueue_t #else - template class yqueue_t +template class yqueue_t #endif +{ + public: + // Create the queue. + inline yqueue_t () + { + begin_chunk = allocate_chunk (); + alloc_assert (begin_chunk); + begin_pos = 0; + back_chunk = NULL; + back_pos = 0; + end_chunk = begin_chunk; + end_pos = 0; + } + + // Destroy the queue. + inline ~yqueue_t () { - public: - - // Create the queue. - inline yqueue_t () - { - begin_chunk = allocate_chunk(); - alloc_assert (begin_chunk); - begin_pos = 0; - back_chunk = NULL; - back_pos = 0; - end_chunk = begin_chunk; - end_pos = 0; + while (true) { + if (begin_chunk == end_chunk) { + free (begin_chunk); + break; + } + chunk_t *o = begin_chunk; + begin_chunk = begin_chunk->next; + free (o); } - // Destroy the queue. - inline ~yqueue_t () - { - while (true) { - if (begin_chunk == end_chunk) { - free (begin_chunk); - break; - } - chunk_t *o = begin_chunk; - begin_chunk = begin_chunk->next; - free (o); - } + chunk_t *sc = spare_chunk.xchg (NULL); + free (sc); + } - chunk_t *sc = spare_chunk.xchg (NULL); - free (sc); - } + // Returns reference to the front element of the queue. + // If the queue is empty, behaviour is undefined. + inline T &front () { return begin_chunk->values[begin_pos]; } - // Returns reference to the front element of the queue. - // If the queue is empty, behaviour is undefined. - inline T &front () - { - return begin_chunk->values [begin_pos]; - } + // Returns reference to the back element of the queue. + // If the queue is empty, behaviour is undefined. + inline T &back () { return back_chunk->values[back_pos]; } - // Returns reference to the back element of the queue. - // If the queue is empty, behaviour is undefined. - inline T &back () - { - return back_chunk->values [back_pos]; + // Adds an element to the back end of the queue. + inline void push () + { + back_chunk = end_chunk; + back_pos = end_pos; + + if (++end_pos != N) + return; + + chunk_t *sc = spare_chunk.xchg (NULL); + if (sc) { + end_chunk->next = sc; + sc->prev = end_chunk; + } else { + end_chunk->next = allocate_chunk (); + alloc_assert (end_chunk->next); + end_chunk->next->prev = end_chunk; } - - // Adds an element to the back end of the queue. - inline void push () - { - back_chunk = end_chunk; - back_pos = end_pos; - - if (++end_pos != N) - return; - - chunk_t *sc = spare_chunk.xchg (NULL); - if (sc) { - end_chunk->next = sc; - sc->prev = end_chunk; - } else { - end_chunk->next = allocate_chunk(); - alloc_assert (end_chunk->next); - end_chunk->next->prev = end_chunk; - } - end_chunk = end_chunk->next; - end_pos = 0; + end_chunk = end_chunk->next; + end_pos = 0; + } + + // Removes element from the back end of the queue. In other words + // it rollbacks last push to the queue. Take care: Caller is + // responsible for destroying the object being unpushed. + // The caller must also guarantee that the queue isn't empty when + // unpush is called. It cannot be done automatically as the read + // side of the queue can be managed by different, completely + // unsynchronised thread. + inline void unpush () + { + // First, move 'back' one position backwards. + if (back_pos) + --back_pos; + else { + back_pos = N - 1; + back_chunk = back_chunk->prev; } - // Removes element from the back end of the queue. In other words - // it rollbacks last push to the queue. Take care: Caller is - // responsible for destroying the object being unpushed. - // The caller must also guarantee that the queue isn't empty when - // unpush is called. It cannot be done automatically as the read - // side of the queue can be managed by different, completely - // unsynchronised thread. - inline void unpush () - { - // First, move 'back' one position backwards. - if (back_pos) - --back_pos; - else { - back_pos = N - 1; - back_chunk = back_chunk->prev; - } - - // Now, move 'end' position backwards. Note that obsolete end chunk - // is not used as a spare chunk. The analysis shows that doing so - // would require free and atomic operation per chunk deallocated - // instead of a simple free. - if (end_pos) - --end_pos; - else { - end_pos = N - 1; - end_chunk = end_chunk->prev; - free (end_chunk->next); - end_chunk->next = NULL; - } + // Now, move 'end' position backwards. Note that obsolete end chunk + // is not used as a spare chunk. The analysis shows that doing so + // would require free and atomic operation per chunk deallocated + // instead of a simple free. + if (end_pos) + --end_pos; + else { + end_pos = N - 1; + end_chunk = end_chunk->prev; + free (end_chunk->next); + end_chunk->next = NULL; } + } - // Removes an element from the front end of the queue. - inline void pop () - { - if (++ begin_pos == N) { - chunk_t *o = begin_chunk; - begin_chunk = begin_chunk->next; - begin_chunk->prev = NULL; - begin_pos = 0; - - // 'o' has been more recently used than spare_chunk, - // so for cache reasons we'll get rid of the spare and - // use 'o' as the spare. - chunk_t *cs = spare_chunk.xchg (o); - free (cs); - } + // Removes an element from the front end of the queue. + inline void pop () + { + if (++begin_pos == N) { + chunk_t *o = begin_chunk; + begin_chunk = begin_chunk->next; + begin_chunk->prev = NULL; + begin_pos = 0; + + // 'o' has been more recently used than spare_chunk, + // so for cache reasons we'll get rid of the spare and + // use 'o' as the spare. + chunk_t *cs = spare_chunk.xchg (o); + free (cs); } + } - private: - - // Individual memory chunk to hold N elements. - struct chunk_t - { - T values [N]; - chunk_t *prev; - chunk_t *next; - }; + private: + // Individual memory chunk to hold N elements. + struct chunk_t + { + T values[N]; + chunk_t *prev; + chunk_t *next; + }; - inline chunk_t *allocate_chunk () - { + inline chunk_t *allocate_chunk () + { #ifdef HAVE_POSIX_MEMALIGN - void *pv; - if (posix_memalign(&pv, ALIGN, sizeof (chunk_t)) == 0) - return (chunk_t*) pv; - return NULL; + void *pv; + if (posix_memalign (&pv, ALIGN, sizeof (chunk_t)) == 0) + return (chunk_t *) pv; + return NULL; #else - return (chunk_t*) malloc (sizeof (chunk_t)); + return (chunk_t *) malloc (sizeof (chunk_t)); #endif - } - - // Back position may point to invalid memory if the queue is empty, - // while begin & end positions are always valid. Begin position is - // accessed exclusively be queue reader (front/pop), while back and - // end positions are accessed exclusively by queue writer (back/push). - chunk_t *begin_chunk; - int begin_pos; - chunk_t *back_chunk; - int back_pos; - chunk_t *end_chunk; - int end_pos; - - // People are likely to produce and consume at similar rates. In - // this scenario holding onto the most recently freed chunk saves - // us from having to call malloc/free. - atomic_ptr_t spare_chunk; - - // Disable copying of yqueue. - yqueue_t (const yqueue_t&); - const yqueue_t &operator = (const yqueue_t&); - }; - + } + + // Back position may point to invalid memory if the queue is empty, + // while begin & end positions are always valid. Begin position is + // accessed exclusively be queue reader (front/pop), while back and + // end positions are accessed exclusively by queue writer (back/push). + chunk_t *begin_chunk; + int begin_pos; + chunk_t *back_chunk; + int back_pos; + chunk_t *end_chunk; + int end_pos; + + // People are likely to produce and consume at similar rates. In + // this scenario holding onto the most recently freed chunk saves + // us from having to call malloc/free. + atomic_ptr_t spare_chunk; + + // Disable copying of yqueue. + yqueue_t (const yqueue_t &); + const yqueue_t &operator= (const yqueue_t &); +}; } #endif diff --git a/src/zap_client.cpp b/src/zap_client.cpp index e44b0e20ab..38289fba06 100644 --- a/src/zap_client.cpp +++ b/src/zap_client.cpp @@ -44,22 +44,22 @@ zap_client_t::zap_client_t (session_base_t *const session_, } void zap_client_t::send_zap_request (const char *mechanism, - size_t mechanism_length, - const uint8_t *credentials, - size_t credentials_size) + size_t mechanism_length, + const uint8_t *credentials, + size_t credentials_size) { send_zap_request (mechanism, mechanism_length, &credentials, &credentials_size, 1); } void zap_client_t::send_zap_request (const char *mechanism, - size_t mechanism_length, - const uint8_t **credentials, - size_t *credentials_sizes, - size_t credentials_count) + size_t mechanism_length, + const uint8_t **credentials, + size_t *credentials_sizes, + size_t credentials_count) { - // write_zap_msg cannot fail. It could only fail if the HWM was exceeded, - // but on the ZAP socket, the HWM is disabled. + // write_zap_msg cannot fail. It could only fail if the HWM was exceeded, + // but on the ZAP socket, the HWM is disabled. int rc; msg_t msg; diff --git a/src/zap_client.hpp b/src/zap_client.hpp index 557cab6026..a227a7c346 100644 --- a/src/zap_client.hpp +++ b/src/zap_client.hpp @@ -54,6 +54,7 @@ class zap_client_t : public virtual mechanism_base_t virtual int receive_and_process_zap_reply (); virtual void handle_zap_status_code (); + protected: const std::string peer_address; diff --git a/src/zmq.cpp b/src/zmq.cpp index dbe1a2dbae..421241dc7f 100644 --- a/src/zmq.cpp +++ b/src/zmq.cpp @@ -61,7 +61,8 @@ #if defined ZMQ_HAVE_UIO #include #else -struct iovec { +struct iovec +{ void *iov_base; size_t iov_len; }; @@ -93,8 +94,8 @@ struct iovec { #endif // Compile time check whether msg_t fits into zmq_msg_t. -typedef char check_msg_t_size - [sizeof (zmq::msg_t) == sizeof (zmq_msg_t) ? 1 : -1]; +typedef char + check_msg_t_size[sizeof (zmq::msg_t) == sizeof (zmq_msg_t) ? 1 : -1]; void zmq_version (int *major_, int *minor_, int *patch_) @@ -129,12 +130,10 @@ void *zmq_ctx_new (void) pgm_error_t *pgm_error = NULL; const bool ok = pgm_init (&pgm_error); if (ok != TRUE) { - // Invalid parameters don't set pgm_error_t zmq_assert (pgm_error != NULL); - if (pgm_error->domain == PGM_ERROR_DOMAIN_TIME && ( - pgm_error->code == PGM_ERROR_FAILED)) { - + if (pgm_error->domain == PGM_ERROR_DOMAIN_TIME + && (pgm_error->code == PGM_ERROR_FAILED)) { // Failed to access RTC or HPET device. pgm_error_free (pgm_error); errno = EINVAL; @@ -149,14 +148,14 @@ void *zmq_ctx_new (void) #ifdef ZMQ_HAVE_WINDOWS // Intialise Windows sockets. Note that WSAStartup can be called multiple // times given that WSACleanup will be called for each WSAStartup. - // We do this before the ctx constructor since its embedded mailbox_t - // object needs Winsock to be up and running. + // We do this before the ctx constructor since its embedded mailbox_t + // object needs Winsock to be up and running. WORD version_requested = MAKEWORD (2, 2); WSADATA wsa_data; int rc = WSAStartup (version_requested, &wsa_data); zmq_assert (rc == 0); - zmq_assert (LOBYTE (wsa_data.wVersion) == 2 && - HIBYTE (wsa_data.wVersion) == 2); + zmq_assert (LOBYTE (wsa_data.wVersion) == 2 + && HIBYTE (wsa_data.wVersion) == 2); #endif // Create 0MQ context. @@ -282,8 +281,10 @@ int zmq_close (void *s_) return 0; } -int zmq_setsockopt (void *s_, int option_, const void *optval_, - size_t optvallen_) +int zmq_setsockopt (void *s_, + int option_, + const void *optval_, + size_t optvallen_) { zmq::socket_base_t *s = as_socket_base_t (s_); if (!s) @@ -307,7 +308,7 @@ int zmq_socket_monitor (void *s_, const char *addr_, int events_) return s->monitor (addr_, events_); } -int zmq_join (void *s_, const char* group_) +int zmq_join (void *s_, const char *group_) { zmq::socket_base_t *s = as_socket_base_t (s_); if (!s) @@ -315,7 +316,7 @@ int zmq_join (void *s_, const char* group_) return s->join (group_); } -int zmq_leave (void *s_, const char* group_) +int zmq_leave (void *s_, const char *group_) { zmq::socket_base_t *s = as_socket_base_t (s_); if (!s) @@ -370,7 +371,7 @@ s_sendmsg (zmq::socket_base_t *s_, zmq_msg_t *msg_, int flags_) size_t max_msgsz = INT_MAX; // Truncate returned size to INT_MAX to avoid overflow to negative values - return (int) (sz < max_msgsz? sz: max_msgsz); + return (int) (sz < max_msgsz ? sz : max_msgsz); } /* To be deprecated once zmq_msg_send() is stable */ @@ -412,7 +413,7 @@ int zmq_send_const (void *s_, const void *buf_, size_t len_, int flags_) if (!s) return -1; zmq_msg_t msg; - int rc = zmq_msg_init_data (&msg, (void *)buf_, len_, NULL, NULL); + int rc = zmq_msg_init_data (&msg, (void *) buf_, len_, NULL, NULL); if (rc != 0) return -1; @@ -461,12 +462,12 @@ int zmq_sendiov (void *s_, iovec *a_, size_t count_, int flags_) flags_ = flags_ & ~ZMQ_SNDMORE; rc = s_sendmsg (s, &msg, flags_); if (unlikely (rc < 0)) { - int err = errno; - int rc2 = zmq_msg_close (&msg); - errno_assert (rc2 == 0); - errno = err; - rc = -1; - break; + int err = errno; + int rc2 = zmq_msg_close (&msg); + errno_assert (rc2 == 0); + errno = err; + rc = -1; + break; } } return rc; @@ -474,8 +475,7 @@ int zmq_sendiov (void *s_, iovec *a_, size_t count_, int flags_) // Receiving functions. -static int -s_recvmsg (zmq::socket_base_t *s_, zmq_msg_t *msg_, int flags_) +static int s_recvmsg (zmq::socket_base_t *s_, zmq_msg_t *msg_, int flags_) { int rc = s_->recv ((zmq::msg_t *) msg_, flags_); if (unlikely (rc < 0)) @@ -483,7 +483,7 @@ s_recvmsg (zmq::socket_base_t *s_, zmq_msg_t *msg_, int flags_) // Truncate returned size to INT_MAX to avoid overflow to negative values size_t sz = zmq_msg_size (msg_); - return (int) (sz < INT_MAX? sz: INT_MAX); + return (int) (sz < INT_MAX ? sz : INT_MAX); } /* To be deprecated once zmq_msg_recv() is stable */ @@ -558,7 +558,6 @@ int zmq_recviov (void *s_, iovec *a_, size_t *count_, int flags_) *count_ = 0; for (size_t i = 0; recvmore && i < count; ++i) { - zmq_msg_t msg; int rc = zmq_msg_init (&msg); errno_assert (rc == 0); @@ -574,17 +573,17 @@ int zmq_recviov (void *s_, iovec *a_, size_t *count_, int flags_) } a_[i].iov_len = zmq_msg_size (&msg); - a_[i].iov_base = static_cast (malloc(a_[i].iov_len)); + a_[i].iov_base = static_cast (malloc (a_[i].iov_len)); if (unlikely (!a_[i].iov_base)) { errno = ENOMEM; return -1; } - memcpy(a_[i].iov_base,static_cast (zmq_msg_data (&msg)), - a_[i].iov_len); + memcpy (a_[i].iov_base, static_cast (zmq_msg_data (&msg)), + a_[i].iov_len); // Assume zmq_socket ZMQ_RVCMORE is properly set. - zmq::msg_t* p_msg = reinterpret_cast(&msg); - recvmore = p_msg->flags() & zmq::msg_t::more; - rc = zmq_msg_close(&msg); + zmq::msg_t *p_msg = reinterpret_cast (&msg); + recvmore = p_msg->flags () & zmq::msg_t::more; + rc = zmq_msg_close (&msg); errno_assert (rc == 0); ++*count_; ++nread; @@ -596,18 +595,18 @@ int zmq_recviov (void *s_, iovec *a_, size_t *count_, int flags_) int zmq_msg_init (zmq_msg_t *msg_) { - return ((zmq::msg_t*) msg_)->init (); + return ((zmq::msg_t *) msg_)->init (); } int zmq_msg_init_size (zmq_msg_t *msg_, size_t size_) { - return ((zmq::msg_t*) msg_)->init_size (size_); + return ((zmq::msg_t *) msg_)->init_size (size_); } -int zmq_msg_init_data (zmq_msg_t *msg_, void *data_, size_t size_, - zmq_free_fn *ffn_, void *hint_) +int zmq_msg_init_data ( + zmq_msg_t *msg_, void *data_, size_t size_, zmq_free_fn *ffn_, void *hint_) { - return ((zmq::msg_t*) msg_)->init_data (data_, size_, ffn_, hint_); + return ((zmq::msg_t *) msg_)->init_data (data_, size_, ffn_, hint_); } int zmq_msg_send (zmq_msg_t *msg_, void *s_, int flags_) @@ -628,27 +627,27 @@ int zmq_msg_recv (zmq_msg_t *msg_, void *s_, int flags_) int zmq_msg_close (zmq_msg_t *msg_) { - return ((zmq::msg_t*) msg_)->close (); + return ((zmq::msg_t *) msg_)->close (); } int zmq_msg_move (zmq_msg_t *dest_, zmq_msg_t *src_) { - return ((zmq::msg_t*) dest_)->move (*(zmq::msg_t*) src_); + return ((zmq::msg_t *) dest_)->move (*(zmq::msg_t *) src_); } int zmq_msg_copy (zmq_msg_t *dest_, zmq_msg_t *src_) { - return ((zmq::msg_t*) dest_)->copy (*(zmq::msg_t*) src_); + return ((zmq::msg_t *) dest_)->copy (*(zmq::msg_t *) src_); } void *zmq_msg_data (zmq_msg_t *msg_) { - return ((zmq::msg_t*) msg_)->data (); + return ((zmq::msg_t *) msg_)->data (); } size_t zmq_msg_size (const zmq_msg_t *msg_) { - return ((zmq::msg_t*) msg_)->size (); + return ((zmq::msg_t *) msg_)->size (); } int zmq_msg_more (const zmq_msg_t *msg_) @@ -658,20 +657,22 @@ int zmq_msg_more (const zmq_msg_t *msg_) int zmq_msg_get (const zmq_msg_t *msg_, int property_) { - const char* fd_string; + const char *fd_string; switch (property_) { case ZMQ_MORE: - return (((zmq::msg_t*) msg_)->flags () & zmq::msg_t::more)? 1: 0; + return (((zmq::msg_t *) msg_)->flags () & zmq::msg_t::more) ? 1 : 0; case ZMQ_SRCFD: - fd_string = zmq_msg_gets(msg_, "__fd"); + fd_string = zmq_msg_gets (msg_, "__fd"); if (fd_string == NULL) - return (int)-1; + return (int) -1; - return atoi(fd_string); + return atoi (fd_string); case ZMQ_SHARED: - return (((zmq::msg_t*) msg_)->is_cmsg ()) || - (((zmq::msg_t*) msg_)->flags () & zmq::msg_t::shared)? 1: 0; + return (((zmq::msg_t *) msg_)->is_cmsg ()) + || (((zmq::msg_t *) msg_)->flags () & zmq::msg_t::shared) + ? 1 + : 0; default: errno = EINVAL; return -1; @@ -721,7 +722,7 @@ const char *zmq_msg_gets (const zmq_msg_t *msg_, const char *property_) } } -// Polling. + // Polling. #if defined ZMQ_HAVE_POLLER inline int zmq_poller_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) @@ -731,7 +732,7 @@ inline int zmq_poller_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) zmq_poller_event_t *events; zmq::socket_poller_t poller; events = new (std::nothrow) zmq_poller_event_t[nitems_]; - alloc_assert(events); + alloc_assert (events); bool repeat_items = false; // Register sockets with poller @@ -756,7 +757,7 @@ inline int zmq_poller_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) rc = zmq_poller_add (&poller, items_[i].socket, NULL, e); } if (rc < 0) { - delete [] events; + delete[] events; return rc; } } else { @@ -775,7 +776,7 @@ inline int zmq_poller_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) rc = zmq_poller_add_fd (&poller, items_[i].fd, NULL, e); } if (rc < 0) { - delete [] events; + delete[] events; return rc; } } @@ -784,8 +785,8 @@ inline int zmq_poller_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) // Wait for events rc = zmq_poller_wait_all (&poller, events, nitems_, timeout_); if (rc < 0) { - delete [] events; - if (zmq_errno() == EAGAIN) { + delete[] events; + if (zmq_errno () == EAGAIN) { return 0; } return rc; @@ -800,10 +801,9 @@ inline int zmq_poller_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) int j_start = 0, found_events = rc; for (int i = 0; i < nitems_; i++) { for (int j = j_start; j < found_events; ++j) { - if ( - (items_[i].socket && items_[i].socket == events[j].socket) || - (!(items_[i].socket || events[j].socket) && items_[i].fd == events[j].fd) - ) { + if ((items_[i].socket && items_[i].socket == events[j].socket) + || (!(items_[i].socket || events[j].socket) + && items_[i].fd == events[j].fd)) { items_[i].revents = events[j].events & items_[i].events; if (!repeat_items) { // no repeats, we can ignore events we've already seen @@ -819,18 +819,18 @@ inline int zmq_poller_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) } // Cleanup - delete [] events; + delete[] events; return rc; } #endif // ZMQ_HAVE_POLLER int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) { - // TODO: the function implementation can just call zmq_pollfd_poll with - // pollfd as NULL, however pollfd is not yet stable. +// TODO: the function implementation can just call zmq_pollfd_poll with +// pollfd as NULL, however pollfd is not yet stable. #if defined ZMQ_HAVE_POLLER // if poller is present, use that. - return zmq_poller_poll(items_, nitems_, timeout_); + return zmq_poller_poll (items_, nitems_, timeout_); #else #if defined ZMQ_POLL_BASED_ON_POLL if (unlikely (nitems_ < 0)) { @@ -863,33 +863,33 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) pollfd *pollfds = spollfds; if (nitems_ > ZMQ_POLLITEMS_DFLT) { - pollfds = (pollfd*) malloc (nitems_ * sizeof (pollfd)); + pollfds = (pollfd *) malloc (nitems_ * sizeof (pollfd)); alloc_assert (pollfds); } // Build pollset for poll () system call. for (int i = 0; i != nitems_; i++) { - // If the poll item is a 0MQ socket, we poll on the file descriptor // retrieved by the ZMQ_FD socket option. - if (items_ [i].socket) { + if (items_[i].socket) { size_t zmq_fd_size = sizeof (zmq::fd_t); - if (zmq_getsockopt (items_ [i].socket, ZMQ_FD, &pollfds [i].fd, - &zmq_fd_size) == -1) { + if (zmq_getsockopt (items_[i].socket, ZMQ_FD, &pollfds[i].fd, + &zmq_fd_size) + == -1) { if (pollfds != spollfds) free (pollfds); return -1; } - pollfds [i].events = items_ [i].events ? POLLIN : 0; + pollfds[i].events = items_[i].events ? POLLIN : 0; } // Else, the poll item is a raw file descriptor. Just convert the // events to normal POLLIN/POLLOUT for poll (). else { - pollfds [i].fd = items_ [i].fd; - pollfds [i].events = - (items_ [i].events & ZMQ_POLLIN ? POLLIN : 0) | - (items_ [i].events & ZMQ_POLLOUT ? POLLOUT : 0) | - (items_ [i].events & ZMQ_POLLPRI ? POLLPRI : 0); + pollfds[i].fd = items_[i].fd; + pollfds[i].events = + (items_[i].events & ZMQ_POLLIN ? POLLIN : 0) + | (items_[i].events & ZMQ_POLLOUT ? POLLOUT : 0) + | (items_[i].events & ZMQ_POLLPRI ? POLLPRI : 0); } } @@ -901,8 +901,7 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) int timeout; if (first_pass) timeout = 0; - else - if (timeout_ < 0) + else if (timeout_ < 0) timeout = -1; else timeout = end - now; @@ -919,41 +918,41 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) } // Check for the events. for (int i = 0; i != nitems_; i++) { - - items_ [i].revents = 0; + items_[i].revents = 0; // The poll item is a 0MQ socket. Retrieve pending events // using the ZMQ_EVENTS socket option. - if (items_ [i].socket) { + if (items_[i].socket) { size_t zmq_events_size = sizeof (uint32_t); uint32_t zmq_events; - if (zmq_getsockopt (items_ [i].socket, ZMQ_EVENTS, &zmq_events, - &zmq_events_size) == -1) { + if (zmq_getsockopt (items_[i].socket, ZMQ_EVENTS, &zmq_events, + &zmq_events_size) + == -1) { if (pollfds != spollfds) free (pollfds); return -1; } - if ((items_ [i].events & ZMQ_POLLOUT) && - (zmq_events & ZMQ_POLLOUT)) - items_ [i].revents |= ZMQ_POLLOUT; - if ((items_ [i].events & ZMQ_POLLIN) && - (zmq_events & ZMQ_POLLIN)) - items_ [i].revents |= ZMQ_POLLIN; + if ((items_[i].events & ZMQ_POLLOUT) + && (zmq_events & ZMQ_POLLOUT)) + items_[i].revents |= ZMQ_POLLOUT; + if ((items_[i].events & ZMQ_POLLIN) + && (zmq_events & ZMQ_POLLIN)) + items_[i].revents |= ZMQ_POLLIN; } // Else, the poll item is a raw file descriptor, simply convert // the events to zmq_pollitem_t-style format. else { - if (pollfds [i].revents & POLLIN) - items_ [i].revents |= ZMQ_POLLIN; - if (pollfds [i].revents & POLLOUT) - items_ [i].revents |= ZMQ_POLLOUT; - if (pollfds [i].revents & POLLPRI) - items_ [i].revents |= ZMQ_POLLPRI; - if (pollfds [i].revents & ~(POLLIN | POLLOUT | POLLPRI)) - items_ [i].revents |= ZMQ_POLLERR; + if (pollfds[i].revents & POLLIN) + items_[i].revents |= ZMQ_POLLIN; + if (pollfds[i].revents & POLLOUT) + items_[i].revents |= ZMQ_POLLOUT; + if (pollfds[i].revents & POLLPRI) + items_[i].revents |= ZMQ_POLLPRI; + if (pollfds[i].revents & ~(POLLIN | POLLOUT | POLLPRI)) + items_[i].revents |= ZMQ_POLLERR; } - if (items_ [i].revents) + if (items_[i].revents) nevents++; } @@ -1031,16 +1030,16 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) // Build the fd_sets for passing to select (). for (int i = 0; i != nitems_; i++) { - // If the poll item is a 0MQ socket we are interested in input on the // notification file descriptor retrieved by the ZMQ_FD socket option. - if (items_ [i].socket) { + if (items_[i].socket) { size_t zmq_fd_size = sizeof (zmq::fd_t); zmq::fd_t notify_fd; - if (zmq_getsockopt (items_ [i].socket, ZMQ_FD, ¬ify_fd, - &zmq_fd_size) == -1) + if (zmq_getsockopt (items_[i].socket, ZMQ_FD, ¬ify_fd, + &zmq_fd_size) + == -1) return -1; - if (items_ [i].events) { + if (items_[i].events) { FD_SET (notify_fd, &pollset_in); if (maxfd < notify_fd) maxfd = notify_fd; @@ -1049,14 +1048,14 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) // Else, the poll item is a raw file descriptor. Convert the poll item // events to the appropriate fd_sets. else { - if (items_ [i].events & ZMQ_POLLIN) - FD_SET (items_ [i].fd, &pollset_in); - if (items_ [i].events & ZMQ_POLLOUT) - FD_SET (items_ [i].fd, &pollset_out); - if (items_ [i].events & ZMQ_POLLERR) - FD_SET (items_ [i].fd, &pollset_err); - if (maxfd < items_ [i].fd) - maxfd = items_ [i].fd; + if (items_[i].events & ZMQ_POLLIN) + FD_SET (items_[i].fd, &pollset_in); + if (items_[i].events & ZMQ_POLLOUT) + FD_SET (items_[i].fd, &pollset_out); + if (items_[i].events & ZMQ_POLLERR) + FD_SET (items_[i].fd, &pollset_err); + if (maxfd < items_[i].fd) + maxfd = items_[i].fd; } } @@ -1065,7 +1064,6 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) fd_set inset, outset, errset; while (true) { - // Compute the timeout for the subsequent poll. timeval timeout; timeval *ptimeout; @@ -1073,9 +1071,7 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) timeout.tv_sec = 0; timeout.tv_usec = 0; ptimeout = &timeout; - } - else - if (timeout_ < 0) + } else if (timeout_ < 0) ptimeout = NULL; else { timeout.tv_sec = (long) ((end - now) / 1000); @@ -1090,9 +1086,15 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) // SOCKETS are continuous from the beginning of fd_array in fd_set. // We just need to copy fd_count elements of fd_array. // We gain huge memcpy() improvement if number of used SOCKETs is much lower than FD_SETSIZE. - memcpy (&inset, &pollset_in , (char *) (pollset_in.fd_array + pollset_in.fd_count ) - (char *) &pollset_in ); - memcpy (&outset, &pollset_out, (char *) (pollset_out.fd_array + pollset_out.fd_count) - (char *) &pollset_out); - memcpy (&errset, &pollset_err, (char *) (pollset_err.fd_array + pollset_err.fd_count) - (char *) &pollset_err); + memcpy (&inset, &pollset_in, + (char *) (pollset_in.fd_array + pollset_in.fd_count) + - (char *) &pollset_in); + memcpy (&outset, &pollset_out, + (char *) (pollset_out.fd_array + pollset_out.fd_count) + - (char *) &pollset_out); + memcpy (&errset, &pollset_err, + (char *) (pollset_err.fd_array + pollset_err.fd_count) + - (char *) &pollset_err); int rc = select (0, &inset, &outset, &errset, ptimeout); if (unlikely (rc == SOCKET_ERROR)) { errno = zmq::wsa_error_to_errno (WSAGetLastError ()); @@ -1100,7 +1102,7 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) return -1; } #else - memcpy (&inset, &pollset_in, sizeof (fd_set)); + memcpy (&inset, &pollset_in, sizeof (fd_set)); memcpy (&outset, &pollset_out, sizeof (fd_set)); memcpy (&errset, &pollset_err, sizeof (fd_set)); int rc = select (maxfd + 1, &inset, &outset, &errset, ptimeout); @@ -1114,36 +1116,36 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) // Check for the events. for (int i = 0; i != nitems_; i++) { - - items_ [i].revents = 0; + items_[i].revents = 0; // The poll item is a 0MQ socket. Retrieve pending events // using the ZMQ_EVENTS socket option. - if (items_ [i].socket) { + if (items_[i].socket) { size_t zmq_events_size = sizeof (uint32_t); uint32_t zmq_events; - if (zmq_getsockopt (items_ [i].socket, ZMQ_EVENTS, &zmq_events, - &zmq_events_size) == -1) + if (zmq_getsockopt (items_[i].socket, ZMQ_EVENTS, &zmq_events, + &zmq_events_size) + == -1) return -1; - if ((items_ [i].events & ZMQ_POLLOUT) && - (zmq_events & ZMQ_POLLOUT)) - items_ [i].revents |= ZMQ_POLLOUT; - if ((items_ [i].events & ZMQ_POLLIN) && - (zmq_events & ZMQ_POLLIN)) - items_ [i].revents |= ZMQ_POLLIN; + if ((items_[i].events & ZMQ_POLLOUT) + && (zmq_events & ZMQ_POLLOUT)) + items_[i].revents |= ZMQ_POLLOUT; + if ((items_[i].events & ZMQ_POLLIN) + && (zmq_events & ZMQ_POLLIN)) + items_[i].revents |= ZMQ_POLLIN; } // Else, the poll item is a raw file descriptor, simply convert // the events to zmq_pollitem_t-style format. else { - if (FD_ISSET (items_ [i].fd, &inset)) - items_ [i].revents |= ZMQ_POLLIN; - if (FD_ISSET (items_ [i].fd, &outset)) - items_ [i].revents |= ZMQ_POLLOUT; - if (FD_ISSET (items_ [i].fd, &errset)) - items_ [i].revents |= ZMQ_POLLERR; + if (FD_ISSET (items_[i].fd, &inset)) + items_[i].revents |= ZMQ_POLLIN; + if (FD_ISSET (items_[i].fd, &outset)) + items_[i].revents |= ZMQ_POLLOUT; + if (FD_ISSET (items_[i].fd, &errset)) + items_[i].revents |= ZMQ_POLLERR; } - if (items_ [i].revents) + if (items_[i].revents) nevents++; } @@ -1179,7 +1181,7 @@ int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_) // Find out whether timeout have expired. now = clock.now_ms (); if (now >= end) - break; + break; } return nevents; @@ -1204,40 +1206,44 @@ void *zmq_poller_new (void) int zmq_poller_destroy (void **poller_p_) { void *poller; - if (!poller_p_ || !(poller = *poller_p_) || - !((zmq::socket_poller_t*) poller)->check_tag ()) { + if (!poller_p_ || !(poller = *poller_p_) + || !((zmq::socket_poller_t *) poller)->check_tag ()) { errno = EFAULT; return -1; } - delete ((zmq::socket_poller_t*) poller); + delete ((zmq::socket_poller_t *) poller); *poller_p_ = NULL; return 0; } int zmq_poller_add (void *poller_, void *s_, void *user_data_, short events_) { - if (!poller_ || !((zmq::socket_poller_t*)poller_)->check_tag ()) { + if (!poller_ || !((zmq::socket_poller_t *) poller_)->check_tag ()) { errno = EFAULT; return -1; } - if (!s_ || !((zmq::socket_base_t*)s_)->check_tag ()) { + if (!s_ || !((zmq::socket_base_t *) s_)->check_tag ()) { errno = ENOTSOCK; return -1; } - zmq::socket_base_t *socket = (zmq::socket_base_t*)s_; + zmq::socket_base_t *socket = (zmq::socket_base_t *) s_; - return ((zmq::socket_poller_t*)poller_)->add (socket, user_data_, events_); + return ((zmq::socket_poller_t *) poller_) + ->add (socket, user_data_, events_); } #if defined _WIN32 -int zmq_poller_add_fd (void *poller_, SOCKET fd_, void *user_data_, short events_) +int zmq_poller_add_fd (void *poller_, + SOCKET fd_, + void *user_data_, + short events_) #else int zmq_poller_add_fd (void *poller_, int fd_, void *user_data_, short events_) #endif { - if (!poller_ || !((zmq::socket_poller_t*)poller_)->check_tag ()) { + if (!poller_ || !((zmq::socket_poller_t *) poller_)->check_tag ()) { errno = EFAULT; return -1; } @@ -1246,24 +1252,25 @@ int zmq_poller_add_fd (void *poller_, int fd_, void *user_data_, short events_) return -1; } - return ((zmq::socket_poller_t*)poller_)->add_fd (fd_, user_data_, events_); + return ((zmq::socket_poller_t *) poller_) + ->add_fd (fd_, user_data_, events_); } int zmq_poller_modify (void *poller_, void *s_, short events_) { - if (!poller_ || !((zmq::socket_poller_t*)poller_)->check_tag ()) { + if (!poller_ || !((zmq::socket_poller_t *) poller_)->check_tag ()) { errno = EFAULT; return -1; } - if (!s_ || !((zmq::socket_base_t*)s_)->check_tag ()) { + if (!s_ || !((zmq::socket_base_t *) s_)->check_tag ()) { errno = ENOTSOCK; return -1; } - zmq::socket_base_t *socket = (zmq::socket_base_t*)s_; + zmq::socket_base_t *socket = (zmq::socket_base_t *) s_; - return ((zmq::socket_poller_t*)poller_)->modify (socket, events_); + return ((zmq::socket_poller_t *) poller_)->modify (socket, events_); } @@ -1273,7 +1280,7 @@ int zmq_poller_modify_fd (void *poller_, SOCKET fd_, short events_) int zmq_poller_modify_fd (void *poller_, int fd_, short events_) #endif { - if (!poller_ || !((zmq::socket_poller_t*)poller_)->check_tag ()) { + if (!poller_ || !((zmq::socket_poller_t *) poller_)->check_tag ()) { errno = EFAULT; return -1; } @@ -1282,24 +1289,24 @@ int zmq_poller_modify_fd (void *poller_, int fd_, short events_) return -1; } - return ((zmq::socket_poller_t*)poller_)->modify_fd (fd_, events_); + return ((zmq::socket_poller_t *) poller_)->modify_fd (fd_, events_); } int zmq_poller_remove (void *poller_, void *s_) { - if (!poller_ || !((zmq::socket_poller_t*)poller_)->check_tag ()) { + if (!poller_ || !((zmq::socket_poller_t *) poller_)->check_tag ()) { errno = EFAULT; return -1; } - if (!s_ || !((zmq::socket_base_t*)s_)->check_tag ()) { + if (!s_ || !((zmq::socket_base_t *) s_)->check_tag ()) { errno = ENOTSOCK; return -1; } - zmq::socket_base_t *socket = (zmq::socket_base_t*)s_; + zmq::socket_base_t *socket = (zmq::socket_base_t *) s_; - return ((zmq::socket_poller_t*)poller_)->remove (socket); + return ((zmq::socket_poller_t *) poller_)->remove (socket); } #if defined _WIN32 @@ -1308,7 +1315,7 @@ int zmq_poller_remove_fd (void *poller_, SOCKET fd_) int zmq_poller_remove_fd (void *poller_, int fd_) #endif { - if (!poller_ || !((zmq::socket_poller_t*)poller_)->check_tag ()) { + if (!poller_ || !((zmq::socket_poller_t *) poller_)->check_tag ()) { errno = EFAULT; return -1; } @@ -1317,13 +1324,13 @@ int zmq_poller_remove_fd (void *poller_, int fd_) return -1; } - return ((zmq::socket_poller_t*)poller_)->remove_fd (fd_); + return ((zmq::socket_poller_t *) poller_)->remove_fd (fd_); } int zmq_poller_wait (void *poller_, zmq_poller_event_t *event_, long timeout_) { - if (!poller_ || !((zmq::socket_poller_t*)poller_)->check_tag ()) { + if (!poller_ || !((zmq::socket_poller_t *) poller_)->check_tag ()) { errno = EFAULT; return -1; } @@ -1332,18 +1339,21 @@ int zmq_poller_wait (void *poller_, zmq_poller_event_t *event_, long timeout_) return -1; } - int rc = zmq_poller_wait_all(poller_, event_, 1, timeout_); + int rc = zmq_poller_wait_all (poller_, event_, 1, timeout_); if (rc < 0) { - memset (event_, 0, sizeof(zmq_poller_event_t)); + memset (event_, 0, sizeof (zmq_poller_event_t)); } // wait_all returns number of events, but we return 0 for any success return rc >= 0 ? 0 : rc; } -int zmq_poller_wait_all (void *poller_, zmq_poller_event_t *events_, int n_events, long timeout_) +int zmq_poller_wait_all (void *poller_, + zmq_poller_event_t *events_, + int n_events, + long timeout_) { - if (!poller_ || !((zmq::socket_poller_t*)poller_)->check_tag ()) { + if (!poller_ || !((zmq::socket_poller_t *) poller_)->check_tag ()) { errno = EFAULT; return -1; } @@ -1356,7 +1366,9 @@ int zmq_poller_wait_all (void *poller_, zmq_poller_event_t *events_, int n_event return -1; } - int rc = ((zmq::socket_poller_t*)poller_)->wait ((zmq::socket_poller_t::event_t *)events_, n_events, timeout_); + int rc = + ((zmq::socket_poller_t *) poller_) + ->wait ((zmq::socket_poller_t::event_t *) events_, n_events, timeout_); return rc; } @@ -1395,64 +1407,67 @@ int zmq_timers_destroy (void **timers_p_) return 0; } -int zmq_timers_add (void *timers_, size_t interval_, zmq_timer_fn handler_, void *arg_) +int zmq_timers_add (void *timers_, + size_t interval_, + zmq_timer_fn handler_, + void *arg_) { - if (!timers_ || !((zmq::timers_t*)timers_)->check_tag ()) { + if (!timers_ || !((zmq::timers_t *) timers_)->check_tag ()) { errno = EFAULT; return -1; } - return ((zmq::timers_t*)timers_)->add (interval_, handler_, arg_); + return ((zmq::timers_t *) timers_)->add (interval_, handler_, arg_); } int zmq_timers_cancel (void *timers_, int timer_id_) { - if (!timers_ || !((zmq::timers_t*)timers_)->check_tag ()) { + if (!timers_ || !((zmq::timers_t *) timers_)->check_tag ()) { errno = EFAULT; return -1; } - return ((zmq::timers_t*)timers_)->cancel (timer_id_); + return ((zmq::timers_t *) timers_)->cancel (timer_id_); } int zmq_timers_set_interval (void *timers_, int timer_id_, size_t interval_) { - if (!timers_ || !((zmq::timers_t*)timers_)->check_tag ()) { + if (!timers_ || !((zmq::timers_t *) timers_)->check_tag ()) { errno = EFAULT; return -1; } - return ((zmq::timers_t*)timers_)->set_interval (timer_id_, interval_); + return ((zmq::timers_t *) timers_)->set_interval (timer_id_, interval_); } int zmq_timers_reset (void *timers_, int timer_id_) { - if (!timers_ || !((zmq::timers_t*)timers_)->check_tag ()) { + if (!timers_ || !((zmq::timers_t *) timers_)->check_tag ()) { errno = EFAULT; return -1; } - return ((zmq::timers_t*)timers_)->reset (timer_id_); + return ((zmq::timers_t *) timers_)->reset (timer_id_); } long zmq_timers_timeout (void *timers_) { - if (!timers_ || !((zmq::timers_t*)timers_)->check_tag ()) { + if (!timers_ || !((zmq::timers_t *) timers_)->check_tag ()) { errno = EFAULT; return -1; } - return ((zmq::timers_t*)timers_)->timeout (); + return ((zmq::timers_t *) timers_)->timeout (); } int zmq_timers_execute (void *timers_) { - if (!timers_ || !((zmq::timers_t*)timers_)->check_tag ()) { + if (!timers_ || !((zmq::timers_t *) timers_)->check_tag ()) { errno = EFAULT; return -1; } - return ((zmq::timers_t*)timers_)->execute (); + return ((zmq::timers_t *) timers_)->execute (); } // The proxy functionality @@ -1463,67 +1478,66 @@ int zmq_proxy (void *frontend_, void *backend_, void *capture_) errno = EFAULT; return -1; } - return zmq::proxy ( - (zmq::socket_base_t*) frontend_, - (zmq::socket_base_t*) backend_, - (zmq::socket_base_t*) capture_); + return zmq::proxy ((zmq::socket_base_t *) frontend_, + (zmq::socket_base_t *) backend_, + (zmq::socket_base_t *) capture_); } -int zmq_proxy_steerable (void *frontend_, void *backend_, void *capture_, void *control_) +int zmq_proxy_steerable (void *frontend_, + void *backend_, + void *capture_, + void *control_) { if (!frontend_ || !backend_) { errno = EFAULT; return -1; } return zmq::proxy ( - (zmq::socket_base_t*) frontend_, - (zmq::socket_base_t*) backend_, - (zmq::socket_base_t*) capture_, - (zmq::socket_base_t*) control_); + (zmq::socket_base_t *) frontend_, (zmq::socket_base_t *) backend_, + (zmq::socket_base_t *) capture_, (zmq::socket_base_t *) control_); } // The deprecated device functionality int zmq_device (int /* type */, void *frontend_, void *backend_) { - return zmq::proxy ( - (zmq::socket_base_t*) frontend_, - (zmq::socket_base_t*) backend_, NULL); + return zmq::proxy ((zmq::socket_base_t *) frontend_, + (zmq::socket_base_t *) backend_, NULL); } // Probe library capabilities; for now, reports on transport and security int zmq_has (const char *capability) { -#if !defined (ZMQ_HAVE_WINDOWS) && !defined (ZMQ_HAVE_OPENVMS) +#if !defined(ZMQ_HAVE_WINDOWS) && !defined(ZMQ_HAVE_OPENVMS) if (strcmp (capability, "ipc") == 0) return true; #endif -#if defined (ZMQ_HAVE_OPENPGM) +#if defined(ZMQ_HAVE_OPENPGM) if (strcmp (capability, "pgm") == 0) return true; #endif -#if defined (ZMQ_HAVE_TIPC) +#if defined(ZMQ_HAVE_TIPC) if (strcmp (capability, "tipc") == 0) return true; #endif -#if defined (ZMQ_HAVE_NORM) +#if defined(ZMQ_HAVE_NORM) if (strcmp (capability, "norm") == 0) return true; #endif -#if defined (ZMQ_HAVE_CURVE) +#if defined(ZMQ_HAVE_CURVE) if (strcmp (capability, "curve") == 0) return true; #endif -#if defined (HAVE_LIBGSSAPI_KRB5) +#if defined(HAVE_LIBGSSAPI_KRB5) if (strcmp (capability, "gssapi") == 0) return true; #endif -#if defined (ZMQ_HAVE_VMCI) +#if defined(ZMQ_HAVE_VMCI) if (strcmp (capability, "vmci") == 0) return true; #endif -#if defined (ZMQ_BUILD_DRAFT_API) +#if defined(ZMQ_BUILD_DRAFT_API) if (strcmp (capability, "draft") == 0) return true; #endif diff --git a/src/zmq_draft.h b/src/zmq_draft.h index cbffcf38f9..b3c1cbffd8 100644 --- a/src/zmq_draft.h +++ b/src/zmq_draft.h @@ -54,16 +54,16 @@ /* DRAFT 0MQ socket events and monitoring */ /* Unspecified system errors during handshake. Event value is an errno. */ -#define ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL 0x0800 +#define ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL 0x0800 /* Handshake complete successfully with successful authentication (if * * enabled). Event value is unused. */ -#define ZMQ_EVENT_HANDSHAKE_SUCCEEDED 0x1000 +#define ZMQ_EVENT_HANDSHAKE_SUCCEEDED 0x1000 /* Protocol errors between ZMTP peers or between server and ZAP handler. * * Event value is one of ZMQ_PROTOCOL_ERROR_* */ -#define ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL 0x2000 +#define ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL 0x2000 /* Failed authentication requests. Event value is the numeric ZAP status * * code, i.e. 300, 400 or 500. */ -#define ZMQ_EVENT_HANDSHAKE_FAILED_AUTH 0x4000 +#define ZMQ_EVENT_HANDSHAKE_FAILED_AUTH 0x4000 #define ZMQ_PROTOCOL_ERROR_ZMTP_UNSPECIFIED 0x10000000 #define ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND 0x10000001 @@ -82,7 +82,7 @@ #define ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC 0x11000001 #define ZMQ_PROTOCOL_ERROR_ZMTP_MECHANISM_MISMATCH 0x11000002 -#define ZMQ_PROTOCOL_ERROR_ZAP_UNSPECIFIED 0x20000000 +#define ZMQ_PROTOCOL_ERROR_ZAP_UNSPECIFIED 0x20000000 #define ZMQ_PROTOCOL_ERROR_ZAP_MALFORMED_REPLY 0x20000001 #define ZMQ_PROTOCOL_ERROR_ZAP_BAD_REQUEST_ID 0x20000002 #define ZMQ_PROTOCOL_ERROR_ZAP_BAD_VERSION 0x20000003 @@ -100,16 +100,16 @@ int zmq_join (void *s, const char *group); int zmq_leave (void *s, const char *group); /* DRAFT Msg methods. */ -int zmq_msg_set_routing_id(zmq_msg_t *msg, uint32_t routing_id); -uint32_t zmq_msg_routing_id(zmq_msg_t *msg); -int zmq_msg_set_group(zmq_msg_t *msg, const char *group); -const char *zmq_msg_group(zmq_msg_t *msg); +int zmq_msg_set_routing_id (zmq_msg_t *msg, uint32_t routing_id); +uint32_t zmq_msg_routing_id (zmq_msg_t *msg); +int zmq_msg_set_group (zmq_msg_t *msg, const char *group); +const char *zmq_msg_group (zmq_msg_t *msg); /* DRAFT Msg property names. */ -#define ZMQ_MSG_PROPERTY_ROUTING_ID "Routing-Id" -#define ZMQ_MSG_PROPERTY_SOCKET_TYPE "Socket-Type" -#define ZMQ_MSG_PROPERTY_USER_ID "User-Id" -#define ZMQ_MSG_PROPERTY_PEER_ADDRESS "Peer-Address" +#define ZMQ_MSG_PROPERTY_ROUTING_ID "Routing-Id" +#define ZMQ_MSG_PROPERTY_SOCKET_TYPE "Socket-Type" +#define ZMQ_MSG_PROPERTY_USER_ID "User-Id" +#define ZMQ_MSG_PROPERTY_PEER_ADDRESS "Peer-Address" /******************************************************************************/ /* Poller polling on sockets,fd and thread-safe sockets */ @@ -128,12 +128,15 @@ typedef struct zmq_poller_event_t } zmq_poller_event_t; void *zmq_poller_new (void); -int zmq_poller_destroy (void **poller_p); -int zmq_poller_add (void *poller, void *socket, void *user_data, short events); -int zmq_poller_modify (void *poller, void *socket, short events); -int zmq_poller_remove (void *poller, void *socket); -int zmq_poller_wait (void *poller, zmq_poller_event_t *event, long timeout); -int zmq_poller_wait_all (void *poller, zmq_poller_event_t *events, int n_events, long timeout); +int zmq_poller_destroy (void **poller_p); +int zmq_poller_add (void *poller, void *socket, void *user_data, short events); +int zmq_poller_modify (void *poller, void *socket, short events); +int zmq_poller_remove (void *poller, void *socket); +int zmq_poller_wait (void *poller, zmq_poller_event_t *event, long timeout); +int zmq_poller_wait_all (void *poller, + zmq_poller_event_t *events, + int n_events, + long timeout); #if defined _WIN32 int zmq_poller_add_fd (void *poller, SOCKET fd, void *user_data, short events); @@ -153,16 +156,19 @@ int zmq_socket_get_peer_state (void *socket, /* Scheduling timers */ /******************************************************************************/ -typedef void (zmq_timer_fn)(int timer_id, void *arg); +typedef void(zmq_timer_fn) (int timer_id, void *arg); void *zmq_timers_new (void); -int zmq_timers_destroy (void **timers_p); -int zmq_timers_add (void *timers, size_t interval, zmq_timer_fn handler, void *arg); -int zmq_timers_cancel (void *timers, int timer_id); -int zmq_timers_set_interval (void *timers, int timer_id, size_t interval); -int zmq_timers_reset (void *timers, int timer_id); -long zmq_timers_timeout (void *timers); -int zmq_timers_execute (void *timers); +int zmq_timers_destroy (void **timers_p); +int zmq_timers_add (void *timers, + size_t interval, + zmq_timer_fn handler, + void *arg); +int zmq_timers_cancel (void *timers, int timer_id); +int zmq_timers_set_interval (void *timers, int timer_id, size_t interval); +int zmq_timers_reset (void *timers, int timer_id); +long zmq_timers_timeout (void *timers); +int zmq_timers_execute (void *timers); /******************************************************************************/ /* GSSAPI definitions */ diff --git a/src/zmq_utils.cpp b/src/zmq_utils.cpp index 24f4df7384..c5243937e8 100644 --- a/src/zmq_utils.cpp +++ b/src/zmq_utils.cpp @@ -43,9 +43,9 @@ #include #endif -#if defined (ZMQ_USE_TWEETNACL) +#if defined(ZMQ_USE_TWEETNACL) #include "tweetnacl.h" -#elif defined (ZMQ_USE_LIBSODIUM) +#elif defined(ZMQ_USE_LIBSODIUM) #include "sodium.h" #endif @@ -60,61 +60,60 @@ void zmq_sleep (int seconds_) void *zmq_stopwatch_start () { - uint64_t *watch = (uint64_t*) malloc (sizeof (uint64_t)); + uint64_t *watch = (uint64_t *) malloc (sizeof (uint64_t)); alloc_assert (watch); *watch = zmq::clock_t::now_us (); - return (void*) watch; + return (void *) watch; } unsigned long zmq_stopwatch_stop (void *watch_) { uint64_t end = zmq::clock_t::now_us (); - uint64_t start = *(uint64_t*) watch_; + uint64_t start = *(uint64_t *) watch_; free (watch_); return (unsigned long) (end - start); } -void *zmq_threadstart(zmq_thread_fn* func, void* arg) +void *zmq_threadstart (zmq_thread_fn *func, void *arg) { - zmq::thread_t* thread = new (std::nothrow) zmq::thread_t; - alloc_assert(thread); - thread->start(func, arg); + zmq::thread_t *thread = new (std::nothrow) zmq::thread_t; + alloc_assert (thread); + thread->start (func, arg); return thread; } -void zmq_threadclose(void* thread) +void zmq_threadclose (void *thread) { - zmq::thread_t* pThread = static_cast(thread); - pThread->stop(); - LIBZMQ_DELETE(pThread); + zmq::thread_t *pThread = static_cast (thread); + pThread->stop (); + LIBZMQ_DELETE (pThread); } // Z85 codec, taken from 0MQ RFC project, implements RFC32 Z85 encoding // Maps base 256 to base 85 -static char encoder [85 + 1] = { - "0123456789" "abcdefghij" "klmnopqrst" "uvwxyzABCD" - "EFGHIJKLMN" "OPQRSTUVWX" "YZ.-:+=^!/" "*?&<>()[]{" - "}@%$#" -}; +static char encoder[85 + 1] = {"0123456789" + "abcdefghij" + "klmnopqrst" + "uvwxyzABCD" + "EFGHIJKLMN" + "OPQRSTUVWX" + "YZ.-:+=^!/" + "*?&<>()[]{" + "}@%$#"}; // Maps base 85 to base 256 // We chop off lower 32 and higher 128 ranges // 0xFF denotes invalid characters within this range -static uint8_t decoder [96] = { - 0xFF, 0x44, 0xFF, 0x54, 0x53, 0x52, 0x48, 0xFF, - 0x4B, 0x4C, 0x46, 0x41, 0xFF, 0x3F, 0x3E, 0x45, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x40, 0xFF, 0x49, 0x42, 0x4A, 0x47, - 0x51, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, - 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, - 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, - 0x3B, 0x3C, 0x3D, 0x4D, 0xFF, 0x4E, 0x43, 0xFF, - 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, - 0x21, 0x22, 0x23, 0x4F, 0xFF, 0x50, 0xFF, 0xFF -}; +static uint8_t decoder[96] = { + 0xFF, 0x44, 0xFF, 0x54, 0x53, 0x52, 0x48, 0xFF, 0x4B, 0x4C, 0x46, 0x41, + 0xFF, 0x3F, 0x3E, 0x45, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x40, 0xFF, 0x49, 0x42, 0x4A, 0x47, 0x51, 0x24, 0x25, 0x26, + 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, + 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x4D, + 0xFF, 0x4E, 0x43, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, + 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x4F, 0xFF, 0x50, 0xFF, 0xFF}; // -------------------------------------------------------------------------- // Encode a binary frame as a string; destination string MUST be at least @@ -133,19 +132,19 @@ char *zmq_z85_encode (char *dest, const uint8_t *data, size_t size) uint32_t value = 0; while (byte_nbr < size) { // Accumulate value in base 256 (binary) - value = value * 256 + data [byte_nbr++]; + value = value * 256 + data[byte_nbr++]; if (byte_nbr % 4 == 0) { // Output value in base 85 unsigned int divisor = 85 * 85 * 85 * 85; while (divisor) { - dest [char_nbr++] = encoder [value / divisor % 85]; + dest[char_nbr++] = encoder[value / divisor % 85]; divisor /= 85; } value = 0; } } assert (char_nbr == size * 5 / 4); - dest [char_nbr] = 0; + dest[char_nbr] = 0; return dest; } @@ -168,12 +167,12 @@ uint8_t *zmq_z85_decode (uint8_t *dest, const char *string) goto error_inval; } value *= 85; - uint8_t index = string [char_nbr++] - 32; - if (index >= sizeof(decoder)) { + uint8_t index = string[char_nbr++] - 32; + if (index >= sizeof (decoder)) { // Invalid z85 encoding, character outside range goto error_inval; } - uint32_t summand = decoder [index]; + uint32_t summand = decoder[index]; if (summand == 0xFF || summand > (UINT32_MAX - value)) { // Invalid z85 encoding, invalid character or represented value exceeds 0xffffffff goto error_inval; @@ -183,7 +182,7 @@ uint8_t *zmq_z85_decode (uint8_t *dest, const char *string) // Output value in base 256 unsigned int divisor = 256 * 256 * 256; while (divisor) { - dest [byte_nbr++] = value / divisor % 256; + dest[byte_nbr++] = value / divisor % 256; divisor /= 256; } value = 0; @@ -208,14 +207,13 @@ uint8_t *zmq_z85_decode (uint8_t *dest, const char *string) int zmq_curve_keypair (char *z85_public_key, char *z85_secret_key) { -#if defined (ZMQ_HAVE_CURVE) -# if crypto_box_PUBLICKEYBYTES != 32 \ - || crypto_box_SECRETKEYBYTES != 32 -# error "CURVE encryption library not built correctly" -# endif +#if defined(ZMQ_HAVE_CURVE) +#if crypto_box_PUBLICKEYBYTES != 32 || crypto_box_SECRETKEYBYTES != 32 +#error "CURVE encryption library not built correctly" +#endif - uint8_t public_key [32]; - uint8_t secret_key [32]; + uint8_t public_key[32]; + uint8_t secret_key[32]; zmq::random_open (); @@ -241,11 +239,10 @@ int zmq_curve_keypair (char *z85_public_key, char *z85_secret_key) int zmq_curve_public (char *z85_public_key, const char *z85_secret_key) { -#if defined (ZMQ_HAVE_CURVE) -# if crypto_box_PUBLICKEYBYTES != 32 \ - || crypto_box_SECRETKEYBYTES != 32 -# error "CURVE encryption library not built correctly" -# endif +#if defined(ZMQ_HAVE_CURVE) +#if crypto_box_PUBLICKEYBYTES != 32 || crypto_box_SECRETKEYBYTES != 32 +#error "CURVE encryption library not built correctly" +#endif uint8_t public_key[32]; uint8_t secret_key[32]; @@ -299,7 +296,7 @@ int zmq_atomic_counter_inc (void *counter_) int zmq_atomic_counter_dec (void *counter_) { - return ((zmq::atomic_counter_t *) counter_)->sub (1)? 1: 0; + return ((zmq::atomic_counter_t *) counter_)->sub (1) ? 1 : 0; } // Return actual value of atomic counter diff --git a/tests/test_abstract_ipc.cpp b/tests/test_abstract_ipc.cpp index aeba5b9110..3e5f5a3302 100644 --- a/tests/test_abstract_ipc.cpp +++ b/tests/test_abstract_ipc.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -41,17 +41,17 @@ int main (void) assert (rc == 0); char endpoint[200]; - size_t size = sizeof(endpoint); + size_t size = sizeof (endpoint); rc = zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, endpoint, &size); assert (rc == 0); - rc = strncmp(endpoint, "ipc://@tmp-tester", size); + rc = strncmp (endpoint, "ipc://@tmp-tester", size); assert (rc == 0); void *sc = zmq_socket (ctx, ZMQ_DEALER); assert (sc); rc = zmq_connect (sc, "ipc://@tmp-tester"); assert (rc == 0); - + bounce (sb, sc); rc = zmq_close (sc); @@ -63,5 +63,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_ancillaries.cpp b/tests/test_ancillaries.cpp index ba72ba4a85..de41ed7d99 100644 --- a/tests/test_ancillaries.cpp +++ b/tests/test_ancillaries.cpp @@ -41,9 +41,8 @@ int main (void) int major, minor, patch; zmq_version (&major, &minor, &patch); - assert (major == ZMQ_VERSION_MAJOR && - minor == ZMQ_VERSION_MINOR && - patch == ZMQ_VERSION_PATCH); + assert (major == ZMQ_VERSION_MAJOR && minor == ZMQ_VERSION_MINOR + && patch == ZMQ_VERSION_PATCH); assert (zmq_strerror (EINVAL)); diff --git a/tests/test_base85.cpp b/tests/test_base85.cpp index 293f989a6a..aa429cb1f7 100644 --- a/tests/test_base85.cpp +++ b/tests/test_base85.cpp @@ -34,14 +34,13 @@ void test__zmq_z85_encode__valid__success () { static const size_t size = 8; static const size_t length = size * 5 / 4; - static const uint8_t decoded[size] = { - 0x86, 0x4F, 0xD2, 0x6F, 0xB5, 0x59, 0xF7, 0x5B - }; + static const uint8_t decoded[size] = {0x86, 0x4F, 0xD2, 0x6F, + 0xB5, 0x59, 0xF7, 0x5B}; static const char expected[length + 1] = "HelloWorld"; - char out_encoded[length + 1] = { 0 }; + char out_encoded[length + 1] = {0}; errno = 0; - assert (zmq_z85_encode(out_encoded, decoded, size) != NULL); + assert (zmq_z85_encode (out_encoded, decoded, size) != NULL); assert (streq (out_encoded, expected)); assert (zmq_errno () == 0); } @@ -50,7 +49,7 @@ void test__zmq_z85_encode__valid__success () void test__zmq_z85_encode__invalid__failure (size_t size) { errno = 0; - assert (zmq_z85_encode(NULL, NULL, size) == NULL); + assert (zmq_z85_encode (NULL, NULL, size) == NULL); assert (zmq_errno () == EINVAL); } @@ -58,60 +57,62 @@ void test__zmq_z85_encode__invalid__failure (size_t size) void test__zmq_z85_decode__valid__success () { static const size_t size = 10 * 4 / 5; - static const uint8_t expected[size] = { - 0x86, 0x4F, 0xD2, 0x6F, 0xB5, 0x59, 0xF7, 0x5B - }; - static const char* encoded = "HelloWorld"; - uint8_t out_decoded[size] = { 0 }; + static const uint8_t expected[size] = {0x86, 0x4F, 0xD2, 0x6F, + 0xB5, 0x59, 0xF7, 0x5B}; + static const char *encoded = "HelloWorld"; + uint8_t out_decoded[size] = {0}; errno = 0; - assert (zmq_z85_decode(out_decoded, encoded) != NULL); + assert (zmq_z85_decode (out_decoded, encoded) != NULL); assert (zmq_errno () == 0); assert (memcmp (out_decoded, expected, size) == 0); } // Invalid input data must fail with EINVAL. -template +template void test__zmq_z85_decode__invalid__failure (const char (&encoded)[SIZE]) { uint8_t decoded[SIZE * 4 / 5 + 1]; errno = 0; - assert (zmq_z85_decode(decoded, encoded) == NULL); + assert (zmq_z85_decode (decoded, encoded) == NULL); assert (zmq_errno () == EINVAL); } // call zmq_z85_encode, then zmq_z85_decode, and compare the results with the original -template -void test__zmq_z85_encode__zmq_z85_decode__roundtrip(const uint8_t (&test_data)[SIZE]) +template +void test__zmq_z85_encode__zmq_z85_decode__roundtrip ( + const uint8_t (&test_data)[SIZE]) { char test_data_z85[SIZE * 5 / 4 + 1]; - char *res1 = zmq_z85_encode(test_data_z85, test_data, SIZE); - assert(res1 != NULL); + char *res1 = zmq_z85_encode (test_data_z85, test_data, SIZE); + assert (res1 != NULL); uint8_t test_data_decoded[SIZE]; - uint8_t *res2 = zmq_z85_decode(test_data_decoded, test_data_z85); - assert(res2 != NULL); + uint8_t *res2 = zmq_z85_decode (test_data_decoded, test_data_z85); + assert (res2 != NULL); - int res3 = memcmp(test_data, test_data_decoded, SIZE); - assert(res3 == 0); + int res3 = memcmp (test_data, test_data_decoded, SIZE); + assert (res3 == 0); } // call zmq_z85_encode, then zmq_z85_decode, and compare the results with the original -template -void test__zmq_z85_decode__zmq_z85_encode__roundtrip(const char (&test_data)[SIZE]) +template +void test__zmq_z85_decode__zmq_z85_encode__roundtrip ( + const char (&test_data)[SIZE]) { const size_t decoded_size = (SIZE - 1) * 4 / 5; uint8_t test_data_decoded[decoded_size]; - uint8_t *res1 = zmq_z85_decode(test_data_decoded, test_data); - assert(res1 != NULL); + uint8_t *res1 = zmq_z85_decode (test_data_decoded, test_data); + assert (res1 != NULL); char test_data_z85[SIZE]; - char *res2 = zmq_z85_encode(test_data_z85, test_data_decoded, decoded_size); - assert(res2 != NULL); + char *res2 = + zmq_z85_encode (test_data_z85, test_data_decoded, decoded_size); + assert (res2 != NULL); - int res3 = memcmp(test_data, test_data_z85, SIZE); - assert(res3 == 0); + int res3 = memcmp (test_data, test_data_z85, SIZE); + assert (res3 == 0); } @@ -147,16 +148,17 @@ int main (void) // round-trip encoding and decoding with minimum value { - const uint8_t test_data[] = {0x00, 0x00, 0x00, 0x00}; - test__zmq_z85_encode__zmq_z85_decode__roundtrip(test_data); + const uint8_t test_data[] = {0x00, 0x00, 0x00, 0x00}; + test__zmq_z85_encode__zmq_z85_decode__roundtrip (test_data); } // round-trip encoding and decoding with maximum value { - const uint8_t test_data[] = {0xff, 0xff, 0xff, 0xff}; - test__zmq_z85_encode__zmq_z85_decode__roundtrip(test_data); + const uint8_t test_data[] = {0xff, 0xff, 0xff, 0xff}; + test__zmq_z85_encode__zmq_z85_decode__roundtrip (test_data); } - test__zmq_z85_decode__zmq_z85_encode__roundtrip("r^/rM9M=rMToK)63O8dCvd9D 0); assert (payload_recved == message_count - 1); diff --git a/tests/test_connect_delay_tipc.cpp b/tests/test_connect_delay_tipc.cpp index 9deb6a00b3..03df8ee13f 100644 --- a/tests/test_connect_delay_tipc.cpp +++ b/tests/test_connect_delay_tipc.cpp @@ -41,21 +41,21 @@ int main (void) // of the messages getting queued, as connect() creates a // pipe immediately. - void *context = zmq_ctx_new(); + void *context = zmq_ctx_new (); assert (context); - void *to = zmq_socket(context, ZMQ_PULL); + void *to = zmq_socket (context, ZMQ_PULL); assert (to); // Bind the one valid receiver val = 0; - rc = zmq_setsockopt(to, ZMQ_LINGER, &val, sizeof(val)); + rc = zmq_setsockopt (to, ZMQ_LINGER, &val, sizeof (val)); assert (rc == 0); rc = zmq_bind (to, "tipc://{6555,0,0}"); assert (rc == 0); // Create a socket pushing to two endpoints - only 1 message should arrive. void *from = zmq_socket (context, ZMQ_PUSH); - assert(from); + assert (from); val = 0; zmq_setsockopt (from, ZMQ_LINGER, &val, sizeof (val)); @@ -83,7 +83,7 @@ int main (void) while (true) { rc = zmq_recv (to, &buffer, sizeof (buffer), 0); if (rc == -1) - break; // Break when we didn't get a message + break; // Break when we didn't get a message seen++; } assert (seen == 5); @@ -104,7 +104,7 @@ int main (void) // also set the delay attach on connect flag, which should // cause the pipe attachment to be delayed until the connection // succeeds. - context = zmq_ctx_new(); + context = zmq_ctx_new (); // Bind the valid socket to = zmq_socket (context, ZMQ_PULL); @@ -113,7 +113,7 @@ int main (void) assert (rc == 0); val = 0; - rc = zmq_setsockopt (to, ZMQ_LINGER, &val, sizeof(val)); + rc = zmq_setsockopt (to, ZMQ_LINGER, &val, sizeof (val)); assert (rc == 0); // Create a socket pushing to two endpoints - all messages should arrive. @@ -121,12 +121,12 @@ int main (void) assert (from); val = 0; - rc = zmq_setsockopt (from, ZMQ_LINGER, &val, sizeof(val)); + rc = zmq_setsockopt (from, ZMQ_LINGER, &val, sizeof (val)); assert (rc == 0); // Set the key flag val = 1; - rc = zmq_setsockopt (from, ZMQ_DELAY_ATTACH_ON_CONNECT, &val, sizeof(val)); + rc = zmq_setsockopt (from, ZMQ_DELAY_ATTACH_ON_CONNECT, &val, sizeof (val)); assert (rc == 0); // Connect to the invalid socket @@ -148,7 +148,7 @@ int main (void) while (true) { rc = zmq_recv (to, &buffer, sizeof (buffer), 0); if (rc == -1) - break; // Break when we didn't get a message + break; // Break when we didn't get a message seen++; } assert (seen == 10); @@ -181,7 +181,8 @@ int main (void) // Frontend connects to backend using DELAY_ATTACH_ON_CONNECT int on = 1; - rc = zmq_setsockopt (frontend, ZMQ_DELAY_ATTACH_ON_CONNECT, &on, sizeof (on)); + rc = + zmq_setsockopt (frontend, ZMQ_DELAY_ATTACH_ON_CONNECT, &on, sizeof (on)); assert (rc == 0); rc = zmq_bind (backend, "tipc://{5560,0,0}"); assert (rc == 0); @@ -235,4 +236,3 @@ int main (void) rc = zmq_ctx_term (context); assert (rc == 0); } - diff --git a/tests/test_connect_resolve.cpp b/tests/test_connect_resolve.cpp index e043b5591b..692dac77dc 100644 --- a/tests/test_connect_resolve.cpp +++ b/tests/test_connect_resolve.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -49,10 +49,10 @@ int main (void) rc = zmq_connect (sock, "tcp://in val id:1234"); assert (rc == -1); - + rc = zmq_connect (sock, "tcp://"); assert (rc == -1); - + rc = zmq_connect (sock, "tcp://192.168.0.200:*"); assert (rc == -1); diff --git a/tests/test_connect_rid.cpp b/tests/test_connect_rid.cpp index eee3e7dd81..1f55ee172e 100644 --- a/tests/test_connect_rid.cpp +++ b/tests/test_connect_rid.cpp @@ -30,7 +30,8 @@ #include "testutil.hpp" -void test_stream_2_stream(){ +void test_stream_2_stream () +{ void *rbind, *rconn1; int ret; char buff[256]; @@ -45,12 +46,13 @@ void test_stream_2_stream(){ // Set up listener STREAM. rbind = zmq_socket (ctx, ZMQ_STREAM); assert (rbind); - ret = zmq_setsockopt (rbind, ZMQ_STREAM_NOTIFY, &disabled, sizeof (disabled)); + ret = + zmq_setsockopt (rbind, ZMQ_STREAM_NOTIFY, &disabled, sizeof (disabled)); assert (ret == 0); ret = zmq_setsockopt (rbind, ZMQ_LINGER, &zero, sizeof (zero)); assert (0 == ret); ret = zmq_bind (rbind, bindip); - assert(0 == ret); + assert (0 == ret); ret = zmq_getsockopt (rbind, ZMQ_LAST_ENDPOINT, my_endpoint, &len); assert (0 == ret); @@ -65,7 +67,7 @@ void test_stream_2_stream(){ assert (0 == ret); ret = zmq_connect (rconn1, my_endpoint); -/* Uncomment to test assert on duplicate routing id. + /* Uncomment to test assert on duplicate routing id. // Test duplicate connect attempt. ret = zmq_setsockopt (rconn1, ZMQ_CONNECT_ROUTING_ID, "conn1", 6); assert (0 == ret); @@ -82,22 +84,23 @@ void test_stream_2_stream(){ ret = zmq_recv (rbind, buff, 256, 0); assert (ret); assert (0 == buff[0]); - ret = zmq_recv (rbind, buff+128, 128, 0); + ret = zmq_recv (rbind, buff + 128, 128, 0); assert (5 == ret); assert ('h' == buff[128]); // Handle close of the socket. ret = zmq_unbind (rbind, my_endpoint); - assert(0 == ret); + assert (0 == ret); ret = zmq_close (rbind); - assert(0 == ret); + assert (0 == ret); ret = zmq_close (rconn1); - assert(0 == ret); + assert (0 == ret); zmq_ctx_destroy (ctx); } -void test_router_2_router(bool named){ +void test_router_2_router (bool named) +{ void *rbind, *rconn1; int ret; char buff[256]; @@ -135,7 +138,7 @@ void test_router_2_router(bool named){ assert (0 == ret); ret = zmq_connect (rconn1, my_endpoint); assert (0 == ret); -/* Uncomment to test assert on duplicate routing id + /* Uncomment to test assert on duplicate routing id // Test duplicate connect attempt. ret = zmq_setsockopt (rconn1, ZMQ_CONNECT_ROUTING_ID, "conn1", 6); assert (0 == ret); @@ -156,15 +159,14 @@ void test_router_2_router(bool named){ assert (ret && 0 == buff[0]); // Receive the data. - ret = zmq_recv (rbind, buff+128, 128, 0); - assert(5 == ret && 'h' == buff[128]); + ret = zmq_recv (rbind, buff + 128, 128, 0); + assert (5 == ret && 'h' == buff[128]); // Send some data back. if (named) { ret = zmq_send (rbind, buff, 1, ZMQ_SNDMORE); assert (1 == ret); - } - else { + } else { ret = zmq_send (rbind, buff, 5, ZMQ_SNDMORE); assert (5 == ret); } @@ -174,15 +176,15 @@ void test_router_2_router(bool named){ // If bound socket identity naming a problem, we'll likely see something funky here. ret = zmq_recv (rconn1, buff, 256, 0); assert ('c' == buff[0] && 6 == ret); - ret = zmq_recv (rconn1, buff+128, 128, 0); + ret = zmq_recv (rconn1, buff + 128, 128, 0); assert (3 == ret && 'o' == buff[128]); ret = zmq_unbind (rbind, my_endpoint); - assert(0 == ret); + assert (0 == ret); ret = zmq_close (rbind); - assert(0 == ret); + assert (0 == ret); ret = zmq_close (rconn1); - assert(0 == ret); + assert (0 == ret); zmq_ctx_destroy (ctx); } diff --git a/tests/test_ctx_destroy.cpp b/tests/test_ctx_destroy.cpp index fa943b0fab..8b43f68705 100644 --- a/tests/test_ctx_destroy.cpp +++ b/tests/test_ctx_destroy.cpp @@ -33,17 +33,17 @@ static void receiver (void *socket) { char buffer[16]; int rc = zmq_recv (socket, &buffer, sizeof (buffer), 0); - assert(rc == -1); + assert (rc == -1); } -void test_ctx_destroy() +void test_ctx_destroy () { int rc; - + // Set up our context and sockets void *ctx = zmq_ctx_new (); assert (ctx); - + void *socket = zmq_socket (ctx, ZMQ_PULL); assert (socket); @@ -62,14 +62,14 @@ void test_ctx_destroy() assert (rc == 0); } -void test_ctx_shutdown() +void test_ctx_shutdown () { int rc; - + // Set up our context and sockets void *ctx = zmq_ctx_new (); assert (ctx); - + void *socket = zmq_socket (ctx, ZMQ_PULL); assert (socket); @@ -101,10 +101,10 @@ void test_ctx_shutdown() int main (void) { - setup_test_environment(); + setup_test_environment (); - test_ctx_destroy(); - test_ctx_shutdown(); + test_ctx_destroy (); + test_ctx_shutdown (); return 0; } diff --git a/tests/test_ctx_options.cpp b/tests/test_ctx_options.cpp index 364376482c..4fbd8da21b 100644 --- a/tests/test_ctx_options.cpp +++ b/tests/test_ctx_options.cpp @@ -30,16 +30,17 @@ #include #include "testutil.hpp" -#define WAIT_FOR_BACKGROUND_THREAD_INSPECTION (0) +#define WAIT_FOR_BACKGROUND_THREAD_INSPECTION (0) #ifdef ZMQ_HAVE_LINUX #include #include -#include // for sleep() +#include // for sleep() -#define TEST_POLICY (SCHED_OTHER) // NOTE: SCHED_OTHER is the default Linux scheduler +#define TEST_POLICY \ + (SCHED_OTHER) // NOTE: SCHED_OTHER is the default Linux scheduler -bool is_allowed_to_raise_priority() +bool is_allowed_to_raise_priority () { // NOTE1: if setrlimit() fails with EPERM, this means that current user has not enough permissions. // NOTE2: even for privileged users (e.g., root) getrlimit() would usually return 0 as nice limit; the only way to @@ -47,24 +48,25 @@ bool is_allowed_to_raise_priority() struct rlimit rlim; rlim.rlim_cur = 40; rlim.rlim_max = 40; - if (setrlimit(RLIMIT_NICE, &rlim) == 0) - { + if (setrlimit (RLIMIT_NICE, &rlim) == 0) { // rlim_cur == 40 means that this process is allowed to set a nice value of -20 if (WAIT_FOR_BACKGROUND_THREAD_INSPECTION) - printf ("This process has enough permissions to raise ZMQ background thread priority!\n"); + printf ("This process has enough permissions to raise ZMQ " + "background thread priority!\n"); return true; } if (WAIT_FOR_BACKGROUND_THREAD_INSPECTION) - printf ("This process has NOT enough permissions to raise ZMQ background thread priority.\n"); + printf ("This process has NOT enough permissions to raise ZMQ " + "background thread priority.\n"); return false; } #else -#define TEST_POLICY (0) +#define TEST_POLICY (0) -bool is_allowed_to_raise_priority() +bool is_allowed_to_raise_priority () { return false; } @@ -72,14 +74,15 @@ bool is_allowed_to_raise_priority() #endif -void test_ctx_thread_opts(void* ctx) +void test_ctx_thread_opts (void *ctx) { int rc; // verify that setting negative values (e.g., default values) fail: - rc = zmq_ctx_set(ctx, ZMQ_THREAD_SCHED_POLICY, ZMQ_THREAD_SCHED_POLICY_DFLT); + rc = + zmq_ctx_set (ctx, ZMQ_THREAD_SCHED_POLICY, ZMQ_THREAD_SCHED_POLICY_DFLT); assert (rc == -1 && errno == EINVAL); - rc = zmq_ctx_set(ctx, ZMQ_THREAD_PRIORITY, ZMQ_THREAD_PRIORITY_DFLT); + rc = zmq_ctx_set (ctx, ZMQ_THREAD_PRIORITY, ZMQ_THREAD_PRIORITY_DFLT); assert (rc == -1 && errno == EINVAL); @@ -87,7 +90,7 @@ void test_ctx_thread_opts(void* ctx) // set context options that alter the background thread CPU scheduling/affinity settings; // as of ZMQ 4.2.3 this has an effect only on POSIX systems (nothing happens on Windows, but still it should return success): - rc = zmq_ctx_set(ctx, ZMQ_THREAD_SCHED_POLICY, TEST_POLICY); + rc = zmq_ctx_set (ctx, ZMQ_THREAD_SCHED_POLICY, TEST_POLICY); assert (rc == 0); @@ -102,9 +105,10 @@ void test_ctx_thread_opts(void* ctx) // ZMQ will internally use nice(2) to set the nice value when using SCHED_OTHER. // However changing the nice value of a process requires appropriate permissions... // check that the current effective user is able to do that: - if (is_allowed_to_raise_priority()) - { - rc = zmq_ctx_set(ctx, ZMQ_THREAD_PRIORITY, 1 /* any positive value different than the default will be ok */); + if (is_allowed_to_raise_priority ()) { + rc = zmq_ctx_set ( + ctx, ZMQ_THREAD_PRIORITY, + 1 /* any positive value different than the default will be ok */); assert (rc == 0); } @@ -112,22 +116,23 @@ void test_ctx_thread_opts(void* ctx) #ifdef ZMQ_THREAD_AFFINITY_CPU_ADD // test affinity: - // this should result in background threads being placed only on the - // first CPU available on this system; try experimenting with other values - // (e.g., 5 to use CPU index 5) and use "top -H" or "taskset -pc" to see the result + // this should result in background threads being placed only on the + // first CPU available on this system; try experimenting with other values + // (e.g., 5 to use CPU index 5) and use "top -H" or "taskset -pc" to see the result - int cpus_add[] = { 0, 1 }; - for (unsigned int idx=0; idx < sizeof(cpus_add)/sizeof(cpus_add[0]); idx++) - { - rc = zmq_ctx_set(ctx, ZMQ_THREAD_AFFINITY_CPU_ADD, cpus_add[idx]); + int cpus_add[] = {0, 1}; + for (unsigned int idx = 0; idx < sizeof (cpus_add) / sizeof (cpus_add[0]); + idx++) { + rc = zmq_ctx_set (ctx, ZMQ_THREAD_AFFINITY_CPU_ADD, cpus_add[idx]); assert (rc == 0); } // you can also remove CPUs from list of affinities: - int cpus_remove[] = { 1 }; - for (unsigned int idx=0; idx < sizeof(cpus_remove)/sizeof(cpus_remove[0]); idx++) - { - rc = zmq_ctx_set(ctx, ZMQ_THREAD_AFFINITY_CPU_REMOVE, cpus_remove[idx]); + int cpus_remove[] = {1}; + for (unsigned int idx = 0; + idx < sizeof (cpus_remove) / sizeof (cpus_remove[0]); idx++) { + rc = + zmq_ctx_set (ctx, ZMQ_THREAD_AFFINITY_CPU_REMOVE, cpus_remove[idx]); assert (rc == 0); } #endif @@ -136,7 +141,7 @@ void test_ctx_thread_opts(void* ctx) #ifdef ZMQ_THREAD_NAME_PREFIX // test thread name prefix: - rc = zmq_ctx_set(ctx, ZMQ_THREAD_NAME_PREFIX, 1234); + rc = zmq_ctx_set (ctx, ZMQ_THREAD_NAME_PREFIX, 1234); assert (rc == 0); #endif } @@ -144,7 +149,7 @@ void test_ctx_thread_opts(void* ctx) int main (void) { - setup_test_environment(); + setup_test_environment (); int rc; // Set up our context and sockets @@ -154,20 +159,20 @@ int main (void) assert (zmq_ctx_get (ctx, ZMQ_MAX_SOCKETS) == ZMQ_MAX_SOCKETS_DFLT); #if defined(ZMQ_USE_SELECT) assert (zmq_ctx_get (ctx, ZMQ_SOCKET_LIMIT) == FD_SETSIZE - 1); -#elif defined(ZMQ_USE_POLL) || defined(ZMQ_USE_EPOLL) \ - || defined(ZMQ_USE_DEVPOLL) || defined(ZMQ_USE_KQUEUE) +#elif defined(ZMQ_USE_POLL) || defined(ZMQ_USE_EPOLL) \ + || defined(ZMQ_USE_DEVPOLL) || defined(ZMQ_USE_KQUEUE) assert (zmq_ctx_get (ctx, ZMQ_SOCKET_LIMIT) == 65535); #endif assert (zmq_ctx_get (ctx, ZMQ_IO_THREADS) == ZMQ_IO_THREADS_DFLT); assert (zmq_ctx_get (ctx, ZMQ_IPV6) == 0); -#if defined (ZMQ_MSG_T_SIZE) +#if defined(ZMQ_MSG_T_SIZE) assert (zmq_ctx_get (ctx, ZMQ_MSG_T_SIZE) == sizeof (zmq_msg_t)); #endif rc = zmq_ctx_set (ctx, ZMQ_IPV6, true); assert (zmq_ctx_get (ctx, ZMQ_IPV6) == 1); - test_ctx_thread_opts(ctx); + test_ctx_thread_opts (ctx); void *router = zmq_socket (ctx, ZMQ_ROUTER); int value; @@ -184,8 +189,10 @@ int main (void) #if WAIT_FOR_BACKGROUND_THREAD_INSPECTION // this is useful when you want to use an external tool (like top or taskset) to view // properties of the background threads - printf ("Sleeping for 100sec. You can now use 'top -H -p $(pgrep -f test_ctx_options)' and 'taskset -pc ' to view ZMQ background thread properties.\n"); - sleep(100); + printf ("Sleeping for 100sec. You can now use 'top -H -p $(pgrep -f " + "test_ctx_options)' and 'taskset -pc ' " + "to view ZMQ background thread properties.\n"); + sleep (100); #endif rc = zmq_ctx_set (ctx, ZMQ_BLOCKY, false); diff --git a/tests/test_dgram.cpp b/tests/test_dgram.cpp index 04e080b675..f092b2746a 100644 --- a/tests/test_dgram.cpp +++ b/tests/test_dgram.cpp @@ -54,8 +54,8 @@ int main (void) void *ctx = zmq_ctx_new (); assert (ctx); - char* message_string; - char* address; + char *message_string; + char *address; void *sender = zmq_socket (ctx, ZMQ_DGRAM); void *listener = zmq_socket (ctx, ZMQ_DGRAM); @@ -73,16 +73,16 @@ int main (void) str_send_to (sender, "Is someone there ?", strrchr (ENDPOINT_4, '/') + 1); str_recv_from (listener, &message_string, &address); - assert (strcmp(message_string, "Is someone there ?") == 0); - assert (strcmp(address, strrchr (ENDPOINT_5, '/') + 1) == 0); + assert (strcmp (message_string, "Is someone there ?") == 0); + assert (strcmp (address, strrchr (ENDPOINT_5, '/') + 1) == 0); free (message_string); str_send_to (listener, "Yes, there is !", address); free (address); str_recv_from (sender, &message_string, &address); - assert (strcmp(message_string, "Yes, there is !") == 0); - assert (strcmp(address, strrchr (ENDPOINT_4, '/') + 1) == 0); + assert (strcmp (message_string, "Yes, there is !") == 0); + assert (strcmp (address, strrchr (ENDPOINT_4, '/') + 1) == 0); free (message_string); free (address); @@ -95,5 +95,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_diffserv.cpp b/tests/test_diffserv.cpp index 244b82b96c..70db2c8360 100644 --- a/tests/test_diffserv.cpp +++ b/tests/test_diffserv.cpp @@ -34,11 +34,11 @@ int main (void) int rc; int tos = 0x28; int o_tos; - size_t tos_size = sizeof(tos); + size_t tos_size = sizeof (tos); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -80,6 +80,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; - + return 0; } diff --git a/tests/test_disconnect_inproc.cpp b/tests/test_disconnect_inproc.cpp index 5102831676..d3c52e2d40 100644 --- a/tests/test_disconnect_inproc.cpp +++ b/tests/test_disconnect_inproc.cpp @@ -30,53 +30,62 @@ #include "testutil.hpp" /// Initialize a zeromq message with a given null-terminated string -#define ZMQ_PREPARE_STRING(msg, data, size) \ -zmq_msg_init(&msg) && printf("zmq_msg_init: %s\n", zmq_strerror(errno)); \ -zmq_msg_init_size (&msg, size + 1) && printf("zmq_msg_init_size: %s\n",zmq_strerror(errno)); \ -memcpy(zmq_msg_data(&msg), data, size + 1); +#define ZMQ_PREPARE_STRING(msg, data, size) \ + \ + zmq_msg_init (&msg) \ + && printf ("zmq_msg_init: %s\n", zmq_strerror (errno)); \ + \ + zmq_msg_init_size (&msg, size + 1) \ + && printf ("zmq_msg_init_size: %s\n", zmq_strerror (errno)); \ + \ + memcpy (zmq_msg_data (&msg), data, size + 1); // TODO: this code fails to meet our style guidelines, and needs rewriting static int publicationsReceived = 0; static bool isSubscribed = false; -int main(int, char**) { - setup_test_environment(); - void* context = zmq_ctx_new(); - void* pubSocket; - void* subSocket; - - (pubSocket = zmq_socket(context, ZMQ_XPUB)) || printf("zmq_socket: %s\n", zmq_strerror(errno)); - (subSocket = zmq_socket(context, ZMQ_SUB)) || printf("zmq_socket: %s\n", zmq_strerror(errno)); - zmq_setsockopt(subSocket, ZMQ_SUBSCRIBE, "foo", 3) && printf("zmq_setsockopt: %s\n",zmq_strerror(errno)); - - zmq_bind(pubSocket, "inproc://someInProcDescriptor") && printf("zmq_bind: %s\n", zmq_strerror(errno)); +int main (int, char **) +{ + setup_test_environment (); + void *context = zmq_ctx_new (); + void *pubSocket; + void *subSocket; + + (pubSocket = zmq_socket (context, ZMQ_XPUB)) + || printf ("zmq_socket: %s\n", zmq_strerror (errno)); + (subSocket = zmq_socket (context, ZMQ_SUB)) + || printf ("zmq_socket: %s\n", zmq_strerror (errno)); + zmq_setsockopt (subSocket, ZMQ_SUBSCRIBE, "foo", 3) + && printf ("zmq_setsockopt: %s\n", zmq_strerror (errno)); + + zmq_bind (pubSocket, "inproc://someInProcDescriptor") + && printf ("zmq_bind: %s\n", zmq_strerror (errno)); //zmq_bind(pubSocket, "tcp://127.0.0.1:30010") && printf("zmq_bind: %s\n", zmq_strerror(errno)); - + int more; - size_t more_size = sizeof(more); + size_t more_size = sizeof (more); int iteration = 0; - + while (1) { - zmq_pollitem_t items [] = { - { subSocket, 0, ZMQ_POLLIN, 0 }, // read publications - { pubSocket, 0, ZMQ_POLLIN, 0 }, // read subscriptions + zmq_pollitem_t items[] = { + {subSocket, 0, ZMQ_POLLIN, 0}, // read publications + {pubSocket, 0, ZMQ_POLLIN, 0}, // read subscriptions }; int rc = zmq_poll (items, 2, 100); - - if (items [1].revents & ZMQ_POLLIN) { + + if (items[1].revents & ZMQ_POLLIN) { while (1) { zmq_msg_t msg; zmq_msg_init (&msg); zmq_msg_recv (&msg, pubSocket, 0); - char* buffer = (char*)zmq_msg_data(&msg); + char *buffer = (char *) zmq_msg_data (&msg); if (buffer[0] == 0) { - assert(isSubscribed); + assert (isSubscribed); isSubscribed = false; - } - else { - assert(!isSubscribed); + } else { + assert (!isSubscribed); isSubscribed = true; } @@ -84,7 +93,7 @@ int main(int, char**) { zmq_msg_close (&msg); if (!more) - break; // Last message part + break; // Last message part } } @@ -95,42 +104,48 @@ int main(int, char**) { zmq_msg_recv (&msg, subSocket, 0); zmq_getsockopt (subSocket, ZMQ_RCVMORE, &more, &more_size); zmq_msg_close (&msg); - + if (!more) { publicationsReceived++; - break; // Last message part + break; // Last message part } } } if (iteration == 1) { - zmq_connect(subSocket, "inproc://someInProcDescriptor") && printf("zmq_connect: %s\n", zmq_strerror(errno)); + zmq_connect (subSocket, "inproc://someInProcDescriptor") + && printf ("zmq_connect: %s\n", zmq_strerror (errno)); msleep (SETTLE_TIME); } if (iteration == 4) { - zmq_disconnect(subSocket, "inproc://someInProcDescriptor") && printf("zmq_disconnect(%d): %s\n", errno, zmq_strerror(errno)); + zmq_disconnect (subSocket, "inproc://someInProcDescriptor") + && printf ("zmq_disconnect(%d): %s\n", errno, + zmq_strerror (errno)); } if (iteration > 4 && rc == 0) break; - + zmq_msg_t channelEnvlp; - ZMQ_PREPARE_STRING(channelEnvlp, "foo", 3); - zmq_msg_send (&channelEnvlp, pubSocket, ZMQ_SNDMORE) >= 0 || printf("zmq_msg_send: %s\n",zmq_strerror(errno)); - zmq_msg_close(&channelEnvlp) && printf("zmq_msg_close: %s\n",zmq_strerror(errno)); + ZMQ_PREPARE_STRING (channelEnvlp, "foo", 3); + zmq_msg_send (&channelEnvlp, pubSocket, ZMQ_SNDMORE) >= 0 + || printf ("zmq_msg_send: %s\n", zmq_strerror (errno)); + zmq_msg_close (&channelEnvlp) + && printf ("zmq_msg_close: %s\n", zmq_strerror (errno)); zmq_msg_t message; - ZMQ_PREPARE_STRING(message, "this is foo!", 12); - zmq_msg_send (&message, pubSocket, 0) >= 0 || printf("zmq_msg_send: %s\n",zmq_strerror(errno)); - zmq_msg_close(&message) && printf("zmq_msg_close: %s\n",zmq_strerror(errno)); + ZMQ_PREPARE_STRING (message, "this is foo!", 12); + zmq_msg_send (&message, pubSocket, 0) >= 0 + || printf ("zmq_msg_send: %s\n", zmq_strerror (errno)); + zmq_msg_close (&message) + && printf ("zmq_msg_close: %s\n", zmq_strerror (errno)); iteration++; } - assert(publicationsReceived == 3); - assert(!isSubscribed); + assert (publicationsReceived == 3); + assert (!isSubscribed); + + zmq_close (pubSocket) && printf ("zmq_close: %s", zmq_strerror (errno)); + zmq_close (subSocket) && printf ("zmq_close: %s", zmq_strerror (errno)); - zmq_close(pubSocket) && printf("zmq_close: %s", zmq_strerror(errno)); - zmq_close(subSocket) && printf("zmq_close: %s", zmq_strerror(errno)); - - zmq_ctx_term(context); + zmq_ctx_term (context); return 0; } - diff --git a/tests/test_filter_ipc.cpp b/tests/test_filter_ipc.cpp index 6bfc7cb65b..2d67672a50 100644 --- a/tests/test_filter_ipc.cpp +++ b/tests/test_filter_ipc.cpp @@ -32,7 +32,7 @@ static void bounce_fail (void *server, void *client) { const char *content = "12345678ABCDEFGH12345678abcdefgh"; - char buffer [32]; + char buffer[32]; // Send message from client to server int rc = zmq_send (client, content, 32, ZMQ_SNDMORE); @@ -68,12 +68,11 @@ static void run_test (int opt, T optval, int expected_error, int bounce_test) assert (sb); if (opt) { - rc = zmq_setsockopt(sb, opt, &optval, sizeof (optval)); + rc = zmq_setsockopt (sb, opt, &optval, sizeof (optval)); if (expected_error) { assert (rc == -1); assert (zmq_errno () == expected_error); - } - else + } else assert (rc == 0); } @@ -95,13 +94,13 @@ static void run_test (int opt, T optval, int expected_error, int bounce_test) assert (rc == 0); if (bounce_test) { - const char* endpoint = "ipc://test_filter_ipc.sock"; + const char *endpoint = "ipc://test_filter_ipc.sock"; int rc = zmq_bind (sb, endpoint); assert (rc == 0); rc = zmq_connect (sc, endpoint); assert (rc == 0); - + if (bounce_test > 0) bounce (sb, sc); else @@ -116,8 +115,8 @@ static void run_test (int opt, T optval, int expected_error, int bounce_test) int main (void) { -#if !defined (ZMQ_HAVE_WINDOWS) - setup_test_environment(); +#if !defined(ZMQ_HAVE_WINDOWS) + setup_test_environment (); // No filters run_test (0, 0, 0, 1); @@ -125,9 +124,9 @@ int main (void) #if defined ZMQ_HAVE_SO_PEERCRED || defined ZMQ_HAVE_LOCAL_PEERCRED // Get the group and supplimental groups of the process owner gid_t groups[100]; - int ngroups = getgroups(100, groups); + int ngroups = getgroups (100, groups); assert (ngroups != -1); - gid_t group = getgid(), supgroup = group, notgroup = group + 1; + gid_t group = getgid (), supgroup = group, notgroup = group + 1; for (int i = 0; i < ngroups; i++) { if (supgroup == group && group != groups[i]) supgroup = groups[i]; @@ -136,24 +135,24 @@ int main (void) } // Test filter with UID of process owner - run_test (ZMQ_IPC_FILTER_UID, getuid(), 0, 1); + run_test (ZMQ_IPC_FILTER_UID, getuid (), 0, 1); // Test filter with UID of another (possibly non-existent) user - run_test (ZMQ_IPC_FILTER_UID, getuid() + 1, 0, -1); + run_test (ZMQ_IPC_FILTER_UID, getuid () + 1, 0, -1); // Test filter with GID of process owner run_test (ZMQ_IPC_FILTER_GID, group, 0, 1); // Test filter with supplimental group of process owner run_test (ZMQ_IPC_FILTER_GID, supgroup, 0, 1); // Test filter with GID of another (possibly non-existent) group run_test (ZMQ_IPC_FILTER_GID, notgroup, 0, -1); -# if defined ZMQ_HAVE_SO_PEERCRED +#if defined ZMQ_HAVE_SO_PEERCRED // Test filter with PID of current process - run_test (ZMQ_IPC_FILTER_PID, getpid(), 0, 1); + run_test (ZMQ_IPC_FILTER_PID, getpid (), 0, 1); // Test filter with PID of another (possibly non-existent) process - run_test (ZMQ_IPC_FILTER_PID, getpid() + 1, 0, -1); -# else + run_test (ZMQ_IPC_FILTER_PID, getpid () + 1, 0, -1); +#else // Setup of PID filter should fail with operation not supported error - run_test (ZMQ_IPC_FILTER_PID, getpid(), EINVAL, 0); -# endif + run_test (ZMQ_IPC_FILTER_PID, getpid (), EINVAL, 0); +#endif #else run_test (ZMQ_IPC_FILTER_UID, 0, EINVAL, 0); run_test (ZMQ_IPC_FILTER_GID, 0, EINVAL, 0); @@ -161,6 +160,5 @@ int main (void) #endif // defined ZMQ_HAVE_SO_PEERCRED || defined ZMQ_HAVE_LOCAL_PEERCRED #endif - return 0 ; + return 0; } - diff --git a/tests/test_fork.cpp b/tests/test_fork.cpp index 4b9fbc2c98..4dbe7853ad 100644 --- a/tests/test_fork.cpp +++ b/tests/test_fork.cpp @@ -36,11 +36,11 @@ char connect_address[MAX_SOCKET_STRING]; int main (void) { -#if !defined (ZMQ_HAVE_WINDOWS) +#if !defined(ZMQ_HAVE_WINDOWS) setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); - + // Create and bind pull socket to receive messages void *pull = zmq_socket (ctx, ZMQ_PULL); assert (pull); @@ -67,23 +67,22 @@ int main (void) int count; for (count = 0; count < NUM_MESSAGES; count++) zmq_send (push, "Hello", 5, 0); - + zmq_close (push); zmq_ctx_destroy (child_ctx); exit (0); - } - else { + } else { // Parent process int count; for (count = 0; count < NUM_MESSAGES; count++) { - char buffer [5]; + char buffer[5]; int num_bytes = zmq_recv (pull, buffer, 5, 0); assert (num_bytes == 5); } int child_status; while (true) { rc = waitpid (pid, &child_status, 0); - if (rc == -1 && errno == EINTR) + if (rc == -1 && errno == EINTR) continue; assert (rc > 0); // Verify the status code of the child was zero diff --git a/tests/test_getsockopt_memset.cpp b/tests/test_getsockopt_memset.cpp index 50b69a14cd..0da0bfacc9 100644 --- a/tests/test_getsockopt_memset.cpp +++ b/tests/test_getsockopt_memset.cpp @@ -27,9 +27,9 @@ int main (void) { int64_t more; - size_t more_size = sizeof(more); + size_t more_size = sizeof (more); - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -43,9 +43,9 @@ int main (void) rc = zmq_connect (sc, "inproc://a"); assert (rc == 0); - memset(&more, 0xFF, sizeof(int64_t)); - zmq_getsockopt(sc, ZMQ_RCVMORE, &more, &more_size); - assert (more_size == sizeof(int)); + memset (&more, 0xFF, sizeof (int64_t)); + zmq_getsockopt (sc, ZMQ_RCVMORE, &more, &more_size); + assert (more_size == sizeof (int)); assert (more == 0); @@ -60,5 +60,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_heartbeats.cpp b/tests/test_heartbeats.cpp index 59bbae0e6d..7ba46a8331 100644 --- a/tests/test_heartbeats.cpp +++ b/tests/test_heartbeats.cpp @@ -18,14 +18,14 @@ */ #include "testutil.hpp" -#if defined (ZMQ_HAVE_WINDOWS) -# include -# include -# include -# define close closesocket +#if defined(ZMQ_HAVE_WINDOWS) +#include +#include +#include +#define close closesocket typedef SOCKET raw_socket; #else -# include +#include typedef int raw_socket; #endif @@ -33,8 +33,7 @@ typedef int raw_socket; // by reference, if not null, and event number by value. Returns -1 // in case of error. -static int -get_monitor_event (void *monitor) +static int get_monitor_event (void *monitor) { for (int i = 0; i < 2; i++) { // First frame in message contains event number and value @@ -43,7 +42,7 @@ get_monitor_event (void *monitor) assert (rc == 0); if (zmq_msg_recv (&msg, monitor, ZMQ_DONTWAIT) == -1) { msleep (SETTLE_TIME); - continue; // Interruped, presumably + continue; // Interruped, presumably } assert (zmq_msg_more (&msg)); @@ -54,7 +53,7 @@ get_monitor_event (void *monitor) rc = zmq_msg_init (&msg); assert (rc == 0); if (zmq_msg_recv (&msg, monitor, 0) == -1) { - return -1; // Interruped, presumably + return -1; // Interruped, presumably } assert (!zmq_msg_more (&msg)); @@ -63,46 +62,47 @@ get_monitor_event (void *monitor) return -1; } -static void -recv_with_retry (raw_socket fd, char *buffer, int bytes) { - int received = 0; +static void recv_with_retry (raw_socket fd, char *buffer, int bytes) +{ + int received = 0; while (true) { - int rc = recv(fd, buffer + received, bytes - received, 0); - assert(rc > 0); - received += rc; - assert(received <= bytes); - if (received == bytes) break; + int rc = recv (fd, buffer + received, bytes - received, 0); + assert (rc > 0); + received += rc; + assert (received <= bytes); + if (received == bytes) + break; } } -static void -mock_handshake (raw_socket fd) { - const uint8_t zmtp_greeting[33] = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f, 3, 0, 'N', 'U', 'L', 'L', 0 }; - char buffer [128]; - memset (buffer, 0, sizeof(buffer)); - memcpy (buffer, zmtp_greeting, sizeof(zmtp_greeting)); +static void mock_handshake (raw_socket fd) +{ + const uint8_t zmtp_greeting[33] = {0xff, 0, 0, 0, 0, 0, 0, 0, 0, + 0x7f, 3, 0, 'N', 'U', 'L', 'L', 0}; + char buffer[128]; + memset (buffer, 0, sizeof (buffer)); + memcpy (buffer, zmtp_greeting, sizeof (zmtp_greeting)); int rc = send (fd, buffer, 64, 0); assert (rc == 64); recv_with_retry (fd, buffer, 64); - const uint8_t zmtp_ready [43] = { - 4, 41, 5, 'R', 'E', 'A', 'D', 'Y', 11, 'S', 'o', 'c', 'k', 'e', 't', '-', 'T', 'y', 'p', 'e', - 0, 0, 0, 6, 'D', 'E', 'A', 'L', 'E', 'R', 8, 'I', 'd', 'e', 'n', 't', 'i', 't', 'y', - 0, 0, 0, 0 - }; + const uint8_t zmtp_ready[43] = { + 4, 41, 5, 'R', 'E', 'A', 'D', 'Y', 11, 'S', 'o', 'c', 'k', 'e', 't', + '-', 'T', 'y', 'p', 'e', 0, 0, 0, 6, 'D', 'E', 'A', 'L', 'E', 'R', + 8, 'I', 'd', 'e', 'n', 't', 'i', 't', 'y', 0, 0, 0, 0}; - memset(buffer, 0, sizeof(buffer)); - memcpy(buffer, zmtp_ready, 43); - rc = send(fd, buffer, 43, 0); + memset (buffer, 0, sizeof (buffer)); + memcpy (buffer, zmtp_ready, 43); + rc = send (fd, buffer, 43, 0); assert (rc == 43); - recv_with_retry(fd, buffer, 43); + recv_with_retry (fd, buffer, 43); } -static void -setup_curve (void * socket, int is_server) { +static void setup_curve (void *socket, int is_server) +{ const char *secret_key; const char *public_key; const char *server_key; @@ -111,24 +111,31 @@ setup_curve (void * socket, int is_server) { secret_key = "JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6"; public_key = "rq:rM>}U?@Lns47E1%kR.o@n%FcmmsL/@{H8]yf7"; server_key = NULL; - } - else { + } else { secret_key = "D:)Q[IlAW!ahhC2ac:9*A}h:p?([4%wOTJ%JR%cs"; public_key = "Yne@$w-vo -1); // Mock a ZMTP 3 client so we can forcibly time out a connection mock_handshake (s); // By now everything should report as connected - rc = get_monitor_event(server_mon); + rc = get_monitor_event (server_mon); assert (rc == ZMQ_EVENT_ACCEPTED); // We should have been disconnected - rc = get_monitor_event(server_mon); + rc = get_monitor_event (server_mon); assert (rc == ZMQ_EVENT_DISCONNECTED); - close(s); + close (s); rc = zmq_close (server); assert (rc == 0); @@ -229,8 +236,7 @@ test_heartbeat_timeout (void) // to a server that is not doing any heartbeating. Then we sleep, // if the server disconnects the client, then we know the TTL did // its thing correctly. -static void -test_heartbeat_ttl (void) +static void test_heartbeat_ttl (void) { int rc, value; char my_endpoint[MAX_SOCKET_STRING]; @@ -239,9 +245,9 @@ test_heartbeat_ttl (void) void *ctx = zmq_ctx_new (); assert (ctx); - void * server, * server_mon, *client; + void *server, *server_mon, *client; prep_server_socket (ctx, 0, 0, &server, &server_mon, my_endpoint, - MAX_SOCKET_STRING); + MAX_SOCKET_STRING); client = zmq_socket (ctx, ZMQ_DEALER); assert (client != NULL); @@ -286,8 +292,7 @@ test_heartbeat_ttl (void) // This checks for normal operation - that is pings and pongs being // exchanged normally. There should be an accepted event on the server, // and then no event afterwards. -static void -test_heartbeat_notimeout (int is_curve) +static void test_heartbeat_notimeout (int is_curve) { int rc; char my_endpoint[MAX_SOCKET_STRING]; @@ -296,20 +301,20 @@ test_heartbeat_notimeout (int is_curve) void *ctx = zmq_ctx_new (); assert (ctx); - void * server, * server_mon; - prep_server_socket(ctx, 1, is_curve, &server, &server_mon, my_endpoint, - MAX_SOCKET_STRING); + void *server, *server_mon; + prep_server_socket (ctx, 1, is_curve, &server, &server_mon, my_endpoint, + MAX_SOCKET_STRING); - void * client = zmq_socket (ctx, ZMQ_DEALER); + void *client = zmq_socket (ctx, ZMQ_DEALER); if (is_curve) - setup_curve(client, 0); + setup_curve (client, 0); rc = zmq_connect (client, my_endpoint); // Give it a sec to connect and handshake msleep (SETTLE_TIME); // By now everything should report as connected - rc = get_monitor_event(server_mon); + rc = get_monitor_event (server_mon); assert (rc == ZMQ_EVENT_ACCEPTED); // We should still be connected because pings and pongs are happenin' diff --git a/tests/test_hwm.cpp b/tests/test_hwm.cpp index 08bc85c865..5f65dea4a8 100644 --- a/tests/test_hwm.cpp +++ b/tests/test_hwm.cpp @@ -31,7 +31,11 @@ const int MAX_SENDS = 10000; -enum TestType { BIND_FIRST, CONNECT_FIRST }; +enum TestType +{ + BIND_FIRST, + CONNECT_FIRST +}; int test_defaults () { @@ -58,7 +62,7 @@ int test_defaults () ++send_count; msleep (SETTLE_TIME); - + // Now receive all sent messages int recv_count = 0; while (zmq_recv (bind_socket, NULL, 0, ZMQ_DONTWAIT) == 0) @@ -87,12 +91,12 @@ int count_msg (int send_hwm, int recv_hwm, TestType testType) void *bind_socket; void *connect_socket; - if (testType == BIND_FIRST) - { + if (testType == BIND_FIRST) { // Set up bind socket bind_socket = zmq_socket (ctx, ZMQ_PULL); assert (bind_socket); - rc = zmq_setsockopt (bind_socket, ZMQ_RCVHWM, &recv_hwm, sizeof (recv_hwm)); + rc = zmq_setsockopt (bind_socket, ZMQ_RCVHWM, &recv_hwm, + sizeof (recv_hwm)); assert (rc == 0); rc = zmq_bind (bind_socket, "inproc://a"); assert (rc == 0); @@ -100,17 +104,17 @@ int count_msg (int send_hwm, int recv_hwm, TestType testType) // Set up connect socket connect_socket = zmq_socket (ctx, ZMQ_PUSH); assert (connect_socket); - rc = zmq_setsockopt (connect_socket, ZMQ_SNDHWM, &send_hwm, sizeof (send_hwm)); + rc = zmq_setsockopt (connect_socket, ZMQ_SNDHWM, &send_hwm, + sizeof (send_hwm)); assert (rc == 0); rc = zmq_connect (connect_socket, "inproc://a"); assert (rc == 0); - } - else - { + } else { // Set up connect socket connect_socket = zmq_socket (ctx, ZMQ_PUSH); assert (connect_socket); - rc = zmq_setsockopt (connect_socket, ZMQ_SNDHWM, &send_hwm, sizeof (send_hwm)); + rc = zmq_setsockopt (connect_socket, ZMQ_SNDHWM, &send_hwm, + sizeof (send_hwm)); assert (rc == 0); rc = zmq_connect (connect_socket, "inproc://a"); assert (rc == 0); @@ -118,7 +122,8 @@ int count_msg (int send_hwm, int recv_hwm, TestType testType) // Set up bind socket bind_socket = zmq_socket (ctx, ZMQ_PULL); assert (bind_socket); - rc = zmq_setsockopt (bind_socket, ZMQ_RCVHWM, &recv_hwm, sizeof (recv_hwm)); + rc = zmq_setsockopt (bind_socket, ZMQ_RCVHWM, &recv_hwm, + sizeof (recv_hwm)); assert (rc == 0); rc = zmq_bind (bind_socket, "inproc://a"); assert (rc == 0); @@ -126,7 +131,8 @@ int count_msg (int send_hwm, int recv_hwm, TestType testType) // Send until we block int send_count = 0; - while (send_count < MAX_SENDS && zmq_send (connect_socket, NULL, 0, ZMQ_DONTWAIT) == 0) + while (send_count < MAX_SENDS + && zmq_send (connect_socket, NULL, 0, ZMQ_DONTWAIT) == 0) ++send_count; // Now receive all sent messages @@ -159,12 +165,12 @@ int count_msg (int send_hwm, int recv_hwm, TestType testType) int test_inproc_bind_first (int send_hwm, int recv_hwm) { - return count_msg(send_hwm, recv_hwm, BIND_FIRST); + return count_msg (send_hwm, recv_hwm, BIND_FIRST); } int test_inproc_connect_first (int send_hwm, int recv_hwm) { - return count_msg(send_hwm, recv_hwm, CONNECT_FIRST); + return count_msg (send_hwm, recv_hwm, CONNECT_FIRST); } int test_inproc_connect_and_close_first (int send_hwm, int recv_hwm) @@ -176,14 +182,16 @@ int test_inproc_connect_and_close_first (int send_hwm, int recv_hwm) // Set up connect socket void *connect_socket = zmq_socket (ctx, ZMQ_PUSH); assert (connect_socket); - rc = zmq_setsockopt (connect_socket, ZMQ_SNDHWM, &send_hwm, sizeof (send_hwm)); + rc = + zmq_setsockopt (connect_socket, ZMQ_SNDHWM, &send_hwm, sizeof (send_hwm)); assert (rc == 0); rc = zmq_connect (connect_socket, "inproc://a"); assert (rc == 0); // Send until we block int send_count = 0; - while (send_count < MAX_SENDS && zmq_send (connect_socket, NULL, 0, ZMQ_DONTWAIT) == 0) + while (send_count < MAX_SENDS + && zmq_send (connect_socket, NULL, 0, ZMQ_DONTWAIT) == 0) ++send_count; // Close connect @@ -231,7 +239,8 @@ int test_inproc_bind_and_close_first (int send_hwm, int /* recv_hwm */) // Send until we block int send_count = 0; - while (send_count < MAX_SENDS && zmq_send (bind_socket, NULL, 0, ZMQ_DONTWAIT) == 0) + while (send_count < MAX_SENDS + && zmq_send (bind_socket, NULL, 0, ZMQ_DONTWAIT) == 0) ++send_count; // Close bind @@ -267,8 +276,8 @@ int test_inproc_bind_and_close_first (int send_hwm, int /* recv_hwm */) int main (void) { - setup_test_environment(); - + setup_test_environment (); + int count; // Default values are 1000 on send and 1000 one receive, so 2000 total diff --git a/tests/test_hwm_pubsub.cpp b/tests/test_hwm_pubsub.cpp index c012da9684..d34dc9cb6c 100644 --- a/tests/test_hwm_pubsub.cpp +++ b/tests/test_hwm_pubsub.cpp @@ -51,11 +51,12 @@ int test_defaults (int send_hwm, int msgCnt) //set a hwm on publisher rc = zmq_setsockopt (pub_socket, ZMQ_SNDHWM, &send_hwm, sizeof (send_hwm)); - rc = zmq_setsockopt( sub_socket, ZMQ_SUBSCRIBE, 0, 0); + rc = zmq_setsockopt (sub_socket, ZMQ_SUBSCRIBE, 0, 0); // Send until we block int send_count = 0; - while (send_count < msgCnt && zmq_send (pub_socket, NULL, 0, ZMQ_DONTWAIT) == 0) + while (send_count < msgCnt + && zmq_send (pub_socket, NULL, 0, ZMQ_DONTWAIT) == 0) ++send_count; msleep (SETTLE_TIME); @@ -81,17 +82,15 @@ int test_defaults (int send_hwm, int msgCnt) return recv_count; } -int receive( void* socket) +int receive (void *socket) { - int recv_count = 0; - // Now receive all sent messages - while (0 == zmq_recv (socket, NULL, 0, ZMQ_DONTWAIT)) - { - ++recv_count; - } - - return recv_count; + int recv_count = 0; + // Now receive all sent messages + while (0 == zmq_recv (socket, NULL, 0, ZMQ_DONTWAIT)) { + ++recv_count; + } + return recv_count; } @@ -116,28 +115,24 @@ int test_blocking (int send_hwm, int msgCnt) //set a hwm on publisher rc = zmq_setsockopt (pub_socket, ZMQ_SNDHWM, &send_hwm, sizeof (send_hwm)); int wait = 1; - rc = zmq_setsockopt (pub_socket, ZMQ_XPUB_NODROP, &wait, sizeof(wait)); - rc = zmq_setsockopt( sub_socket, ZMQ_SUBSCRIBE, 0, 0); + rc = zmq_setsockopt (pub_socket, ZMQ_XPUB_NODROP, &wait, sizeof (wait)); + rc = zmq_setsockopt (sub_socket, ZMQ_SUBSCRIBE, 0, 0); // Send until we block int send_count = 0; int recv_count = 0; - while (send_count < msgCnt ) - { + while (send_count < msgCnt) { rc = zmq_send (pub_socket, NULL, 0, ZMQ_DONTWAIT); - if( rc == 0) - { + if (rc == 0) { ++send_count; - } - else if( -1 == rc) - { - assert(EAGAIN == errno); - recv_count += receive(sub_socket); - assert(recv_count == send_count); + } else if (-1 == rc) { + assert (EAGAIN == errno); + recv_count += receive (sub_socket); + assert (recv_count == send_count); } } - recv_count += receive(sub_socket); + recv_count += receive (sub_socket); // Clean up rc = zmq_close (sub_socket); @@ -182,14 +177,15 @@ void test_reset_hwm () assert (rc == 0); rc = zmq_connect (sub_socket, my_endpoint); assert (rc == 0); - rc = zmq_setsockopt( sub_socket, ZMQ_SUBSCRIBE, 0, 0); + rc = zmq_setsockopt (sub_socket, ZMQ_SUBSCRIBE, 0, 0); assert (rc == 0); msleep (SETTLE_TIME); // Send messages int send_count = 0; - while (send_count < first_count && zmq_send (pub_socket, NULL, 0, ZMQ_DONTWAIT) == 0) + while (send_count < first_count + && zmq_send (pub_socket, NULL, 0, ZMQ_DONTWAIT) == 0) ++send_count; assert (first_count == send_count); @@ -197,8 +193,7 @@ void test_reset_hwm () // Now receive all sent messages int recv_count = 0; - while (0 == zmq_recv (sub_socket, NULL, 0, ZMQ_DONTWAIT)) - { + while (0 == zmq_recv (sub_socket, NULL, 0, ZMQ_DONTWAIT)) { ++recv_count; } assert (first_count == recv_count); @@ -207,7 +202,8 @@ void test_reset_hwm () // Send messages send_count = 0; - while (send_count < second_count && zmq_send (pub_socket, NULL, 0, ZMQ_DONTWAIT) == 0) + while (send_count < second_count + && zmq_send (pub_socket, NULL, 0, ZMQ_DONTWAIT) == 0) ++send_count; assert (second_count == send_count); @@ -215,8 +211,7 @@ void test_reset_hwm () // Now receive all sent messages recv_count = 0; - while (0 == zmq_recv (sub_socket, NULL, 0, ZMQ_DONTWAIT)) - { + while (0 == zmq_recv (sub_socket, NULL, 0, ZMQ_DONTWAIT)) { ++recv_count; } assert (second_count == recv_count); @@ -234,16 +229,16 @@ void test_reset_hwm () int main (void) { - setup_test_environment(); - + setup_test_environment (); + int count; // send 1000 msg on hwm 1000, receive 1000 - count = test_defaults (1000,1000); + count = test_defaults (1000, 1000); assert (count == 1000); - // send 6000 msg on hwm 2000, drops above hwm, only receive hwm - count = test_blocking (2000,6000); + // send 6000 msg on hwm 2000, drops above hwm, only receive hwm + count = test_blocking (2000, 6000); assert (count == 6000); // hwm should apply to the messages that have already been received diff --git a/tests/test_immediate.cpp b/tests/test_immediate.cpp index dc472255e6..e40711f84b 100644 --- a/tests/test_immediate.cpp +++ b/tests/test_immediate.cpp @@ -31,27 +31,27 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); int val; int rc; char buffer[16]; size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; - // TEST 1. + // TEST 1. // First we're going to attempt to send messages to two // pipes, one connected, the other not. We should see // the PUSH load balancing to both pipes, and hence half // of the messages getting queued, as connect() creates a - // pipe immediately. - - void *context = zmq_ctx_new(); + // pipe immediately. + + void *context = zmq_ctx_new (); assert (context); - void *to = zmq_socket(context, ZMQ_PULL); + void *to = zmq_socket (context, ZMQ_PULL); assert (to); // Bind the one valid receiver val = 0; - rc = zmq_setsockopt(to, ZMQ_LINGER, &val, sizeof(val)); + rc = zmq_setsockopt (to, ZMQ_LINGER, &val, sizeof (val)); assert (rc == 0); rc = zmq_bind (to, "tcp://127.0.0.1:*"); assert (rc == 0); @@ -60,14 +60,14 @@ int main (void) // Create a socket pushing to two endpoints - only 1 message should arrive. void *from = zmq_socket (context, ZMQ_PUSH); - assert(from); + assert (from); val = 0; zmq_setsockopt (from, ZMQ_LINGER, &val, sizeof (val)); // This pipe will not connect rc = zmq_connect (from, "tcp://localhost:5556"); assert (rc == 0); - // This pipe will + // This pipe will rc = zmq_connect (from, my_endpoint); assert (rc == 0); @@ -90,7 +90,7 @@ int main (void) while (true) { rc = zmq_recv (to, &buffer, sizeof (buffer), 0); if (rc == -1) - break; // Break when we didn't get a message + break; // Break when we didn't get a message seen++; } assert (seen == 5); @@ -105,13 +105,13 @@ int main (void) assert (rc == 0); // TEST 2 - // This time we will do the same thing, connect two pipes, - // one of which will succeed in connecting to a bound - // receiver, the other of which will fail. However, we will - // also set the delay attach on connect flag, which should + // This time we will do the same thing, connect two pipes, + // one of which will succeed in connecting to a bound + // receiver, the other of which will fail. However, we will + // also set the delay attach on connect flag, which should // cause the pipe attachment to be delayed until the connection - // succeeds. - context = zmq_ctx_new(); + // succeeds. + context = zmq_ctx_new (); // Bind the valid socket to = zmq_socket (context, ZMQ_PULL); @@ -123,7 +123,7 @@ int main (void) assert (rc == 0); val = 0; - rc = zmq_setsockopt (to, ZMQ_LINGER, &val, sizeof(val)); + rc = zmq_setsockopt (to, ZMQ_LINGER, &val, sizeof (val)); assert (rc == 0); // Create a socket pushing to two endpoints - all messages should arrive. @@ -131,12 +131,12 @@ int main (void) assert (from); val = 0; - rc = zmq_setsockopt (from, ZMQ_LINGER, &val, sizeof(val)); + rc = zmq_setsockopt (from, ZMQ_LINGER, &val, sizeof (val)); assert (rc == 0); // Set the key flag val = 1; - rc = zmq_setsockopt (from, ZMQ_IMMEDIATE, &val, sizeof(val)); + rc = zmq_setsockopt (from, ZMQ_IMMEDIATE, &val, sizeof (val)); assert (rc == 0); // Connect to the invalid socket @@ -153,12 +153,12 @@ int main (void) } rc = zmq_setsockopt (to, ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); - + seen = 0; while (true) { rc = zmq_recv (to, &buffer, sizeof (buffer), 0); if (rc == -1) - break; // Break when we didn't get a message + break; // Break when we didn't get a message seen++; } assert (seen == 10); @@ -168,7 +168,7 @@ int main (void) rc = zmq_close (to); assert (rc == 0); - + rc = zmq_ctx_term (context); assert (rc == 0); @@ -206,17 +206,17 @@ int main (void) assert (rc == 5); rc = zmq_recv (frontend, buffer, 255, 0); assert (rc == 5); - + // Send message from frontend to backend rc = zmq_send (frontend, "Hello", 5, ZMQ_DONTWAIT); assert (rc == 5); - + rc = zmq_close (backend); assert (rc == 0); // Give time to process disconnect msleep (SETTLE_TIME * 10); - + // Send a message, should fail rc = zmq_send (frontend, "Hello", 5, ZMQ_DONTWAIT); assert (rc == -1); @@ -238,10 +238,10 @@ int main (void) // After the reconnect, should succeed rc = zmq_send (frontend, "Hello", 5, ZMQ_DONTWAIT); assert (rc == 5); - + rc = zmq_close (backend); assert (rc == 0); - + rc = zmq_close (frontend); assert (rc == 0); diff --git a/tests/test_inproc_connect.cpp b/tests/test_inproc_connect.cpp index 6778c92776..9bd69291d6 100644 --- a/tests/test_inproc_connect.cpp +++ b/tests/test_inproc_connect.cpp @@ -49,8 +49,8 @@ static void pusher (void *ctx) static void simult_conn (void *payload) { // Pull out arguments - context followed by endpoint string - void* ctx = (void*)((void**)payload)[0]; - char* endpt = (char*)((void**)payload)[1]; + void *ctx = (void *) ((void **) payload)[0]; + char *endpt = (char *) ((void **) payload)[1]; // Connect void *connectSocket = zmq_socket (ctx, ZMQ_SUB); @@ -66,8 +66,8 @@ static void simult_conn (void *payload) static void simult_bind (void *payload) { // Pull out arguments - context followed by endpoint string - void* ctx = (void*)((void**)payload)[0]; - char* endpt = (char*)((void**)payload)[1]; + void *ctx = (void *) ((void **) payload)[0]; + char *endpt = (char *) ((void **) payload)[1]; // Bind void *bindSocket = zmq_socket (ctx, ZMQ_PUB); @@ -223,7 +223,7 @@ void test_connect_before_bind_ctx_term () assert (connectSocket); char ep[20]; - sprintf(ep, "inproc://cbbrr%d", i); + sprintf (ep, "inproc://cbbrr%d", i); int rc = zmq_connect (connectSocket, ep); assert (rc == 0); @@ -243,18 +243,17 @@ void test_multiple_connects () assert (ctx); int rc; - void *connectSocket [no_of_connects]; + void *connectSocket[no_of_connects]; // Connect first - for (unsigned int i = 0; i < no_of_connects; ++i) - { - connectSocket [i] = zmq_socket (ctx, ZMQ_PUSH); - assert (connectSocket [i]); - rc = zmq_connect (connectSocket [i], "inproc://multiple"); + for (unsigned int i = 0; i < no_of_connects; ++i) { + connectSocket[i] = zmq_socket (ctx, ZMQ_PUSH); + assert (connectSocket[i]); + rc = zmq_connect (connectSocket[i], "inproc://multiple"); assert (rc == 0); // Queue up some data - rc = zmq_send_const (connectSocket [i], "foobar", 6, 0); + rc = zmq_send_const (connectSocket[i], "foobar", 6, 0); assert (rc == 6); } @@ -264,8 +263,7 @@ void test_multiple_connects () rc = zmq_bind (bindSocket, "inproc://multiple"); assert (rc == 0); - for (unsigned int i = 0; i < no_of_connects; ++i) - { + for (unsigned int i = 0; i < no_of_connects; ++i) { // Read pending message zmq_msg_t msg; rc = zmq_msg_init (&msg); @@ -277,9 +275,8 @@ void test_multiple_connects () } // Cleanup - for (unsigned int i = 0; i < no_of_connects; ++i) - { - rc = zmq_close (connectSocket [i]); + for (unsigned int i = 0; i < no_of_connects; ++i) { + rc = zmq_close (connectSocket[i]); assert (rc == 0); } @@ -297,12 +294,11 @@ void test_multiple_threads () assert (ctx); int rc; - void *threads [no_of_threads]; + void *threads[no_of_threads]; // Connect first - for (unsigned int i = 0; i < no_of_threads; ++i) - { - threads [i] = zmq_threadstart (&pusher, ctx); + for (unsigned int i = 0; i < no_of_threads; ++i) { + threads[i] = zmq_threadstart (&pusher, ctx); } // Now bind @@ -311,8 +307,7 @@ void test_multiple_threads () rc = zmq_bind (bindSocket, "inproc://sink"); assert (rc == 0); - for (unsigned int i = 0; i < no_of_threads; ++i) - { + for (unsigned int i = 0; i < no_of_threads; ++i) { // Read pending message zmq_msg_t msg; rc = zmq_msg_init (&msg); @@ -324,9 +319,8 @@ void test_multiple_threads () } // Cleanup - for (unsigned int i = 0; i < no_of_threads; ++i) - { - zmq_threadclose (threads [i]); + for (unsigned int i = 0; i < no_of_threads; ++i) { + zmq_threadclose (threads[i]); } rc = zmq_close (bindSocket); @@ -342,30 +336,29 @@ void test_simultaneous_connect_bind_threads () void *ctx = zmq_ctx_new (); assert (ctx); - void *threads[no_of_times*2]; + void *threads[no_of_times * 2]; void *thr_args[no_of_times][2]; char endpts[no_of_times][20]; // Set up thread arguments: context followed by endpoint string - for (unsigned int i = 0; i < no_of_times; ++i) - { - thr_args[i][0] = (void*) ctx; - thr_args[i][1] = (void*) endpts[i]; + for (unsigned int i = 0; i < no_of_times; ++i) { + thr_args[i][0] = (void *) ctx; + thr_args[i][1] = (void *) endpts[i]; sprintf (endpts[i], "inproc://foo_%d", i); } // Spawn all threads as simultaneously as possible - for (unsigned int i = 0; i < no_of_times; ++i) - { - threads[i*2+0] = zmq_threadstart (&simult_conn, (void*)thr_args[i]); - threads[i*2+1] = zmq_threadstart (&simult_bind, (void*)thr_args[i]); + for (unsigned int i = 0; i < no_of_times; ++i) { + threads[i * 2 + 0] = + zmq_threadstart (&simult_conn, (void *) thr_args[i]); + threads[i * 2 + 1] = + zmq_threadstart (&simult_bind, (void *) thr_args[i]); } // Close all threads - for (unsigned int i = 0; i < no_of_times; ++i) - { - zmq_threadclose (threads[i*2+0]); - zmq_threadclose (threads[i*2+1]); + for (unsigned int i = 0; i < no_of_times; ++i) { + zmq_threadclose (threads[i * 2 + 0]); + zmq_threadclose (threads[i * 2 + 1]); } int rc = zmq_ctx_term (ctx); diff --git a/tests/test_invalid_rep.cpp b/tests/test_invalid_rep.cpp index 843a941502..7d079eaa89 100644 --- a/tests/test_invalid_rep.cpp +++ b/tests/test_invalid_rep.cpp @@ -31,17 +31,17 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); // Create REQ/ROUTER wiring. void *ctx = zmq_ctx_new (); assert (ctx); - + void *router_socket = zmq_socket (ctx, ZMQ_ROUTER); assert (router_socket); - + void *req_socket = zmq_socket (ctx, ZMQ_REQ); assert (req_socket); - + int linger = 0; int rc = zmq_setsockopt (router_socket, ZMQ_LINGER, &linger, sizeof (int)); assert (rc == 0); @@ -57,10 +57,10 @@ int main (void) assert (rc == 1); // Receive the request. - char addr [32]; + char addr[32]; int addr_size; - char bottom [1]; - char body [1]; + char bottom[1]; + char body[1]; addr_size = zmq_recv (router_socket, addr, sizeof (addr), 0); assert (addr_size >= 0); rc = zmq_recv (router_socket, bottom, sizeof (bottom), 0); @@ -83,7 +83,7 @@ int main (void) // Check whether we've got the valid reply. rc = zmq_recv (req_socket, body, sizeof (body), 0); assert (rc == 1); - assert (body [0] == 'b'); + assert (body[0] == 'b'); // Tear down the wiring. rc = zmq_close (router_socket); @@ -95,4 +95,3 @@ int main (void) return 0; } - diff --git a/tests/test_iov.cpp b/tests/test_iov.cpp index 305f1f0ccd..0daae87e4b 100644 --- a/tests/test_iov.cpp +++ b/tests/test_iov.cpp @@ -33,13 +33,14 @@ #if defined ZMQ_HAVE_UIO #include #else -struct iovec { +struct iovec +{ void *iov_base; size_t iov_len; }; #endif -void do_check(void* sb, void* sc, size_t msg_size) +void do_check (void *sb, void *sc, size_t msg_size) { assert (sb && sc && msg_size > 0); @@ -58,8 +59,7 @@ void do_check(void* sb, void* sc, size_t msg_size) struct iovec send_iov[num_messages]; char *buf = (char *) malloc (msg_size * num_messages); - for (int i = 0; i < num_messages; i++) - { + for (int i = 0; i < num_messages; i++) { send_iov[i].iov_base = &buf[i * msg_size]; send_iov[i].iov_len = msg_size; memcpy (send_iov[i].iov_base, ref_msg, msg_size); @@ -83,7 +83,7 @@ void do_check(void* sb, void* sc, size_t msg_size) // so, whilst the former sends the number of bytes successfully sent from // the last message, which does not hold much sense from a batch send // perspective; hence the assert checks if rc is same as msg_size. - assert ((size_t)rc == msg_size); + assert ((size_t) rc == msg_size); // zmq_recviov(3) single-shot struct iovec recv_iov[num_messages]; @@ -105,11 +105,10 @@ void do_check(void* sb, void* sc, size_t msg_size) rc = zmq_recviov (sb, recv_iov, &recv_count, 0); assert (rc == num_messages); - for (int i = 0; i < num_messages; i++) - { + for (int i = 0; i < num_messages; i++) { assert (recv_iov[i].iov_base); assert (memcmp (ref_msg, recv_iov[i].iov_base, msg_size) == 0); - free(recv_iov[i].iov_base); + free (recv_iov[i].iov_base); } assert (send_count == recv_count); @@ -124,16 +123,16 @@ int main (void) void *ctx = zmq_ctx_new (); assert (ctx); int rc; - + void *sb = zmq_socket (ctx, ZMQ_PULL); assert (sb); - + rc = zmq_bind (sb, "inproc://a"); assert (rc == 0); msleep (SETTLE_TIME); void *sc = zmq_socket (ctx, ZMQ_PUSH); - + rc = zmq_connect (sc, "inproc://a"); assert (rc == 0); diff --git a/tests/test_ipc_wildcard.cpp b/tests/test_ipc_wildcard.cpp index 6e37405665..2068a1a402 100644 --- a/tests/test_ipc_wildcard.cpp +++ b/tests/test_ipc_wildcard.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -40,7 +40,7 @@ int main (void) int rc = zmq_bind (sb, "ipc://*"); assert (rc == 0); - char endpoint [200]; + char endpoint[200]; size_t size = sizeof (endpoint); rc = zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, endpoint, &size); assert (rc == 0); @@ -49,7 +49,7 @@ int main (void) assert (sc); rc = zmq_connect (sc, endpoint); assert (rc == 0); - + bounce (sb, sc); rc = zmq_close (sc); @@ -61,5 +61,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_issue_566.cpp b/tests/test_issue_566.cpp index 9cba83b843..682d520c7a 100644 --- a/tests/test_issue_566.cpp +++ b/tests/test_issue_566.cpp @@ -36,8 +36,8 @@ int main (void) { - setup_test_environment(); - + setup_test_environment (); + size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx1 = zmq_ctx_new (); @@ -46,7 +46,7 @@ int main (void) void *ctx2 = zmq_ctx_new (); assert (ctx2); - void *router = zmq_socket (ctx1, ZMQ_ROUTER); + void *router = zmq_socket (ctx1, ZMQ_ROUTER); int on = 1; int rc = zmq_setsockopt (router, ZMQ_ROUTER_MANDATORY, &on, sizeof (on)); assert (rc == 0); @@ -54,13 +54,13 @@ int main (void) assert (rc != -1); rc = zmq_getsockopt (router, ZMQ_LAST_ENDPOINT, my_endpoint, &len); assert (rc == 0); - + // Repeat often enough to be sure this works as it should for (int cycle = 0; cycle < 100; cycle++) { // Create dealer with unique explicit routing id // We assume the router learns this out-of-band void *dealer = zmq_socket (ctx2, ZMQ_DEALER); - char routing_id [10]; + char routing_id[10]; sprintf (routing_id, "%09d", cycle); rc = zmq_setsockopt (dealer, ZMQ_ROUTING_ID, routing_id, 10); assert (rc == 0); @@ -85,7 +85,7 @@ int main (void) assert (rc == 5); break; } - uint8_t buffer [5]; + uint8_t buffer[5]; rc = zmq_recv (dealer, buffer, 5, 0); assert (rc == 5); assert (memcmp (buffer, "HELLO", 5) == 0); diff --git a/tests/test_last_endpoint.cpp b/tests/test_last_endpoint.cpp index 0c922b48ad..502f567c4e 100644 --- a/tests/test_last_endpoint.cpp +++ b/tests/test_last_endpoint.cpp @@ -33,7 +33,7 @@ static void do_bind_and_verify (void *s, const char *endpoint) { int rc = zmq_bind (s, endpoint); assert (rc == 0); - char reported [255]; + char reported[255]; size_t size = 255; rc = zmq_getsockopt (s, ZMQ_LAST_ENDPOINT, reported, &size); assert (rc == 0 && strcmp (reported, endpoint) == 0); @@ -41,7 +41,7 @@ static void do_bind_and_verify (void *s, const char *endpoint) int main (void) { - setup_test_environment(); + setup_test_environment (); // Create the infrastructure void *ctx = zmq_ctx_new (); assert (ctx); @@ -57,10 +57,9 @@ int main (void) rc = zmq_close (sb); assert (rc == 0); - + rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } - diff --git a/tests/test_many_sockets.cpp b/tests/test_many_sockets.cpp index 2fa3be9b49..816942e509 100644 --- a/tests/test_many_sockets.cpp +++ b/tests/test_many_sockets.cpp @@ -39,7 +39,7 @@ void test_system_max () const int no_of_sockets = 2 * 65536; void *ctx = zmq_ctx_new (); zmq_ctx_set (ctx, ZMQ_MAX_SOCKETS, no_of_sockets); - std::vector sockets; + std::vector sockets; while (true) { void *socket = zmq_socket (ctx, ZMQ_PAIR); @@ -56,7 +56,7 @@ void test_system_max () } // Clean up. for (unsigned int i = 0; i < sockets.size (); ++i) - zmq_close (sockets [i]); + zmq_close (sockets[i]); zmq_ctx_destroy (ctx); } @@ -65,7 +65,7 @@ void test_zmq_default_max () { // Keep allocating sockets until we hit the default limit void *ctx = zmq_ctx_new (); - std::vector sockets; + std::vector sockets; while (true) { void *socket = zmq_socket (ctx, ZMQ_PAIR); @@ -84,7 +84,7 @@ void test_zmq_default_max () // Clean up for (unsigned int i = 0; i < sockets.size (); ++i) - zmq_close (sockets [i]); + zmq_close (sockets[i]); zmq_ctx_destroy (ctx); } diff --git a/tests/test_metadata.cpp b/tests/test_metadata.cpp index 6b6a73dc6a..c622aad984 100644 --- a/tests/test_metadata.cpp +++ b/tests/test_metadata.cpp @@ -29,19 +29,16 @@ #include "testutil.hpp" -static void -zap_handler (void *handler) +static void zap_handler (void *handler) { - uint8_t metadata [] = { - 5, 'H', 'e', 'l', 'l', 'o', - 0, 0, 0, 5, 'W', 'o', 'r', 'l', 'd' - }; + uint8_t metadata[] = {5, 'H', 'e', 'l', 'l', 'o', 0, 0, + 0, 5, 'W', 'o', 'r', 'l', 'd'}; // Process ZAP requests forever while (true) { char *version = s_recv (handler); if (!version) - break; // Terminating + break; // Terminating char *sequence = s_recv (handler); char *domain = s_recv (handler); @@ -59,12 +56,11 @@ zap_handler (void *handler) s_sendmore (handler, "OK"); s_sendmore (handler, "anonymous"); zmq_send (handler, metadata, sizeof (metadata), 0); - } - else { + } else { s_sendmore (handler, "400"); s_sendmore (handler, "BAD DOMAIN"); s_sendmore (handler, ""); - s_send (handler, ""); + s_send (handler, ""); } free (version); free (sequence); @@ -78,7 +74,7 @@ zap_handler (void *handler) int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); diff --git a/tests/test_monitor.cpp b/tests/test_monitor.cpp index f5515239d4..dc1e5a4c1b 100644 --- a/tests/test_monitor.cpp +++ b/tests/test_monitor.cpp @@ -32,13 +32,13 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); assert (ctx); - + // We'll monitor these two sockets void *client = zmq_socket (ctx, ZMQ_DEALER); assert (client); @@ -67,7 +67,7 @@ int main (void) assert (rc == 0); rc = zmq_connect (server_mon, "inproc://monitor-server"); assert (rc == 0); - + // Now do a basic ping test rc = zmq_bind (server, "tcp://127.0.0.1:*"); assert (rc == 0); @@ -80,7 +80,7 @@ int main (void) // Close client and server close_zero_linger (client); close_zero_linger (server); - + // Now collect and check events from both sockets int event = get_monitor_event (client_mon, NULL, NULL); if (event == ZMQ_EVENT_CONNECT_DELAYED) @@ -100,17 +100,17 @@ int main (void) event = get_monitor_event (server_mon, NULL, NULL); // Sometimes the server sees the client closing before it gets closed. if (event != ZMQ_EVENT_DISCONNECTED) { - assert (event == ZMQ_EVENT_CLOSED); - event = get_monitor_event (server_mon, NULL, NULL); + assert (event == ZMQ_EVENT_CLOSED); + event = get_monitor_event (server_mon, NULL, NULL); } if (event != ZMQ_EVENT_DISCONNECTED) { - assert (event == ZMQ_EVENT_MONITOR_STOPPED); + assert (event == ZMQ_EVENT_MONITOR_STOPPED); } - + // Close down the sockets close_zero_linger (client_mon); close_zero_linger (server_mon); zmq_ctx_term (ctx); - return 0 ; + return 0; } diff --git a/tests/test_msg_ffn.cpp b/tests/test_msg_ffn.cpp index 2cab9d669a..a4b828b982 100644 --- a/tests/test_msg_ffn.cpp +++ b/tests/test_msg_ffn.cpp @@ -29,14 +29,16 @@ #include "testutil.hpp" -void ffn(void *data, void *hint) { +void ffn (void *data, void *hint) +{ // Signal that ffn has been called by writing "freed" to hint - (void) data; // Suppress 'unused' warnings at compile time - memcpy(hint, (void *) "freed", 5); + (void) data; // Suppress 'unused' warnings at compile time + memcpy (hint, (void *) "freed", 5); } -int main (void) { - setup_test_environment(); +int main (void) +{ + setup_test_environment (); // Create the infrastructure void *ctx = zmq_ctx_new (); assert (ctx); @@ -62,74 +64,74 @@ int main (void) { zmq_msg_t msg; char hint[5]; char data[255]; - memset(data, 0, 255); - memcpy(data, (void *) "data", 4); - memcpy(hint, (void *) "hint", 4); - rc = zmq_msg_init_data(&msg, (void *)data, 255, ffn, (void*)hint); + memset (data, 0, 255); + memcpy (data, (void *) "data", 4); + memcpy (hint, (void *) "hint", 4); + rc = zmq_msg_init_data (&msg, (void *) data, 255, ffn, (void *) hint); assert (rc == 0); - rc = zmq_msg_close(&msg); + rc = zmq_msg_close (&msg); assert (rc == 0); msleep (SETTLE_TIME); - assert (memcmp(hint, "freed", 5) == 0); - memcpy(hint, (void *) "hint", 4); + assert (memcmp (hint, "freed", 5) == 0); + memcpy (hint, (void *) "hint", 4); // Making and closing a copy triggers ffn zmq_msg_t msg2; - zmq_msg_init(&msg2); - rc = zmq_msg_init_data(&msg, (void *)data, 255, ffn, (void *)hint); + zmq_msg_init (&msg2); + rc = zmq_msg_init_data (&msg, (void *) data, 255, ffn, (void *) hint); assert (rc == 0); - rc = zmq_msg_copy(&msg2, &msg); + rc = zmq_msg_copy (&msg2, &msg); assert (rc == 0); - rc = zmq_msg_close(&msg2); + rc = zmq_msg_close (&msg2); assert (rc == 0); - rc = zmq_msg_close(&msg); + rc = zmq_msg_close (&msg); assert (rc == 0); msleep (SETTLE_TIME); - assert (memcmp(hint, "freed", 5) == 0); - memcpy(hint, (void *) "hint", 4); + assert (memcmp (hint, "freed", 5) == 0); + memcpy (hint, (void *) "hint", 4); // Test that sending a message triggers ffn - rc = zmq_msg_init_data(&msg, (void *)data, 255, ffn, (void *)hint); + rc = zmq_msg_init_data (&msg, (void *) data, 255, ffn, (void *) hint); assert (rc == 0); - zmq_msg_send(&msg, dealer, 0); + zmq_msg_send (&msg, dealer, 0); char buf[255]; - rc = zmq_recv(router, buf, 255, 0); + rc = zmq_recv (router, buf, 255, 0); assert (rc > -1); - rc = zmq_recv(router, buf, 255, 0); + rc = zmq_recv (router, buf, 255, 0); assert (rc == 255); - assert (memcmp(data, buf, 4) == 0); + assert (memcmp (data, buf, 4) == 0); msleep (SETTLE_TIME); - assert (memcmp(hint, "freed", 5) == 0); - memcpy(hint, (void *) "hint", 4); - rc = zmq_msg_close(&msg); + assert (memcmp (hint, "freed", 5) == 0); + memcpy (hint, (void *) "hint", 4); + rc = zmq_msg_close (&msg); assert (rc == 0); // Sending a copy of a message triggers ffn - rc = zmq_msg_init(&msg2); + rc = zmq_msg_init (&msg2); assert (rc == 0); - rc = zmq_msg_init_data(&msg, (void *)data, 255, ffn, (void *)hint); + rc = zmq_msg_init_data (&msg, (void *) data, 255, ffn, (void *) hint); assert (rc == 0); - rc = zmq_msg_copy(&msg2, &msg); + rc = zmq_msg_copy (&msg2, &msg); assert (rc == 0); - zmq_msg_send(&msg, dealer, 0); - rc = zmq_recv(router, buf, 255, 0); + zmq_msg_send (&msg, dealer, 0); + rc = zmq_recv (router, buf, 255, 0); assert (rc > -1); - rc = zmq_recv(router, buf, 255, 0); + rc = zmq_recv (router, buf, 255, 0); assert (rc == 255); - assert (memcmp(data, buf, 4) == 0); - rc = zmq_msg_close(&msg2); + assert (memcmp (data, buf, 4) == 0); + rc = zmq_msg_close (&msg2); assert (rc == 0); - rc = zmq_msg_close(&msg); + rc = zmq_msg_close (&msg); assert (rc == 0); msleep (SETTLE_TIME); - assert (memcmp(hint, "freed", 5) == 0); - memcpy(hint, (void *) "hint", 4); + assert (memcmp (hint, "freed", 5) == 0); + memcpy (hint, (void *) "hint", 4); // Deallocate the infrastructure. rc = zmq_close (router); @@ -140,6 +142,5 @@ int main (void) { rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } - diff --git a/tests/test_msg_flags.cpp b/tests/test_msg_flags.cpp index a4b674474e..27f7fed0fd 100644 --- a/tests/test_msg_flags.cpp +++ b/tests/test_msg_flags.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); // Create the infrastructure void *ctx = zmq_ctx_new (); assert (ctx); @@ -77,40 +77,40 @@ int main (void) // Test ZMQ_SHARED property (case 1, refcounted messages) zmq_msg_t msg_a; - rc = zmq_msg_init_size(&msg_a, 1024); // large enough to be a type_lmsg + rc = zmq_msg_init_size (&msg_a, 1024); // large enough to be a type_lmsg assert (rc == 0); // Message is not shared - rc = zmq_msg_get(&msg_a, ZMQ_SHARED); + rc = zmq_msg_get (&msg_a, ZMQ_SHARED); assert (rc == 0); zmq_msg_t msg_b; - rc = zmq_msg_init(&msg_b); + rc = zmq_msg_init (&msg_b); assert (rc == 0); - rc = zmq_msg_copy(&msg_b, &msg_a); + rc = zmq_msg_copy (&msg_b, &msg_a); assert (rc == 0); // Message is now shared - rc = zmq_msg_get(&msg_b, ZMQ_SHARED); + rc = zmq_msg_get (&msg_b, ZMQ_SHARED); assert (rc == 1); // cleanup - rc = zmq_msg_close(&msg_a); + rc = zmq_msg_close (&msg_a); assert (rc == 0); - rc = zmq_msg_close(&msg_b); + rc = zmq_msg_close (&msg_b); assert (rc == 0); // Test ZMQ_SHARED property (case 2, constant data messages) - rc = zmq_msg_init_data(&msg_a, (void*) "TEST", 5, 0, 0); + rc = zmq_msg_init_data (&msg_a, (void *) "TEST", 5, 0, 0); assert (rc == 0); // Message reports as shared - rc = zmq_msg_get(&msg_a, ZMQ_SHARED); + rc = zmq_msg_get (&msg_a, ZMQ_SHARED); assert (rc == 1); // cleanup - rc = zmq_msg_close(&msg_a); + rc = zmq_msg_close (&msg_a); assert (rc == 0); // Deallocate the infrastructure. @@ -122,6 +122,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } - diff --git a/tests/test_pair_inproc.cpp b/tests/test_pair_inproc.cpp index 9bbf329bae..a891caf7f3 100644 --- a/tests/test_pair_inproc.cpp +++ b/tests/test_pair_inproc.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -44,28 +44,28 @@ int main (void) assert (sc); rc = zmq_connect (sc, "inproc://a"); assert (rc == 0); - + bounce (sb, sc); - + // Test zmq_send_const rc = zmq_send_const (sb, "foo", 3, ZMQ_SNDMORE); assert (rc == 3); rc = zmq_send_const (sb, "foobar", 6, 0); assert (rc == 6); - + zmq_msg_t msg; rc = zmq_msg_init (&msg); assert (rc == 0); rc = zmq_msg_recv (&msg, sc, 0); assert (rc == 3); assert (zmq_msg_size (&msg) == 3); - void* data = zmq_msg_data (&msg); + void *data = zmq_msg_data (&msg); assert (memcmp ("foo", data, 3) == 0); rc = zmq_msg_recv (&msg, sc, 0); assert (rc == 6); data = zmq_msg_data (&msg); assert (memcmp ("foobar", data, 6) == 0); - + // Cleanup rc = zmq_close (sc); @@ -77,5 +77,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_pair_ipc.cpp b/tests/test_pair_ipc.cpp index 12022f776b..84a38e0959 100644 --- a/tests/test_pair_ipc.cpp +++ b/tests/test_pair_ipc.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -44,7 +44,7 @@ int main (void) assert (sc); rc = zmq_connect (sc, "ipc:///tmp/test_pair_ipc"); assert (rc == 0); - + bounce (sb, sc); rc = zmq_close (sc); @@ -56,5 +56,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_pair_tcp.cpp b/tests/test_pair_tcp.cpp index 1a7bb02cf5..aadd9ad8cf 100644 --- a/tests/test_pair_tcp.cpp +++ b/tests/test_pair_tcp.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); @@ -48,7 +48,7 @@ int main (void) assert (sc); rc = zmq_connect (sc, my_endpoint); assert (rc == 0); - + bounce (sb, sc); rc = zmq_close (sc); @@ -60,5 +60,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_pair_tipc.cpp b/tests/test_pair_tipc.cpp index b494050c12..9c37317171 100644 --- a/tests/test_pair_tipc.cpp +++ b/tests/test_pair_tipc.cpp @@ -58,5 +58,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_pair_vmci.cpp b/tests/test_pair_vmci.cpp index d3a8cf4861..c190deaec9 100644 --- a/tests/test_pair_vmci.cpp +++ b/tests/test_pair_vmci.cpp @@ -35,22 +35,22 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); std::stringstream s; - s << "vmci://" << VMCISock_GetLocalCID() << ":" << 5560; - std::string endpoint = s.str(); + s << "vmci://" << VMCISock_GetLocalCID () << ":" << 5560; + std::string endpoint = s.str (); void *sb = zmq_socket (ctx, ZMQ_PAIR); assert (sb); - int rc = zmq_bind (sb, endpoint.c_str()); + int rc = zmq_bind (sb, endpoint.c_str ()); assert (rc == 0); void *sc = zmq_socket (ctx, ZMQ_PAIR); assert (sc); - rc = zmq_connect (sc, endpoint.c_str()); + rc = zmq_connect (sc, endpoint.c_str ()); assert (rc == 0); bounce (sb, sc); diff --git a/tests/test_poller.cpp b/tests/test_poller.cpp index d738ce979b..abc59e9352 100644 --- a/tests/test_poller.cpp +++ b/tests/test_poller.cpp @@ -31,16 +31,25 @@ // duplicated from fd.hpp #ifdef ZMQ_HAVE_WINDOWS -#if defined _MSC_VER &&_MSC_VER <= 1400 - typedef UINT_PTR fd_t; - enum {retired_fd = (fd_t)(~0)}; +#if defined _MSC_VER && _MSC_VER <= 1400 +typedef UINT_PTR fd_t; +enum +{ + retired_fd = (fd_t) (~0) +}; #else - typedef SOCKET fd_t; - enum {retired_fd = (fd_t)INVALID_SOCKET}; +typedef SOCKET fd_t; +enum +{ + retired_fd = (fd_t) INVALID_SOCKET +}; #endif #else - typedef int fd_t; - enum {retired_fd = -1}; +typedef int fd_t; +enum +{ + retired_fd = -1 +}; #endif void test_null_poller_pointers (void *ctx) @@ -71,7 +80,7 @@ void test_null_poller_pointers (void *ctx) fd_t fd; size_t fd_size = sizeof fd; - rc = zmq_getsockopt(socket, ZMQ_FD, &fd, &fd_size); + rc = zmq_getsockopt (socket, ZMQ_FD, &fd, &fd_size); assert (rc == 0); rc = zmq_poller_add_fd (NULL, fd, NULL, ZMQ_POLLIN); @@ -119,7 +128,7 @@ void test_null_socket_pointers () assert (rc == -1 && errno == ENOTSOCK); fd_t null_socket_fd = retired_fd; - + rc = zmq_poller_add_fd (poller, null_socket_fd, NULL, ZMQ_POLLIN); assert (rc == -1 && errno == EBADF); @@ -150,8 +159,8 @@ void test_null_event_pointers (void *ctx) rc = zmq_poller_wait_all (poller, NULL, 1, 0); assert (rc == -1 && errno == EFAULT); - // TODO this causes an assertion, which is not consistent if the number - // of events may be 0, the pointer should be allowed to by NULL in that + // TODO this causes an assertion, which is not consistent if the number + // of events may be 0, the pointer should be allowed to by NULL in that // case too #if 0 rc = zmq_poller_wait_all (poller, NULL, 0, 0); @@ -165,7 +174,7 @@ void test_null_event_pointers (void *ctx) assert (rc == 0); } -void test_add_modify_remove_corner_cases(void *ctx) +void test_add_modify_remove_corner_cases (void *ctx) { void *poller = zmq_poller_new (); assert (poller != NULL); @@ -231,11 +240,11 @@ void test_wait_corner_cases (void) assert (poller != NULL); zmq_poller_event_t event; - int rc = zmq_poller_wait(poller, &event, 0); + int rc = zmq_poller_wait (poller, &event, 0); assert (rc == -1 && errno == EAGAIN); // this can never return since no socket was registered, and should yield an error - rc = zmq_poller_wait(poller, &event, -1); + rc = zmq_poller_wait (poller, &event, -1); assert (rc == -1 && errno == EFAULT); rc = zmq_poller_wait_all (poller, &event, -1, 0); diff --git a/tests/test_probe_router.cpp b/tests/test_probe_router.cpp index 745db28ee6..ff924fc974 100644 --- a/tests/test_probe_router.cpp +++ b/tests/test_probe_router.cpp @@ -31,12 +31,12 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); assert (ctx); - + // Create server and bind to endpoint void *server = zmq_socket (ctx, ZMQ_ROUTER); assert (server); @@ -57,10 +57,10 @@ int main (void) assert (rc == 0); // We expect a routing id=X + empty message from client - unsigned char buffer [255]; + unsigned char buffer[255]; rc = zmq_recv (server, buffer, 255, 0); assert (rc == 1); - assert (buffer [0] == 'X'); + assert (buffer[0] == 'X'); rc = zmq_recv (server, buffer, 255, 0); assert (rc == 0); @@ -69,10 +69,10 @@ int main (void) assert (rc == 1); rc = zmq_send (server, "Hello", 5, 0); assert (rc == 5); - + rc = zmq_recv (client, buffer, 255, 0); assert (rc == 5); - + rc = zmq_close (server); assert (rc == 0); @@ -82,5 +82,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_proxy.cpp b/tests/test_proxy.cpp index 35247a012f..17f3c8cad3 100644 --- a/tests/test_proxy.cpp +++ b/tests/test_proxy.cpp @@ -46,11 +46,12 @@ #define CONTENT_SIZE_MAX 32 #define ROUTING_ID_SIZE 10 #define ROUTING_ID_SIZE_MAX 32 -#define QT_WORKERS 5 -#define QT_CLIENTS 3 +#define QT_WORKERS 5 +#define QT_CLIENTS 3 #define is_verbose 0 -struct thread_data { +struct thread_data +{ void *ctx; int id; }; @@ -73,17 +74,16 @@ void *g_clients_pkts_out = NULL; void *g_workers_pkts_out = NULL; -static void -client_task (void *db) +static void client_task (void *db) { - struct thread_data *databag = (struct thread_data *)db; + struct thread_data *databag = (struct thread_data *) db; // Endpoint socket gets random port to avoid test failing when port in use void *endpoint = zmq_socket (databag->ctx, ZMQ_PAIR); assert (endpoint); int linger = 0; int rc = zmq_setsockopt (endpoint, ZMQ_LINGER, &linger, sizeof (linger)); assert (rc == 0); - char endpoint_source [256]; + char endpoint_source[256]; sprintf (endpoint_source, "inproc://endpoint%d", databag->id); rc = zmq_connect (endpoint, endpoint_source); assert (rc == 0); @@ -103,11 +103,13 @@ client_task (void *db) rc = zmq_connect (control, "inproc://control"); assert (rc == 0); - char content [CONTENT_SIZE_MAX]; + char content[CONTENT_SIZE_MAX]; // Set random routing id to make tracing easier - char routing_id [ROUTING_ID_SIZE]; - sprintf (routing_id, "%04X-%04X", rand() % 0xFFFF, rand() % 0xFFFF); - rc = zmq_setsockopt (client, ZMQ_ROUTING_ID, routing_id, ROUTING_ID_SIZE); // includes '\0' as an helper for printf + char routing_id[ROUTING_ID_SIZE]; + sprintf (routing_id, "%04X-%04X", rand () % 0xFFFF, rand () % 0xFFFF); + rc = + zmq_setsockopt (client, ZMQ_ROUTING_ID, routing_id, + ROUTING_ID_SIZE); // includes '\0' as an helper for printf assert (rc == 0); linger = 0; rc = zmq_setsockopt (client, ZMQ_LINGER, &linger, sizeof (linger)); @@ -115,7 +117,8 @@ client_task (void *db) rc = zmq_connect (client, my_endpoint); assert (rc == 0); - zmq_pollitem_t items [] = { { client, 0, ZMQ_POLLIN, 0 }, { control, 0, ZMQ_POLLIN, 0 } }; + zmq_pollitem_t items[] = {{client, 0, ZMQ_POLLIN, 0}, + {control, 0, ZMQ_POLLIN, 0}}; int request_nbr = 0; bool run = true; bool keep_sending = true; @@ -124,25 +127,30 @@ client_task (void *db) int centitick; for (centitick = 0; centitick < 20; centitick++) { zmq_poll (items, 2, 10); - if (items [0].revents & ZMQ_POLLIN) { + if (items[0].revents & ZMQ_POLLIN) { int rcvmore; size_t sz = sizeof (rcvmore); rc = zmq_recv (client, content, CONTENT_SIZE_MAX, 0); assert (rc == CONTENT_SIZE); - if (is_verbose) printf("client receive - routing_id = %s content = %s\n", routing_id, content); + if (is_verbose) + printf ( + "client receive - routing_id = %s content = %s\n", + routing_id, content); // Check that message is still the same assert (memcmp (content, "request #", 9) == 0); rc = zmq_getsockopt (client, ZMQ_RCVMORE, &rcvmore, &sz); assert (rc == 0); assert (!rcvmore); } - if (items [1].revents & ZMQ_POLLIN) { + if (items[1].revents & ZMQ_POLLIN) { rc = zmq_recv (control, content, CONTENT_SIZE_MAX, 0); - if (rc > 0) - { - content[rc] = 0; // NULL-terminate the command string - if (is_verbose) printf("client receive - routing_id = %s command = %s\n", routing_id, content); + if (rc > 0) { + content[rc] = 0; // NULL-terminate the command string + if (is_verbose) + printf ( + "client receive - routing_id = %s command = %s\n", + routing_id, content); if (memcmp (content, "TERMINATE", 9) == 0) { run = false; break; @@ -155,11 +163,12 @@ client_task (void *db) } } - if (keep_sending) - { - sprintf(content, "request #%03d", ++request_nbr); // CONTENT_SIZE - if (is_verbose) printf("client send - routing_id = %s request #%03d\n", routing_id, request_nbr); - zmq_atomic_counter_inc(g_clients_pkts_out); + if (keep_sending) { + sprintf (content, "request #%03d", ++request_nbr); // CONTENT_SIZE + if (is_verbose) + printf ("client send - routing_id = %s request #%03d\n", + routing_id, request_nbr); + zmq_atomic_counter_inc (g_clients_pkts_out); rc = zmq_send (client, content, CONTENT_SIZE, 0); assert (rc == CONTENT_SIZE); @@ -183,8 +192,7 @@ client_task (void *db) static void server_worker (void *ctx); -void -server_task (void *ctx) +void server_task (void *ctx) { // Frontend socket talks to clients over TCP size_t len = MAX_SOCKET_STRING; @@ -217,26 +225,26 @@ server_task (void *ctx) // Launch pool of worker threads, precise number is not critical int thread_nbr; - void* threads [5]; + void *threads[5]; for (thread_nbr = 0; thread_nbr < QT_WORKERS; thread_nbr++) threads[thread_nbr] = zmq_threadstart (&server_worker, ctx); // Endpoint socket sends random port to avoid test failing when port in use - void *endpoint_receivers [QT_CLIENTS]; - char endpoint_source [256]; + void *endpoint_receivers[QT_CLIENTS]; + char endpoint_source[256]; for (int i = 0; i < QT_CLIENTS; ++i) { - endpoint_receivers [i] = zmq_socket (ctx, ZMQ_PAIR); - assert (endpoint_receivers [i]); - rc = zmq_setsockopt (endpoint_receivers [i], ZMQ_LINGER, &linger, - sizeof (linger)); + endpoint_receivers[i] = zmq_socket (ctx, ZMQ_PAIR); + assert (endpoint_receivers[i]); + rc = zmq_setsockopt (endpoint_receivers[i], ZMQ_LINGER, &linger, + sizeof (linger)); assert (rc == 0); sprintf (endpoint_source, "inproc://endpoint%d", i); - rc = zmq_bind (endpoint_receivers [i], endpoint_source); + rc = zmq_bind (endpoint_receivers[i], endpoint_source); assert (rc == 0); } for (int i = 0; i < QT_CLIENTS; ++i) { - rc = s_send (endpoint_receivers [i], my_endpoint); + rc = s_send (endpoint_receivers[i], my_endpoint); assert (rc > 0); } @@ -254,7 +262,7 @@ server_task (void *ctx) rc = zmq_close (control); assert (rc == 0); for (int i = 0; i < QT_CLIENTS; ++i) { - rc = zmq_close(endpoint_receivers [i]); + rc = zmq_close (endpoint_receivers[i]); assert (rc == 0); } } @@ -263,8 +271,7 @@ server_task (void *ctx) // of replies back, with random delays between replies: // The comments in the first column, if suppressed, makes it a poller version -static void -server_worker (void *ctx) +static void server_worker (void *ctx) { void *worker = zmq_socket (ctx, ZMQ_DEALER); assert (worker); @@ -284,17 +291,18 @@ server_worker (void *ctx) rc = zmq_connect (control, "inproc://control"); assert (rc == 0); - char content [CONTENT_SIZE_MAX]; // bigger than what we need to check that - char routing_id [ROUTING_ID_SIZE_MAX]; // the size received is the size sent + char content[CONTENT_SIZE_MAX]; // bigger than what we need to check that + char routing_id[ROUTING_ID_SIZE_MAX]; // the size received is the size sent bool run = true; bool keep_sending = true; while (run) { - rc = zmq_recv (control, content, CONTENT_SIZE_MAX, ZMQ_DONTWAIT); // usually, rc == -1 (no message) + rc = zmq_recv (control, content, CONTENT_SIZE_MAX, + ZMQ_DONTWAIT); // usually, rc == -1 (no message) if (rc > 0) { - content[rc] = 0; // NULL-terminate the command string + content[rc] = 0; // NULL-terminate the command string if (is_verbose) - printf("server_worker receives command = %s\n", content); + printf ("server_worker receives command = %s\n", content); if (memcmp (content, "TERMINATE", 9) == 0) run = false; if (memcmp (content, "STOP", 4) == 0) @@ -307,21 +315,24 @@ server_worker (void *ctx) rc = zmq_recv (worker, content, CONTENT_SIZE_MAX, 0); assert (rc == CONTENT_SIZE); if (is_verbose) - printf ("server receive - routing_id = %s content = %s\n", routing_id, content); + printf ("server receive - routing_id = %s content = %s\n", + routing_id, content); // Send 0..4 replies back - if (keep_sending) - { - int reply, replies = rand() % 5; + if (keep_sending) { + int reply, replies = rand () % 5; for (reply = 0; reply < replies; reply++) { // Sleep for some fraction of a second msleep (rand () % 10 + 1); // Send message from server to client - if (is_verbose) printf("server send - routing_id = %s reply\n", routing_id); - zmq_atomic_counter_inc(g_workers_pkts_out); + if (is_verbose) + printf ("server send - routing_id = %s reply\n", + routing_id); + zmq_atomic_counter_inc (g_workers_pkts_out); - rc = zmq_send (worker, routing_id, ROUTING_ID_SIZE, ZMQ_SNDMORE); + rc = zmq_send (worker, routing_id, ROUTING_ID_SIZE, + ZMQ_SNDMORE); assert (rc == ROUTING_ID_SIZE); rc = zmq_send (worker, content, CONTENT_SIZE, 0); assert (rc == CONTENT_SIZE); @@ -343,8 +354,8 @@ uint64_t recv_stat (void *sock, bool last) int rc = zmq_msg_init (&stats_msg); assert (rc == 0); rc = zmq_recvmsg (sock, &stats_msg, 0); - assert (rc == sizeof(uint64_t)); - memcpy(&res, zmq_msg_data(&stats_msg), zmq_msg_size(&stats_msg)); + assert (rc == sizeof (uint64_t)); + memcpy (&res, zmq_msg_data (&stats_msg), zmq_msg_size (&stats_msg)); rc = zmq_msg_close (&stats_msg); assert (rc == 0); @@ -359,7 +370,7 @@ uint64_t recv_stat (void *sock, bool last) // Utility function to interrogate the proxy: -void check_proxy_stats(void *control_proxy) +void check_proxy_stats (void *control_proxy) { zmq_proxy_stats_t total_stats; int rc; @@ -381,30 +392,36 @@ void check_proxy_stats(void *control_proxy) // check stats - if (is_verbose) - { - printf ("frontend: pkts_in=%lu bytes_in=%lu pkts_out=%lu bytes_out=%lu\n", - (unsigned long int)total_stats.frontend.msg_in, - (unsigned long int)total_stats.frontend.bytes_in, - (unsigned long int)total_stats.frontend.msg_out, - (unsigned long int)total_stats.frontend.bytes_out); - printf ("backend: pkts_in=%lu bytes_in=%lu pkts_out=%lu bytes_out=%lu\n", - (unsigned long int)total_stats.backend.msg_in, - (unsigned long int)total_stats.backend.bytes_in, - (unsigned long int)total_stats.backend.msg_out, - (unsigned long int)total_stats.backend.bytes_out); - - printf ("clients sent out %d requests\n", zmq_atomic_counter_value(g_clients_pkts_out)); - printf ("workers sent out %d replies\n", zmq_atomic_counter_value(g_workers_pkts_out)); + if (is_verbose) { + printf ( + "frontend: pkts_in=%lu bytes_in=%lu pkts_out=%lu bytes_out=%lu\n", + (unsigned long int) total_stats.frontend.msg_in, + (unsigned long int) total_stats.frontend.bytes_in, + (unsigned long int) total_stats.frontend.msg_out, + (unsigned long int) total_stats.frontend.bytes_out); + printf ( + "backend: pkts_in=%lu bytes_in=%lu pkts_out=%lu bytes_out=%lu\n", + (unsigned long int) total_stats.backend.msg_in, + (unsigned long int) total_stats.backend.bytes_in, + (unsigned long int) total_stats.backend.msg_out, + (unsigned long int) total_stats.backend.bytes_out); + + printf ("clients sent out %d requests\n", + zmq_atomic_counter_value (g_clients_pkts_out)); + printf ("workers sent out %d replies\n", + zmq_atomic_counter_value (g_workers_pkts_out)); } - assert( total_stats.frontend.msg_in == (unsigned)zmq_atomic_counter_value(g_clients_pkts_out) ); - assert( total_stats.frontend.msg_out == (unsigned)zmq_atomic_counter_value(g_workers_pkts_out) ); - assert( total_stats.backend.msg_in == (unsigned)zmq_atomic_counter_value(g_workers_pkts_out) ); - assert( total_stats.backend.msg_out == (unsigned)zmq_atomic_counter_value(g_clients_pkts_out) ); + assert (total_stats.frontend.msg_in + == (unsigned) zmq_atomic_counter_value (g_clients_pkts_out)); + assert (total_stats.frontend.msg_out + == (unsigned) zmq_atomic_counter_value (g_workers_pkts_out)); + assert (total_stats.backend.msg_in + == (unsigned) zmq_atomic_counter_value (g_workers_pkts_out)); + assert (total_stats.backend.msg_out + == (unsigned) zmq_atomic_counter_value (g_clients_pkts_out)); } - // The main thread simply starts several clients and a server, and then // waits for the server to finish. @@ -436,14 +453,14 @@ int main (void) rc = zmq_bind (control_proxy, "inproc://control_proxy"); assert (rc == 0); - void *threads [QT_CLIENTS + 1]; - struct thread_data databags [QT_CLIENTS + 1]; + void *threads[QT_CLIENTS + 1]; + struct thread_data databags[QT_CLIENTS + 1]; for (int i = 0; i < QT_CLIENTS; i++) { - databags [i].ctx = ctx; - databags [i].id = i; - threads[i] = zmq_threadstart (&client_task, &databags [i]); + databags[i].ctx = ctx; + databags[i].id = i; + threads[i] = zmq_threadstart (&client_task, &databags[i]); } - threads[QT_CLIENTS] = zmq_threadstart (&server_task, ctx); + threads[QT_CLIENTS] = zmq_threadstart (&server_task, ctx); msleep (500); // Run for 500 ms then quit @@ -452,13 +469,13 @@ int main (void) rc = zmq_send (control, "STOP", 4, 0); assert (rc == 4); - msleep(500); // Wait for all clients and workers to STOP + msleep (500); // Wait for all clients and workers to STOP #ifdef ZMQ_BUILD_DRAFT_API if (is_verbose) printf ("retrieving stats from the proxy\n"); - check_proxy_stats(control_proxy); + check_proxy_stats (control_proxy); #endif if (is_verbose) diff --git a/tests/test_proxy_single_socket.cpp b/tests/test_proxy_single_socket.cpp index bd17f8f73e..36caa1b7c3 100644 --- a/tests/test_proxy_single_socket.cpp +++ b/tests/test_proxy_single_socket.cpp @@ -30,12 +30,10 @@ #include "testutil.hpp" - // This is our server task. // It runs a proxy with a single REP socket as both frontend and backend. -void -server_task (void *ctx) +void server_task (void *ctx) { size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; @@ -75,7 +73,7 @@ int main (void) void *ctx = zmq_ctx_new (); assert (ctx); - void *server_thread = zmq_threadstart(&server_task, ctx); + void *server_thread = zmq_threadstart (&server_task, ctx); // Control socket receives terminate command from main over inproc void *control = zmq_socket (ctx, ZMQ_REP); @@ -92,15 +90,15 @@ int main (void) assert (rc == 0); char buf[255]; - rc = zmq_send(req, "msg1", 4, 0); + rc = zmq_send (req, "msg1", 4, 0); assert (rc == 4); - rc = zmq_recv(req, buf, 255, 0); + rc = zmq_recv (req, buf, 255, 0); assert (rc == 4); assert (memcmp (buf, "msg1", 4) == 0); - rc = zmq_send(req, "msg22", 5, 0); + rc = zmq_send (req, "msg22", 5, 0); assert (rc == 5); - rc = zmq_recv(req, buf, 255, 0); + rc = zmq_recv (req, buf, 255, 0); assert (rc == 5); assert (memcmp (buf, "msg22", 5) == 0); diff --git a/tests/test_proxy_terminate.cpp b/tests/test_proxy_terminate.cpp index f9fcef07c3..46140e644a 100644 --- a/tests/test_proxy_terminate.cpp +++ b/tests/test_proxy_terminate.cpp @@ -34,8 +34,7 @@ // but there is no pull on the other side, previously the proxy blocks // in writing to the backend, preventing the proxy from terminating -void -server_task (void *ctx) +void server_task (void *ctx) { size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; @@ -86,7 +85,7 @@ int main (void) void *ctx = zmq_ctx_new (); assert (ctx); - void *thread = zmq_threadstart(&server_task, ctx); + void *thread = zmq_threadstart (&server_task, ctx); // Control socket receives terminate command from main over inproc void *control = zmq_socket (ctx, ZMQ_REP); diff --git a/tests/test_pub_invert_matching.cpp b/tests/test_pub_invert_matching.cpp index 39109c75ee..32e5dee4f4 100644 --- a/tests/test_pub_invert_matching.cpp +++ b/tests/test_pub_invert_matching.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -57,31 +57,31 @@ int main (void) const char PREFIX1[] = "prefix1"; const char PREFIX2[] = "p2"; - rc = zmq_setsockopt (sub1, ZMQ_SUBSCRIBE, PREFIX1, sizeof(PREFIX1)); + rc = zmq_setsockopt (sub1, ZMQ_SUBSCRIBE, PREFIX1, sizeof (PREFIX1)); assert (rc == 0); - rc = zmq_setsockopt (sub2, ZMQ_SUBSCRIBE, PREFIX2, sizeof(PREFIX2)); + rc = zmq_setsockopt (sub2, ZMQ_SUBSCRIBE, PREFIX2, sizeof (PREFIX2)); assert (rc == 0); // Send a message with the first prefix - rc = zmq_send_const(pub, PREFIX1, sizeof(PREFIX1), 0); - assert (rc == sizeof(PREFIX1)); + rc = zmq_send_const (pub, PREFIX1, sizeof (PREFIX1), 0); + assert (rc == sizeof (PREFIX1)); // sub1 should receive it, but not sub2 rc = zmq_recv (sub1, NULL, 0, ZMQ_DONTWAIT); - assert (rc == sizeof(PREFIX1)); + assert (rc == sizeof (PREFIX1)); rc = zmq_recv (sub2, NULL, 0, ZMQ_DONTWAIT); assert (rc == -1); assert (errno == EAGAIN); // Send a message with the second prefix - rc = zmq_send_const(pub, PREFIX2, sizeof(PREFIX2), 0); - assert (rc == sizeof(PREFIX2)); + rc = zmq_send_const (pub, PREFIX2, sizeof (PREFIX2), 0); + assert (rc == sizeof (PREFIX2)); // sub2 should receive it, but not sub1 rc = zmq_recv (sub2, NULL, 0, ZMQ_DONTWAIT); - assert (rc == sizeof(PREFIX2)); + assert (rc == sizeof (PREFIX2)); rc = zmq_recv (sub1, NULL, 0, ZMQ_DONTWAIT); assert (rc == -1); @@ -89,33 +89,33 @@ int main (void) // Now invert the matching int invert = 1; - rc = zmq_setsockopt (pub, ZMQ_INVERT_MATCHING, &invert, sizeof(invert)); + rc = zmq_setsockopt (pub, ZMQ_INVERT_MATCHING, &invert, sizeof (invert)); assert (rc == 0); // ... on both sides, otherwise the SUB socket will filter the messages out - rc = zmq_setsockopt (sub1, ZMQ_INVERT_MATCHING, &invert, sizeof(invert)); - rc = zmq_setsockopt (sub2, ZMQ_INVERT_MATCHING, &invert, sizeof(invert)); + rc = zmq_setsockopt (sub1, ZMQ_INVERT_MATCHING, &invert, sizeof (invert)); + rc = zmq_setsockopt (sub2, ZMQ_INVERT_MATCHING, &invert, sizeof (invert)); assert (rc == 0); // Send a message with the first prefix - rc = zmq_send_const(pub, PREFIX1, sizeof(PREFIX1), 0); - assert (rc == sizeof(PREFIX1)); + rc = zmq_send_const (pub, PREFIX1, sizeof (PREFIX1), 0); + assert (rc == sizeof (PREFIX1)); // sub2 should receive it, but not sub1 rc = zmq_recv (sub2, NULL, 0, ZMQ_DONTWAIT); - assert (rc == sizeof(PREFIX1)); + assert (rc == sizeof (PREFIX1)); rc = zmq_recv (sub1, NULL, 0, ZMQ_DONTWAIT); assert (rc == -1); assert (errno == EAGAIN); // Send a message with the second prefix - rc = zmq_send_const(pub, PREFIX2, sizeof(PREFIX2), 0); - assert (rc == sizeof(PREFIX2)); + rc = zmq_send_const (pub, PREFIX2, sizeof (PREFIX2), 0); + assert (rc == sizeof (PREFIX2)); // sub1 should receive it, but not sub2 rc = zmq_recv (sub1, NULL, 0, ZMQ_DONTWAIT); - assert (rc == sizeof(PREFIX2)); + assert (rc == sizeof (PREFIX2)); rc = zmq_recv (sub2, NULL, 0, ZMQ_DONTWAIT); assert (rc == -1); @@ -132,5 +132,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_radio_dish.cpp b/tests/test_radio_dish.cpp index 9374388d10..086f6a1180 100644 --- a/tests/test_radio_dish.cpp +++ b/tests/test_radio_dish.cpp @@ -29,7 +29,7 @@ #include "testutil.hpp" -int msg_send (zmq_msg_t *msg_, void *s_, const char* group_, const char* body_) +int msg_send (zmq_msg_t *msg_, void *s_, const char *group_, const char *body_) { int rc = zmq_msg_init_size (msg_, strlen (body_)); if (rc != 0) @@ -50,7 +50,10 @@ int msg_send (zmq_msg_t *msg_, void *s_, const char* group_, const char* body_) return rc; } -int msg_recv_cmp (zmq_msg_t *msg_, void *s_, const char* group_, const char* body_) +int msg_recv_cmp (zmq_msg_t *msg_, + void *s_, + const char *group_, + const char *body_) { int rc = zmq_msg_init (msg_); if (rc != 0) @@ -60,24 +63,22 @@ int msg_recv_cmp (zmq_msg_t *msg_, void *s_, const char* group_, const char* bod if (recv_rc == -1) return -1; - if (strcmp (zmq_msg_group (msg_), group_) != 0) - { + if (strcmp (zmq_msg_group (msg_), group_) != 0) { zmq_msg_close (msg_); return -1; } - char * body = (char*) malloc (sizeof(char) * (zmq_msg_size (msg_) + 1)); + char *body = (char *) malloc (sizeof (char) * (zmq_msg_size (msg_) + 1)); memcpy (body, zmq_msg_data (msg_), zmq_msg_size (msg_)); - body [zmq_msg_size (msg_)] = '\0'; + body[zmq_msg_size (msg_)] = '\0'; - if (strcmp (body, body_) != 0) - { + if (strcmp (body, body_) != 0) { zmq_msg_close (msg_); return -1; } zmq_msg_close (msg_); - free(body); + free (body); return recv_rc; } @@ -166,11 +167,11 @@ int main (void) assert (rc == 9); // test zmq_poll with dish - zmq_pollitem_t items [] = { - { radio, 0, ZMQ_POLLIN, 0 }, // read publications - { dish, 0, ZMQ_POLLIN, 0 }, // read subscriptions + zmq_pollitem_t items[] = { + {radio, 0, ZMQ_POLLIN, 0}, // read publications + {dish, 0, ZMQ_POLLIN, 0}, // read subscriptions }; - rc = zmq_poll(items, 2, 2000); + rc = zmq_poll (items, 2, 2000); assert (rc == 1); assert (items[1].revents == ZMQ_POLLIN); @@ -187,5 +188,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_rebind_ipc.cpp b/tests/test_rebind_ipc.cpp index 5132ccb244..000c9b3960 100644 --- a/tests/test_rebind_ipc.cpp +++ b/tests/test_rebind_ipc.cpp @@ -29,12 +29,12 @@ #include "testutil.hpp" -static const char* SOCKET_ADDR = "ipc:///tmp/test_rebind_ipc"; +static const char *SOCKET_ADDR = "ipc:///tmp/test_rebind_ipc"; int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -55,8 +55,8 @@ int main (void) rc = zmq_send (sb0, "42", 2, 0); assert (rc == 2); - char buffer [2]; - rc = zmq_recv(sc, buffer, 2, 0); + char buffer[2]; + rc = zmq_recv (sc, buffer, 2, 0); assert (rc == 2); rc = zmq_close (sb0); @@ -68,7 +68,7 @@ int main (void) rc = zmq_send (sb1, "42", 2, 0); assert (rc == 2); - rc = zmq_recv(sc, buffer, 2, 0); + rc = zmq_recv (sc, buffer, 2, 0); assert (rc == 2); rc = zmq_close (sc); diff --git a/tests/test_reconnect_ivl.cpp b/tests/test_reconnect_ivl.cpp index 87b07d696d..7e5b4977f6 100644 --- a/tests/test_reconnect_ivl.cpp +++ b/tests/test_reconnect_ivl.cpp @@ -86,7 +86,7 @@ void test_reconnect_ivl_tcp (const char *address) if (streq (address, "tcp://[::1]:*")) { if (is_ipv6_available ()) { - zmq_ctx_set(ctx, ZMQ_IPV6, 1); + zmq_ctx_set (ctx, ZMQ_IPV6, 1); } else { zmq_ctx_term (ctx); return; @@ -145,5 +145,5 @@ int main (void) test_reconnect_ivl_tcp ("tcp://127.0.0.1:*"); test_reconnect_ivl_tcp ("tcp://[::1]:*"); - return 0 ; + return 0; } diff --git a/tests/test_req_correlate.cpp b/tests/test_req_correlate.cpp index 50aca1bf0b..b8e176e8e3 100644 --- a/tests/test_req_correlate.cpp +++ b/tests/test_req_correlate.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); @@ -82,7 +82,7 @@ int main (void) // Receive request id 1 rc = zmq_msg_recv (&msg, router, 0); assert (rc != -1); - assert (zmq_msg_size (&msg) == sizeof(uint32_t)); + assert (zmq_msg_size (&msg) == sizeof (uint32_t)); uint32_t req_id = *static_cast (zmq_msg_data (&msg)); zmq_msg_t req_id_msg; zmq_msg_init (&req_id_msg); diff --git a/tests/test_req_relaxed.cpp b/tests/test_req_relaxed.cpp index 0bd943d836..1e66176528 100644 --- a/tests/test_req_relaxed.cpp +++ b/tests/test_req_relaxed.cpp @@ -58,7 +58,7 @@ static int get_events (void *socket) { int rc; int events; - size_t events_size = sizeof(events); + size_t events_size = sizeof (events); rc = zmq_getsockopt (socket, ZMQ_EVENTS, &events, &events_size); assert (rc == 0); return events; @@ -88,16 +88,16 @@ int main (void) assert (rc == 0); const size_t services = 5; - void *rep [services]; + void *rep[services]; for (size_t peer = 0; peer < services; peer++) { - rep [peer] = zmq_socket (ctx, ZMQ_REP); - assert (rep [peer]); + rep[peer] = zmq_socket (ctx, ZMQ_REP); + assert (rep[peer]); int timeout = 500; - rc = zmq_setsockopt (rep [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); + rc = zmq_setsockopt (rep[peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); - rc = zmq_connect (rep [peer], my_endpoint); + rc = zmq_connect (rep[peer], my_endpoint); assert (rc == 0); } // We have to give the connects time to finish otherwise the requests @@ -108,33 +108,33 @@ int main (void) // Case 1: Second send() before a reply arrives in a pipe. int events = get_events (req); - assert(events == ZMQ_POLLOUT); + assert (events == ZMQ_POLLOUT); // Send a request, ensure it arrives, don't send a reply s_send_seq (req, "A", "B", SEQ_END); - s_recv_seq (rep [0], "A", "B", SEQ_END); + s_recv_seq (rep[0], "A", "B", SEQ_END); events = get_events (req); - assert(events == ZMQ_POLLOUT); + assert (events == ZMQ_POLLOUT); // Send another request on the REQ socket s_send_seq (req, "C", "D", SEQ_END); - s_recv_seq (rep [1], "C", "D", SEQ_END); + s_recv_seq (rep[1], "C", "D", SEQ_END); events = get_events (req); - assert(events == ZMQ_POLLOUT); + assert (events == ZMQ_POLLOUT); // Send a reply to the first request - that should be discarded by the REQ - s_send_seq (rep [0], "WRONG", SEQ_END); + s_send_seq (rep[0], "WRONG", SEQ_END); // Send the expected reply - s_send_seq (rep [1], "OK", SEQ_END); + s_send_seq (rep[1], "OK", SEQ_END); s_recv_seq (req, "OK", SEQ_END); // Another standard req-rep cycle, just to check s_send_seq (req, "E", SEQ_END); - s_recv_seq (rep [2], "E", SEQ_END); - s_send_seq (rep [2], "F", "G", SEQ_END); + s_recv_seq (rep[2], "E", SEQ_END); + s_send_seq (rep[2], "F", "G", SEQ_END); s_recv_seq (req, "F", "G", SEQ_END); @@ -142,18 +142,18 @@ int main (void) // Send a request, ensure it arrives, send a reply s_send_seq (req, "H", SEQ_END); - s_recv_seq (rep [3], "H", SEQ_END); - s_send_seq (rep [3], "BAD", SEQ_END); + s_recv_seq (rep[3], "H", SEQ_END); + s_send_seq (rep[3], "BAD", SEQ_END); // Wait for message to be there. msleep (SETTLE_TIME); // Without receiving that reply, send another request on the REQ socket s_send_seq (req, "I", SEQ_END); - s_recv_seq (rep [4], "I", SEQ_END); + s_recv_seq (rep[4], "I", SEQ_END); // Send the expected reply - s_send_seq (rep [4], "GOOD", SEQ_END); + s_send_seq (rep[4], "GOOD", SEQ_END); s_recv_seq (req, "GOOD", SEQ_END); // Case 3: Check issue #1690. Two send() in a row should not close the @@ -161,11 +161,11 @@ int main (void) // closed after executing Case 1. So rep[0] should be the next to receive, // not rep[1]. s_send_seq (req, "J", SEQ_END); - s_recv_seq (rep [0], "J", SEQ_END); + s_recv_seq (rep[0], "J", SEQ_END); close_zero_linger (req); for (size_t peer = 0; peer < services; peer++) - close_zero_linger (rep [peer]); + close_zero_linger (rep[peer]); // Wait for disconnects. msleep (SETTLE_TIME); @@ -216,5 +216,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_reqrep_device.cpp b/tests/test_reqrep_device.cpp index c663a29a70..6f64b17cb3 100644 --- a/tests/test_reqrep_device.cpp +++ b/tests/test_reqrep_device.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char endpoint1[MAX_SOCKET_STRING]; char endpoint2[MAX_SOCKET_STRING]; @@ -82,12 +82,12 @@ int main (void) size_t sz = sizeof (rcvmore); rc = zmq_getsockopt (router, ZMQ_RCVMORE, &rcvmore, &sz); assert (rc == 0); - rc = zmq_msg_send (&msg, dealer, rcvmore? ZMQ_SNDMORE: 0); + rc = zmq_msg_send (&msg, dealer, rcvmore ? ZMQ_SNDMORE : 0); assert (rc >= 0); } // Receive the request. - char buff [3]; + char buff[3]; rc = zmq_recv (rep, buff, 3, 0); assert (rc == 3); assert (memcmp (buff, "ABC", 3) == 0); @@ -119,7 +119,7 @@ int main (void) int rcvmore; rc = zmq_getsockopt (dealer, ZMQ_RCVMORE, &rcvmore, &sz); assert (rc == 0); - rc = zmq_msg_send (&msg, router, rcvmore? ZMQ_SNDMORE: 0); + rc = zmq_msg_send (&msg, router, rcvmore ? ZMQ_SNDMORE : 0); assert (rc >= 0); } @@ -149,5 +149,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_reqrep_device_tipc.cpp b/tests/test_reqrep_device_tipc.cpp index a5da6310d9..291231590c 100644 --- a/tests/test_reqrep_device_tipc.cpp +++ b/tests/test_reqrep_device_tipc.cpp @@ -80,7 +80,7 @@ int main (void) } // Receive the request. - char buff [3]; + char buff[3]; rc = zmq_recv (rep, buff, 3, 0); assert (rc == 3); assert (memcmp (buff, "ABC", 3) == 0); @@ -142,5 +142,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_reqrep_inproc.cpp b/tests/test_reqrep_inproc.cpp index a09ae307bf..a369c24167 100644 --- a/tests/test_reqrep_inproc.cpp +++ b/tests/test_reqrep_inproc.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -44,7 +44,7 @@ int main (void) assert (sc); rc = zmq_connect (sc, "inproc://a"); assert (rc == 0); - + bounce (sb, sc); rc = zmq_close (sc); @@ -56,5 +56,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_reqrep_ipc.cpp b/tests/test_reqrep_ipc.cpp index 7e483ee965..b41b4e58df 100644 --- a/tests/test_reqrep_ipc.cpp +++ b/tests/test_reqrep_ipc.cpp @@ -39,7 +39,7 @@ void test_leak (void) assert (sb); int rc = zmq_bind (sb, "ipc://*"); assert (rc == 0); - size_t len = sizeof(my_endpoint); + size_t len = sizeof (my_endpoint); rc = zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, my_endpoint, &len); assert (rc == 0); @@ -79,7 +79,7 @@ void test_simple (void) assert (sb); int rc = zmq_bind (sb, "ipc://*"); assert (rc == 0); - size_t len = sizeof(my_endpoint); + size_t len = sizeof (my_endpoint); rc = zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, my_endpoint, &len); assert (rc == 0); @@ -87,7 +87,7 @@ void test_simple (void) assert (sc); rc = zmq_connect (sc, my_endpoint); assert (rc == 0); - + bounce (sb, sc); rc = zmq_close (sc); @@ -102,11 +102,11 @@ void test_simple (void) int main (void) { - setup_test_environment(); + setup_test_environment (); test_simple (); test_leak (); - return 0 ; + return 0; } diff --git a/tests/test_reqrep_tcp.cpp b/tests/test_reqrep_tcp.cpp index 2b65e5ea87..27aa176eb2 100644 --- a/tests/test_reqrep_tcp.cpp +++ b/tests/test_reqrep_tcp.cpp @@ -37,9 +37,9 @@ void test_single_connect (const char *address) assert (ctx); int ipv6; - if (streq(address, "tcp://127.0.0.1:*")) + if (streq (address, "tcp://127.0.0.1:*")) ipv6 = 0; - else if (streq(address, "tcp://[::1]:*")) + else if (streq (address, "tcp://[::1]:*")) ipv6 = 1; else assert (false); @@ -94,9 +94,9 @@ void test_multi_connect (const char *address) assert (ctx); int ipv6; - if (streq(address, "tcp://127.0.0.1:*")) + if (streq (address, "tcp://127.0.0.1:*")) ipv6 = 0; - else if (streq(address, "tcp://[::1]:*")) + else if (streq (address, "tcp://[::1]:*")) ipv6 = 1; else assert (false); @@ -113,7 +113,7 @@ void test_multi_connect (const char *address) rc = zmq_bind (sb0, address); assert (rc == 0); rc = zmq_getsockopt (sb0, ZMQ_LAST_ENDPOINT, my_endpoint_0, &len); - assert (rc == 0); + assert (rc == 0); void *sb1 = zmq_socket (ctx, ZMQ_REP); assert (sb1); @@ -123,7 +123,7 @@ void test_multi_connect (const char *address) assert (rc == 0); len = MAX_SOCKET_STRING; rc = zmq_getsockopt (sb1, ZMQ_LAST_ENDPOINT, my_endpoint_1, &len); - assert (rc == 0); + assert (rc == 0); void *sb2 = zmq_socket (ctx, ZMQ_REP); assert (sb2); @@ -133,7 +133,7 @@ void test_multi_connect (const char *address) assert (rc == 0); len = MAX_SOCKET_STRING; rc = zmq_getsockopt (sb2, ZMQ_LAST_ENDPOINT, my_endpoint_2, &len); - assert (rc == 0); + assert (rc == 0); void *sc = zmq_socket (ctx, ZMQ_REQ); assert (sc); @@ -145,10 +145,10 @@ void test_multi_connect (const char *address) assert (rc == 0); if (!ipv6) sprintf (my_endpoint_3, "tcp://127.0.0.1:5564;%s", - strrchr(my_endpoint_2, '/') + 1); + strrchr (my_endpoint_2, '/') + 1); else sprintf (my_endpoint_3, "tcp://[::1]:5564;%s", - strrchr(my_endpoint_2, '/') + 1); + strrchr (my_endpoint_2, '/') + 1); rc = zmq_connect (sc, my_endpoint_3); assert (rc == 0); @@ -205,9 +205,9 @@ void test_multi_connect_same_port (const char *address) assert (ctx); int ipv6; - if (streq(address, "tcp://127.0.0.1:*")) + if (streq (address, "tcp://127.0.0.1:*")) ipv6 = 0; - else if (streq(address, "tcp://[::1]:*")) + else if (streq (address, "tcp://[::1]:*")) ipv6 = 1; else assert (false); @@ -224,7 +224,7 @@ void test_multi_connect_same_port (const char *address) rc = zmq_bind (sb0, address); assert (rc == 0); rc = zmq_getsockopt (sb0, ZMQ_LAST_ENDPOINT, my_endpoint_0, &len); - assert (rc == 0); + assert (rc == 0); void *sb1 = zmq_socket (ctx, ZMQ_REP); assert (sb1); @@ -234,7 +234,7 @@ void test_multi_connect_same_port (const char *address) assert (rc == 0); len = MAX_SOCKET_STRING; rc = zmq_getsockopt (sb1, ZMQ_LAST_ENDPOINT, my_endpoint_1, &len); - assert (rc == 0); + assert (rc == 0); void *sc0 = zmq_socket (ctx, ZMQ_REQ); assert (sc0); @@ -242,18 +242,18 @@ void test_multi_connect_same_port (const char *address) assert (rc == 0); if (!ipv6) sprintf (my_endpoint_2, "tcp://127.0.0.1:5564;%s", - strrchr(my_endpoint_0, '/') + 1); + strrchr (my_endpoint_0, '/') + 1); else sprintf (my_endpoint_2, "tcp://[::1]:5564;%s", - strrchr(my_endpoint_0, '/') + 1); + strrchr (my_endpoint_0, '/') + 1); rc = zmq_connect (sc0, my_endpoint_2); assert (rc == 0); if (!ipv6) sprintf (my_endpoint_3, "tcp://127.0.0.1:5565;%s", - strrchr(my_endpoint_1, '/') + 1); + strrchr (my_endpoint_1, '/') + 1); else sprintf (my_endpoint_3, "tcp://[::1]:5565;%s", - strrchr(my_endpoint_1, '/') + 1); + strrchr (my_endpoint_1, '/') + 1); rc = zmq_connect (sc0, my_endpoint_3); assert (rc == 0); @@ -263,18 +263,18 @@ void test_multi_connect_same_port (const char *address) assert (rc == 0); if (!ipv6) sprintf (my_endpoint_4, "tcp://127.0.0.1:5565;%s", - strrchr(my_endpoint_0, '/') + 1); + strrchr (my_endpoint_0, '/') + 1); else sprintf (my_endpoint_4, "tcp://[::1]:5565;%s", - strrchr(my_endpoint_0, '/') + 1); + strrchr (my_endpoint_0, '/') + 1); rc = zmq_connect (sc1, my_endpoint_4); assert (rc == 0); if (!ipv6) sprintf (my_endpoint_5, "tcp://127.0.0.1:5564;%s", - strrchr(my_endpoint_1, '/') + 1); + strrchr (my_endpoint_1, '/') + 1); else sprintf (my_endpoint_5, "tcp://[::1]:5564;%s", - strrchr(my_endpoint_1, '/') + 1); + strrchr (my_endpoint_1, '/') + 1); rc = zmq_connect (sc1, my_endpoint_5); assert (rc == 0); @@ -332,5 +332,5 @@ int main (void) test_multi_connect_same_port ("tcp://[::1]:*"); - return 0 ; + return 0; } diff --git a/tests/test_reqrep_tipc.cpp b/tests/test_reqrep_tipc.cpp index 1e22f0e525..b4d5c98146 100644 --- a/tests/test_reqrep_tipc.cpp +++ b/tests/test_reqrep_tipc.cpp @@ -57,5 +57,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_reqrep_vmci.cpp b/tests/test_reqrep_vmci.cpp index f915338fba..6cae22b1e3 100644 --- a/tests/test_reqrep_vmci.cpp +++ b/tests/test_reqrep_vmci.cpp @@ -35,22 +35,22 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); std::stringstream s; - s << "vmci://" << VMCISock_GetLocalCID() << ":" << 5560; - std::string endpoint = s.str(); + s << "vmci://" << VMCISock_GetLocalCID () << ":" << 5560; + std::string endpoint = s.str (); void *sb = zmq_socket (ctx, ZMQ_REP); assert (sb); - int rc = zmq_bind (sb, endpoint.c_str()); + int rc = zmq_bind (sb, endpoint.c_str ()); assert (rc == 0); void *sc = zmq_socket (ctx, ZMQ_REQ); assert (sc); - rc = zmq_connect (sc, endpoint.c_str()); + rc = zmq_connect (sc, endpoint.c_str ()); assert (rc == 0); bounce (sb, sc); diff --git a/tests/test_router_handover.cpp b/tests/test_router_handover.cpp index 7dbaac97b4..3916d3b511 100644 --- a/tests/test_router_handover.cpp +++ b/tests/test_router_handover.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); @@ -47,7 +47,8 @@ int main (void) // Enable the handover flag int handover = 1; - rc = zmq_setsockopt (router, ZMQ_ROUTER_HANDOVER, &handover, sizeof (handover)); + rc = zmq_setsockopt (router, ZMQ_ROUTER_HANDOVER, &handover, + sizeof (handover)); assert (rc == 0); // Create dealer called "X" and connect it to our router @@ -57,14 +58,14 @@ int main (void) assert (rc == 0); rc = zmq_connect (dealer_one, my_endpoint); assert (rc == 0); - + // Get message from dealer to know when connection is ready - char buffer [255]; + char buffer[255]; rc = zmq_send (dealer_one, "Hello", 5, 0); assert (rc == 5); rc = zmq_recv (router, buffer, 255, 0); assert (rc == 1); - assert (buffer [0] == 'X'); + assert (buffer[0] == 'X'); rc = zmq_recv (router, buffer, 255, 0); assert (rc == 5); @@ -81,11 +82,11 @@ int main (void) assert (rc == 5); rc = zmq_recv (router, buffer, 255, 0); assert (rc == 1); - assert (buffer [0] == 'X'); + assert (buffer[0] == 'X'); rc = zmq_recv (router, buffer, 255, 0); assert (rc == 5); - // Send a message to 'X' routing id. This should be delivered + // Send a message to 'X' routing id. This should be delivered // to the second dealer, instead of the first beccause of the handover. rc = zmq_send (router, "X", 1, ZMQ_SNDMORE); assert (rc == 1); @@ -93,13 +94,13 @@ int main (void) assert (rc == 5); // Ensure that the first dealer doesn't receive the message - // but the second one does + // but the second one does rc = zmq_recv (dealer_one, buffer, 255, ZMQ_NOBLOCK); assert (rc == -1); rc = zmq_recv (dealer_two, buffer, 255, 0); assert (rc == 5); - + rc = zmq_close (router); assert (rc == 0); @@ -112,5 +113,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_router_mandatory.cpp b/tests/test_router_mandatory.cpp index 5a67933d01..9a39342bcb 100644 --- a/tests/test_router_mandatory.cpp +++ b/tests/test_router_mandatory.cpp @@ -34,8 +34,8 @@ bool send_msg_to_peer_if_ready (void *router, const char *peer_routing_id) { int rc = zmq_socket_get_peer_state (router, peer_routing_id, 1); if (rc == -1) - printf ("zmq_socket_get_peer_state failed for %s: %i\n", peer_routing_id, - errno); + printf ("zmq_socket_get_peer_state failed for %s: %i\n", + peer_routing_id, errno); assert (rc != -1); if (rc & ZMQ_POLLOUT) { rc = zmq_send (router, peer_routing_id, 1, ZMQ_SNDMORE | ZMQ_DONTWAIT); @@ -183,8 +183,8 @@ void test_get_peer_state_corner_cases () const char peer_routing_id[] = "foo"; // call get_peer_state with NULL socket - int rc = - zmq_socket_get_peer_state (NULL, peer_routing_id, strlen (peer_routing_id)); + int rc = zmq_socket_get_peer_state (NULL, peer_routing_id, + strlen (peer_routing_id)); assert (rc == -1 && errno == ENOTSOCK); void *ctx = zmq_ctx_new (); @@ -195,13 +195,13 @@ void test_get_peer_state_corner_cases () assert (router); // call get_peer_state with a non-ROUTER socket - rc = - zmq_socket_get_peer_state (dealer, peer_routing_id, strlen (peer_routing_id)); + rc = zmq_socket_get_peer_state (dealer, peer_routing_id, + strlen (peer_routing_id)); assert (rc == -1 && errno == ENOTSUP); // call get_peer_state for an unknown routing id - rc = - zmq_socket_get_peer_state (router, peer_routing_id, strlen (peer_routing_id)); + rc = zmq_socket_get_peer_state (router, peer_routing_id, + strlen (peer_routing_id)); assert (rc == -1 && errno == EHOSTUNREACH); rc = zmq_close (router); diff --git a/tests/test_router_mandatory_hwm.cpp b/tests/test_router_mandatory_hwm.cpp index 95883b2027..a0d36cd9cf 100644 --- a/tests/test_router_mandatory_hwm.cpp +++ b/tests/test_router_mandatory_hwm.cpp @@ -39,8 +39,9 @@ int main (void) { int rc; - if (TRACE_ENABLED) fprintf(stderr, "Staring router mandatory HWM test ...\n"); - setup_test_environment(); + if (TRACE_ENABLED) + fprintf (stderr, "Staring router mandatory HWM test ...\n"); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); @@ -50,7 +51,8 @@ int main (void) // Configure router socket to mandatory routing and set HWM and linger int mandatory = 1; - rc = zmq_setsockopt (router, ZMQ_ROUTER_MANDATORY, &mandatory, sizeof (mandatory)); + rc = zmq_setsockopt (router, ZMQ_ROUTER_MANDATORY, &mandatory, + sizeof (mandatory)); assert (rc == 0); int sndhwm = 1; rc = zmq_setsockopt (router, ZMQ_SNDHWM, &sndhwm, sizeof (sndhwm)); @@ -77,22 +79,24 @@ int main (void) assert (rc == 0); // Get message from dealer to know when connection is ready - char buffer [255]; + char buffer[255]; rc = zmq_send (dealer, "Hello", 5, 0); assert (rc == 5); rc = zmq_recv (router, buffer, 255, 0); assert (rc == 1); - assert (buffer [0] == 'X'); + assert (buffer[0] == 'X'); int i; const int BUF_SIZE = 65536; char buf[BUF_SIZE]; - memset(buf, 0, BUF_SIZE); + memset (buf, 0, BUF_SIZE); // Send first batch of messages - for(i = 0; i < 100000; ++i) { - if (TRACE_ENABLED) fprintf(stderr, "Sending message %d ...\n", i); + for (i = 0; i < 100000; ++i) { + if (TRACE_ENABLED) + fprintf (stderr, "Sending message %d ...\n", i); rc = zmq_send (router, "X", 1, ZMQ_DONTWAIT | ZMQ_SNDMORE); - if (rc == -1 && zmq_errno() == EAGAIN) break; + if (rc == -1 && zmq_errno () == EAGAIN) + break; assert (rc == 1); rc = zmq_send (router, buf, BUF_SIZE, ZMQ_DONTWAIT); assert (rc == BUF_SIZE); @@ -102,10 +106,12 @@ int main (void) assert (i < 10); msleep (1000); // Send second batch of messages - for(; i < 100000; ++i) { - if (TRACE_ENABLED) fprintf(stderr, "Sending message %d (part 2) ...\n", i); + for (; i < 100000; ++i) { + if (TRACE_ENABLED) + fprintf (stderr, "Sending message %d (part 2) ...\n", i); rc = zmq_send (router, "X", 1, ZMQ_DONTWAIT | ZMQ_SNDMORE); - if (rc == -1 && zmq_errno() == EAGAIN) break; + if (rc == -1 && zmq_errno () == EAGAIN) + break; assert (rc == 1); rc = zmq_send (router, buf, BUF_SIZE, ZMQ_DONTWAIT); assert (rc == BUF_SIZE); @@ -114,7 +120,8 @@ int main (void) // skew results assert (i < 20); - if (TRACE_ENABLED) fprintf(stderr, "Done sending messages.\n"); + if (TRACE_ENABLED) + fprintf (stderr, "Done sending messages.\n"); rc = zmq_close (router); assert (rc == 0); @@ -125,5 +132,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_router_mandatory_tipc.cpp b/tests/test_router_mandatory_tipc.cpp index 0d0e1916ee..b2634c06a4 100644 --- a/tests/test_router_mandatory_tipc.cpp +++ b/tests/test_router_mandatory_tipc.cpp @@ -53,7 +53,8 @@ int main (void) int mandatory = 1; // Set mandatory routing on socket - rc = zmq_setsockopt (sa, ZMQ_ROUTER_MANDATORY, &mandatory, sizeof (mandatory)); + rc = + zmq_setsockopt (sa, ZMQ_ROUTER_MANDATORY, &mandatory, sizeof (mandatory)); assert (rc == 0); // Send a message and check that it fails @@ -66,5 +67,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_scatter_gather.cpp b/tests/test_scatter_gather.cpp index a9ac3073bf..65d7e709f0 100644 --- a/tests/test_scatter_gather.cpp +++ b/tests/test_scatter_gather.cpp @@ -37,7 +37,7 @@ int main (void) void *scatter = zmq_socket (ctx, ZMQ_SCATTER); void *gather = zmq_socket (ctx, ZMQ_GATHER); - void *gather2 = zmq_socket (ctx, ZMQ_GATHER); + void *gather2 = zmq_socket (ctx, ZMQ_GATHER); int rc = zmq_bind (scatter, "inproc://test-scatter-gather"); assert (rc == 0); @@ -58,15 +58,15 @@ int main (void) rc = s_send (scatter, "2"); assert (rc == 1); - char* message = s_recv (gather); + char *message = s_recv (gather); assert (message); - assert (streq(message, "1")); - free(message); + assert (streq (message, "1")); + free (message); message = s_recv (gather2); assert (message); - assert (streq(message, "2")); - free(message); + assert (streq (message, "2")); + free (message); rc = zmq_close (scatter); assert (rc == 0); @@ -80,5 +80,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_security_curve.cpp b/tests/test_security_curve.cpp index f93b1225cc..2d51cfc721 100644 --- a/tests/test_security_curve.cpp +++ b/tests/test_security_curve.cpp @@ -29,16 +29,16 @@ #include "testutil.hpp" #include "testutil_security.hpp" -#if defined (ZMQ_HAVE_WINDOWS) -# include -# include -# include -# define close closesocket +#if defined(ZMQ_HAVE_WINDOWS) +#include +#include +#include +#define close closesocket #else -# include -# include -# include -# include +#include +#include +#include +#include #endif #include "../src/tweetnacl.h" @@ -46,12 +46,12 @@ #include "../src/random.hpp" const char large_routing_id[] = "0123456789012345678901234567890123456789" - "0123456789012345678901234567890123456789" - "0123456789012345678901234567890123456789" - "0123456789012345678901234567890123456789" - "0123456789012345678901234567890123456789" - "0123456789012345678901234567890123456789" - "012345678901234"; + "0123456789012345678901234567890123456789" + "0123456789012345678901234567890123456789" + "0123456789012345678901234567890123456789" + "0123456789012345678901234567890123456789" + "0123456789012345678901234567890123456789" + "012345678901234"; static void zap_handler_large_routing_id (void *ctx) { @@ -92,10 +92,10 @@ void test_null_key (void *ctx, ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL, ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); - // handshake_failed_encryption_event_count should be at least two because + // handshake_failed_encryption_event_count should be at least two because // expect_bounce_fail involves two exchanges - // however, with valgrind we see only one event (maybe the next one takes - // very long, or does not happen at all because something else takes very + // however, with valgrind we see only one event (maybe the next one takes + // very long, or does not happen at all because something else takes very // long) fprintf (stderr, @@ -141,8 +141,8 @@ void test_curve_security_with_bogus_client_credentials ( LIBZMQ_UNUSED (timeout); // This must be caught by the ZAP handler - char bogus_public [41]; - char bogus_secret [41]; + char bogus_public[41]; + char bogus_secret[41]; zmq_curve_keypair (bogus_public, bogus_secret); expect_new_client_curve_bounce_fail (ctx, valid_server_public, bogus_public, @@ -155,7 +155,7 @@ void test_curve_security_with_bogus_client_credentials ( #endif ); - int server_event_count = 0; + int server_event_count = 0; #ifdef ZMQ_BUILD_DRAFT_API server_event_count = expect_monitor_event_multiple ( server_mon, ZMQ_EVENT_HANDSHAKE_FAILED_AUTH, 400); @@ -241,7 +241,7 @@ void test_curve_security_unauthenticated_message (char *my_endpoint, int timeout) { // Unauthenticated messages from a vanilla socket shouldn't be received - int s = connect_vanilla_socket(my_endpoint); + int s = connect_vanilla_socket (my_endpoint); // send anonymous ZMTP/1.0 greeting send (s, "\x01\x00", 2, 0); // send sneaky message that shouldn't be received @@ -266,17 +266,17 @@ void send_all (int fd, const char *data, size_t size) } } -template void send (int fd, const char (&data) [N]) +template void send (int fd, const char (&data)[N]) { send_all (fd, data, N - 1); } -void send_greeting(int s) +void send_greeting (int s) { - send (s, "\xff\0\0\0\0\0\0\0\0\x7f"); // signature - send (s, "\x03\x00"); // version 3.0 + send (s, "\xff\0\0\0\0\0\0\0\0\x7f"); // signature + send (s, "\x03\x00"); // version 3.0 send (s, "CURVE\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); // mechanism CURVE - send (s, "\0"); // as-server == false + send (s, "\0"); // as-server == false send (s, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); } @@ -294,7 +294,7 @@ void test_curve_security_invalid_hello_wrong_length (char *my_endpoint, send_greeting (s); // send CURVE HELLO of wrong size - send(s, "\x04\x06\x05HELLO"); + send (s, "\x04\x06\x05HELLO"); #ifdef ZMQ_BUILD_DRAFT_API expect_monitor_event_multiple ( @@ -345,16 +345,16 @@ uint64_t htonll (uint64_t value) template void send_command (int s, char (&command)[N]) { - if (N < 256) { - send(s, "\x04"); - char len = (char)N; - send_all(s, &len, 1); - } else { - send(s, "\x06"); - uint64_t len = htonll (N); - send_all (s, (char*)&len, 8); - } - send_all (s, command, N); + if (N < 256) { + send (s, "\x04"); + char len = (char) N; + send_all (s, &len, 1); + } else { + send (s, "\x06"); + uint64_t len = htonll (N); + send_all (s, (char *) &len, 8); + } + send_all (s, command, N); } void test_curve_security_invalid_hello_command_name (char *my_endpoint, @@ -377,7 +377,7 @@ void test_curve_security_invalid_hello_command_name (char *my_endpoint, assert (rc == 0); hello[5] = 'X'; - send_command(s, hello); + send_command (s, hello); #ifdef ZMQ_BUILD_DRAFT_API expect_monitor_event_multiple (server_mon, @@ -419,7 +419,7 @@ void test_curve_security_invalid_hello_version (char *my_endpoint, close (s); } -void flush_read(int fd) +void flush_read (int fd) { int res; char buf[256]; @@ -429,17 +429,16 @@ void flush_read(int fd) assert (res != -1); } -void recv_all(int fd, uint8_t *data, size_t len) +void recv_all (int fd, uint8_t *data, size_t len) { - size_t received = 0; - while (received < len) - { - int res = recv(fd, (char*)data, len, 0); - assert(res > 0); - - data += res; - received += res; - } + size_t received = 0; + while (received < len) { + int res = recv (fd, (char *) data, len, 0); + assert (res > 0); + + data += res; + received += res; + } } void recv_greeting (int fd) @@ -487,7 +486,7 @@ void test_curve_security_invalid_initiate_length (char *my_endpoint, LIBZMQ_UNUSED (timeout); #endif - send(s, "\x04\x09\x08INITIATE"); + send (s, "\x04\x09\x08INITIATE"); #ifdef ZMQ_BUILD_DRAFT_API expect_monitor_event_multiple ( @@ -504,14 +503,13 @@ int connect_exchange_greeting_and_hello_welcome ( int timeout, zmq::curve_client_tools_t &tools) { - int s = connect_exchange_greeting_and_send_hello ( - my_endpoint, tools); + int s = connect_exchange_greeting_and_send_hello (my_endpoint, tools); // receive but ignore WELCOME uint8_t welcome[welcome_length + 2]; recv_all (s, welcome, welcome_length + 2); - - uint8_t cn_precom [crypto_box_BEFORENMBYTES]; + + uint8_t cn_precom[crypto_box_BEFORENMBYTES]; int res = tools.process_welcome (welcome + 2, welcome_length, cn_precom); assert (res == 0); @@ -534,7 +532,7 @@ void test_curve_security_invalid_initiate_command_name (char *my_endpoint, int s = connect_exchange_greeting_and_hello_welcome ( my_endpoint, server_mon, timeout, tools); - char initiate [257]; + char initiate[257]; tools.produce_initiate (initiate, 257, 1, NULL, 0); // modify command name initiate[5] = 'X'; @@ -559,7 +557,7 @@ void test_curve_security_invalid_initiate_command_encrypted_cookie ( int s = connect_exchange_greeting_and_hello_welcome ( my_endpoint, server_mon, timeout, tools); - char initiate [257]; + char initiate[257]; tools.produce_initiate (initiate, 257, 1, NULL, 0); // make garbage from encrypted cookie initiate[30] = !initiate[30]; @@ -584,7 +582,7 @@ void test_curve_security_invalid_initiate_command_encrypted_content ( int s = connect_exchange_greeting_and_hello_welcome ( my_endpoint, server_mon, timeout, tools); - char initiate [257]; + char initiate[257]; tools.produce_initiate (initiate, 257, 1, NULL, 0); // make garbage from encrypted content initiate[150] = !initiate[150]; @@ -606,7 +604,8 @@ void test_curve_security_invalid_keysize (void *ctx) void *client = zmq_socket (ctx, ZMQ_DEALER); assert (client); errno = 0; - int rc = zmq_setsockopt (client, ZMQ_CURVE_SERVERKEY, valid_server_public, 123); + int rc = + zmq_setsockopt (client, ZMQ_CURVE_SERVERKEY, valid_server_public, 123); assert (rc == -1 && errno == EINVAL); errno = 0; rc = zmq_setsockopt (client, ZMQ_CURVE_PUBLICKEY, valid_client_public, 123); @@ -638,7 +637,7 @@ int main (void) void *zap_thread; void *server; void *server_mon; - char my_endpoint [MAX_SOCKET_STRING]; + char my_endpoint[MAX_SOCKET_STRING]; fprintf (stderr, "test_curve_security_with_valid_credentials\n"); setup_context_and_server_side (&ctx, &handler, &zap_thread, &server, diff --git a/tests/test_security_gssapi.cpp b/tests/test_security_gssapi.cpp index c749fba34e..91d8593d07 100644 --- a/tests/test_security_gssapi.cpp +++ b/tests/test_security_gssapi.cpp @@ -28,16 +28,16 @@ */ #include "testutil.hpp" -#if defined (ZMQ_HAVE_WINDOWS) -# include -# include -# include -# define close closesocket +#if defined(ZMQ_HAVE_WINDOWS) +#include +#include +#include +#define close closesocket #else -# include -# include -# include -# include +#include +#include +#include +#include #endif // This test requires a KRB5 environment with the following @@ -60,14 +60,13 @@ static volatile int zap_deny_all = 0; // in case of error. #ifdef ZMQ_BUILD_DRAFT_API -static int -get_monitor_event (void *monitor, int *value, char **address) +static int get_monitor_event (void *monitor, int *value, char **address) { // First frame in message contains event number and value zmq_msg_t msg; zmq_msg_init (&msg); if (zmq_msg_recv (&msg, monitor, 0) == -1) - return -1; // Interruped, presumably + return -1; // Interruped, presumably assert (zmq_msg_more (&msg)); uint8_t *data = (uint8_t *) zmq_msg_data (&msg); @@ -79,7 +78,7 @@ get_monitor_event (void *monitor, int *value, char **address) // Second frame in message contains event address zmq_msg_init (&msg); if (zmq_msg_recv (&msg, monitor, 0) == -1) - return -1; // Interruped, presumably + return -1; // Interruped, presumably assert (!zmq_msg_more (&msg)); if (address) { @@ -87,7 +86,7 @@ get_monitor_event (void *monitor, int *value, char **address) size_t size = zmq_msg_size (&msg); *address = (char *) malloc (size + 1); memcpy (*address, data, size); - *address [size] = 0; + *address[size] = 0; } zmq_msg_close (&msg); @@ -106,7 +105,7 @@ static void zap_handler (void *handler) while (true) { char *version = s_recv (handler); if (!version) - break; // Terminating + break; // Terminating char *sequence = s_recv (handler); char *domain = s_recv (handler); @@ -125,15 +124,14 @@ static void zap_handler (void *handler) s_sendmore (handler, "200"); s_sendmore (handler, "OK"); s_sendmore (handler, "anonymous"); - s_send (handler, ""); - //fprintf (stderr, "ALLOW %s\n", principal); - } - else { + s_send (handler, ""); + //fprintf (stderr, "ALLOW %s\n", principal); + } else { s_sendmore (handler, "400"); s_sendmore (handler, "Denied"); s_sendmore (handler, ""); - s_send (handler, ""); - //fprintf (stderr, "DENY %s\n", principal); + s_send (handler, ""); + //fprintf (stderr, "DENY %s\n", principal); } free (version); free (sequence); @@ -146,20 +144,22 @@ static void zap_handler (void *handler) zmq_close (handler); } -void test_valid_creds (void *ctx, void *server, void *server_mon, char *endpoint) +void test_valid_creds (void *ctx, + void *server, + void *server_mon, + char *endpoint) { void *client = zmq_socket (ctx, ZMQ_DEALER); assert (client); - int rc = zmq_setsockopt (client, ZMQ_GSSAPI_SERVICE_PRINCIPAL, - name, strlen (name) + 1); + int rc = zmq_setsockopt (client, ZMQ_GSSAPI_SERVICE_PRINCIPAL, name, + strlen (name) + 1); assert (rc == 0); - rc = zmq_setsockopt (client, ZMQ_GSSAPI_PRINCIPAL, - name, strlen (name) + 1); + rc = zmq_setsockopt (client, ZMQ_GSSAPI_PRINCIPAL, name, strlen (name) + 1); assert (rc == 0); #ifdef ZMQ_BUILD_DRAFT_API int name_type = ZMQ_GSSAPI_NT_HOSTBASED; - rc = zmq_setsockopt (client, ZMQ_GSSAPI_PRINCIPAL_NAMETYPE, - &name_type, sizeof (name_type)); + rc = zmq_setsockopt (client, ZMQ_GSSAPI_PRINCIPAL_NAMETYPE, &name_type, + sizeof (name_type)); assert (rc == 0); #endif rc = zmq_connect (client, endpoint); @@ -178,20 +178,22 @@ void test_valid_creds (void *ctx, void *server, void *server_mon, char *endpoint // Check security with valid but unauthorized credentials // Note: ZAP may see multiple requests - after a failure, client will // fall back to other crypto types for principal, if available. -void test_unauth_creds (void *ctx, void *server, void *server_mon, char *endpoint) +void test_unauth_creds (void *ctx, + void *server, + void *server_mon, + char *endpoint) { void *client = zmq_socket (ctx, ZMQ_DEALER); assert (client); - int rc = zmq_setsockopt (client, ZMQ_GSSAPI_SERVICE_PRINCIPAL, - name, strlen (name) + 1); + int rc = zmq_setsockopt (client, ZMQ_GSSAPI_SERVICE_PRINCIPAL, name, + strlen (name) + 1); assert (rc == 0); - rc = zmq_setsockopt (client, ZMQ_GSSAPI_PRINCIPAL, - name, strlen (name) + 1); + rc = zmq_setsockopt (client, ZMQ_GSSAPI_PRINCIPAL, name, strlen (name) + 1); assert (rc == 0); #ifdef ZMQ_BUILD_DRAFT_API int name_type = ZMQ_GSSAPI_NT_HOSTBASED; - rc = zmq_setsockopt (client, ZMQ_GSSAPI_PRINCIPAL_NAMETYPE, - &name_type, sizeof (name_type)); + rc = zmq_setsockopt (client, ZMQ_GSSAPI_PRINCIPAL_NAMETYPE, &name_type, + sizeof (name_type)); assert (rc == 0); #endif zap_deny_all = 1; @@ -228,7 +230,10 @@ void test_null_creds (void *ctx, void *server, void *server_mon, char *endpoint) // Check GSSAPI security with PLAIN client credentials // This must be caught by the curve_server class, not passed to ZAP -void test_plain_creds (void *ctx, void *server, void *server_mon, char *endpoint) +void test_plain_creds (void *ctx, + void *server, + void *server_mon, + char *endpoint) { void *client = zmq_socket (ctx, ZMQ_DEALER); assert (client); @@ -243,23 +248,26 @@ void test_plain_creds (void *ctx, void *server, void *server_mon, char *endpoint } // Unauthenticated messages from a vanilla socket shouldn't be received -void test_vanilla_socket (void *ctx, void *server, void *server_mon, char *endpoint) +void test_vanilla_socket (void *ctx, + void *server, + void *server_mon, + char *endpoint) { struct sockaddr_in ip4addr; int s; unsigned short int port; - int rc = sscanf(endpoint, "tcp://127.0.0.1:%hu", &port); + int rc = sscanf (endpoint, "tcp://127.0.0.1:%hu", &port); assert (rc == 1); ip4addr.sin_family = AF_INET; ip4addr.sin_port = htons (port); -#if defined (ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) +#if defined(ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) ip4addr.sin_addr.s_addr = inet_addr ("127.0.0.1"); #else - inet_pton(AF_INET, "127.0.0.1", &ip4addr.sin_addr); + inet_pton (AF_INET, "127.0.0.1", &ip4addr.sin_addr); #endif s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); - rc = connect (s, (struct sockaddr*) &ip4addr, sizeof (ip4addr)); + rc = connect (s, (struct sockaddr *) &ip4addr, sizeof (ip4addr)); assert (rc > -1); // send anonymous ZMTP/1.0 greeting send (s, "\x01\x00", 2, 0); @@ -306,13 +314,12 @@ int main (void) int as_server = 1; rc = zmq_setsockopt (server, ZMQ_GSSAPI_SERVER, &as_server, sizeof (int)); assert (rc == 0); - rc = zmq_setsockopt (server, ZMQ_GSSAPI_PRINCIPAL, - name, strlen (name) + 1); + rc = zmq_setsockopt (server, ZMQ_GSSAPI_PRINCIPAL, name, strlen (name) + 1); assert (rc == 0); #ifdef ZMQ_BUILD_DRAFT_API int name_type = ZMQ_GSSAPI_NT_HOSTBASED; - rc = zmq_setsockopt (server, ZMQ_GSSAPI_PRINCIPAL_NAMETYPE, - &name_type, sizeof (name_type)); + rc = zmq_setsockopt (server, ZMQ_GSSAPI_PRINCIPAL_NAMETYPE, &name_type, + sizeof (name_type)); assert (rc == 0); #endif rc = zmq_bind (server, "tcp://127.0.0.1:*"); @@ -323,8 +330,9 @@ int main (void) #ifdef ZMQ_BUILD_DRAFT_API // Monitor handshake events on the server rc = zmq_socket_monitor (server, "inproc://monitor-server", - ZMQ_EVENT_HANDSHAKE_SUCCEEDED | ZMQ_EVENT_HANDSHAKE_FAILED_AUTH | - ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL); + ZMQ_EVENT_HANDSHAKE_SUCCEEDED + | ZMQ_EVENT_HANDSHAKE_FAILED_AUTH + | ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL); assert (rc == 0); #endif diff --git a/tests/test_security_null.cpp b/tests/test_security_null.cpp index c50f479ae5..94729ed8e2 100644 --- a/tests/test_security_null.cpp +++ b/tests/test_security_null.cpp @@ -28,26 +28,25 @@ */ #include "testutil.hpp" -#if defined (ZMQ_HAVE_WINDOWS) -# include -# include -# include -# define close closesocket +#if defined(ZMQ_HAVE_WINDOWS) +#include +#include +#include +#define close closesocket #else -# include -# include -# include -# include +#include +#include +#include +#include #endif -static void -zap_handler (void *handler) +static void zap_handler (void *handler) { // Process ZAP requests forever while (true) { char *version = s_recv (handler); if (!version) - break; // Terminating + break; // Terminating char *sequence = s_recv (handler); char *domain = s_recv (handler); @@ -57,20 +56,19 @@ zap_handler (void *handler) assert (streq (version, "1.0")); assert (streq (mechanism, "NULL")); - + s_sendmore (handler, version); s_sendmore (handler, sequence); if (streq (domain, "TEST")) { s_sendmore (handler, "200"); s_sendmore (handler, "OK"); s_sendmore (handler, "anonymous"); - s_send (handler, ""); - } - else { + s_send (handler, ""); + } else { s_sendmore (handler, "400"); s_sendmore (handler, "BAD DOMAIN"); s_sendmore (handler, ""); - s_send (handler, ""); + s_send (handler, ""); } free (version); free (sequence); @@ -84,7 +82,7 @@ zap_handler (void *handler) int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); @@ -100,7 +98,7 @@ int main (void) void *zap_thread = zmq_threadstart (&zap_handler, handler); // We bounce between a binding server and a connecting client - + // We first test client/server with no ZAP domain // Libzmq does not call our ZAP handler, the connect must succeed void *server = zmq_socket (ctx, ZMQ_DEALER); @@ -117,7 +115,7 @@ int main (void) close_zero_linger (client); close_zero_linger (server); - // Now define a ZAP domain for the server; this enables + // Now define a ZAP domain for the server; this enables // authentication. We're using the wrong domain so this test // must fail. server = zmq_socket (ctx, ZMQ_DEALER); @@ -171,19 +169,19 @@ int main (void) int s; unsigned short int port; - rc = sscanf(my_endpoint, "tcp://127.0.0.1:%hu", &port); + rc = sscanf (my_endpoint, "tcp://127.0.0.1:%hu", &port); assert (rc == 1); ip4addr.sin_family = AF_INET; - ip4addr.sin_port = htons(port); -#if defined (ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) + ip4addr.sin_port = htons (port); +#if defined(ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) ip4addr.sin_addr.s_addr = inet_addr ("127.0.0.1"); #else - inet_pton(AF_INET, "127.0.0.1", &ip4addr.sin_addr); + inet_pton (AF_INET, "127.0.0.1", &ip4addr.sin_addr); #endif s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); - rc = connect (s, (struct sockaddr*) &ip4addr, sizeof ip4addr); + rc = connect (s, (struct sockaddr *) &ip4addr, sizeof ip4addr); assert (rc > -1); // send anonymous ZMTP/1.0 greeting send (s, "\x01\x00", 2, 0); diff --git a/tests/test_security_plain.cpp b/tests/test_security_plain.cpp index 7e3034787b..8542c32369 100644 --- a/tests/test_security_plain.cpp +++ b/tests/test_security_plain.cpp @@ -28,20 +28,19 @@ */ #include "testutil.hpp" -#if defined (ZMQ_HAVE_WINDOWS) -# include -# include -# include -# define close closesocket +#if defined(ZMQ_HAVE_WINDOWS) +#include +#include +#include +#define close closesocket #else -# include -# include -# include -# include +#include +#include +#include +#include #endif -static void -zap_handler (void *ctx) +static void zap_handler (void *ctx) { // Create and bind ZAP socket void *zap = zmq_socket (ctx, ZMQ_REP); @@ -53,7 +52,7 @@ zap_handler (void *ctx) while (true) { char *version = s_recv (zap); if (!version) - break; // Terminating + break; // Terminating char *sequence = s_recv (zap); char *domain = s_recv (zap); char *address = s_recv (zap); @@ -68,14 +67,12 @@ zap_handler (void *ctx) s_sendmore (zap, version); s_sendmore (zap, sequence); - if (streq (username, "admin") - && streq (password, "password")) { + if (streq (username, "admin") && streq (password, "password")) { s_sendmore (zap, "200"); s_sendmore (zap, "OK"); s_sendmore (zap, "anonymous"); s_send (zap, ""); - } - else { + } else { s_sendmore (zap, "400"); s_sendmore (zap, "Invalid username or password"); s_sendmore (zap, ""); @@ -96,7 +93,7 @@ zap_handler (void *ctx) int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); @@ -121,17 +118,19 @@ int main (void) rc = zmq_getsockopt (server, ZMQ_LAST_ENDPOINT, my_endpoint, &len); assert (rc == 0); - char username [256]; - char password [256]; + char username[256]; + char password[256]; // Check PLAIN security with correct username/password void *client = zmq_socket (ctx, ZMQ_DEALER); assert (client); strcpy (username, "admin"); - rc = zmq_setsockopt (client, ZMQ_PLAIN_USERNAME, username, strlen (username)); + rc = + zmq_setsockopt (client, ZMQ_PLAIN_USERNAME, username, strlen (username)); assert (rc == 0); strcpy (password, "password"); - rc = zmq_setsockopt (client, ZMQ_PLAIN_PASSWORD, password, strlen (password)); + rc = + zmq_setsockopt (client, ZMQ_PLAIN_PASSWORD, password, strlen (password)); assert (rc == 0); rc = zmq_connect (client, my_endpoint); assert (rc == 0); @@ -144,7 +143,7 @@ int main (void) client = zmq_socket (ctx, ZMQ_DEALER); assert (client); as_server = 1; - rc = zmq_setsockopt(client, ZMQ_ZAP_DOMAIN, domain, strlen (domain)); + rc = zmq_setsockopt (client, ZMQ_ZAP_DOMAIN, domain, strlen (domain)); assert (rc == 0); rc = zmq_setsockopt (client, ZMQ_PLAIN_SERVER, &as_server, sizeof (int)); assert (rc == 0); @@ -158,9 +157,11 @@ int main (void) assert (client); strcpy (username, "wronguser"); strcpy (password, "wrongpass"); - rc = zmq_setsockopt (client, ZMQ_PLAIN_USERNAME, username, strlen (username)); + rc = + zmq_setsockopt (client, ZMQ_PLAIN_USERNAME, username, strlen (username)); assert (rc == 0); - rc = zmq_setsockopt (client, ZMQ_PLAIN_PASSWORD, password, strlen (password)); + rc = + zmq_setsockopt (client, ZMQ_PLAIN_PASSWORD, password, strlen (password)); assert (rc == 0); rc = zmq_connect (client, my_endpoint); assert (rc == 0); @@ -172,19 +173,19 @@ int main (void) int s; unsigned short int port; - rc = sscanf(my_endpoint, "tcp://127.0.0.1:%hu", &port); + rc = sscanf (my_endpoint, "tcp://127.0.0.1:%hu", &port); assert (rc == 1); ip4addr.sin_family = AF_INET; ip4addr.sin_port = htons (port); -#if defined (ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) +#if defined(ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) ip4addr.sin_addr.s_addr = inet_addr ("127.0.0.1"); #else inet_pton (AF_INET, "127.0.0.1", &ip4addr.sin_addr); #endif s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); - rc = connect (s, (struct sockaddr*) &ip4addr, sizeof (ip4addr)); + rc = connect (s, (struct sockaddr *) &ip4addr, sizeof (ip4addr)); assert (rc > -1); // send anonymous ZMTP/1.0 greeting send (s, "\x01\x00", 2, 0); diff --git a/tests/test_security_zap.cpp b/tests/test_security_zap.cpp index 31bd0d7ce0..f33f041a82 100644 --- a/tests/test_security_zap.cpp +++ b/tests/test_security_zap.cpp @@ -343,10 +343,10 @@ void test_zap_errors (socket_config_fn server_socket_config_, #endif // ZAP handler disconnecting on first message - fprintf(stderr, "test_zap_unsuccessful ZAP handler disconnects\n"); - setup_context_and_server_side(&ctx, &handler, &zap_thread, &server, - &server_mon, my_endpoint, &zap_handler_disconnect, - server_socket_config_); + fprintf (stderr, "test_zap_unsuccessful ZAP handler disconnects\n"); + setup_context_and_server_side ( + &ctx, &handler, &zap_thread, &server, &server_mon, my_endpoint, + &zap_handler_disconnect, server_socket_config_); test_zap_unsuccessful_no_handler ( ctx, my_endpoint, server, server_mon, #ifdef ZMQ_BUILD_DRAFT_API @@ -361,9 +361,9 @@ void test_zap_errors (socket_config_fn server_socket_config_, // ZAP handler does not read request fprintf (stderr, "test_zap_unsuccessful ZAP handler does not read request\n"); - setup_context_and_server_side (&ctx, &handler, &zap_thread, &server, - &server_mon, my_endpoint, &zap_handler_do_not_recv, - server_socket_config_); + setup_context_and_server_side ( + &ctx, &handler, &zap_thread, &server, &server_mon, my_endpoint, + &zap_handler_do_not_recv, server_socket_config_); test_zap_unsuccessful_no_handler ( ctx, my_endpoint, server, server_mon, #ifdef ZMQ_BUILD_DRAFT_API diff --git a/tests/test_setsockopt.cpp b/tests/test_setsockopt.cpp index de152e51e9..be2cd160f2 100644 --- a/tests/test_setsockopt.cpp +++ b/tests/test_setsockopt.cpp @@ -93,18 +93,18 @@ void test_setsockopt_use_fd () size_t placeholder = sizeof (val); rc = zmq_getsockopt (socket, ZMQ_USE_FD, &val, &placeholder); - assert(rc == 0); - assert(val == -1); + assert (rc == 0); + assert (val == -1); val = 3; - rc = zmq_setsockopt (socket, ZMQ_USE_FD, &val, sizeof(val)); - assert(rc == 0); - assert(val == 3); + rc = zmq_setsockopt (socket, ZMQ_USE_FD, &val, sizeof (val)); + assert (rc == 0); + assert (val == 3); rc = zmq_getsockopt (socket, ZMQ_USE_FD, &val, &placeholder); - assert(rc == 0); - assert(val == 3); + assert (rc == 0); + assert (val == 3); zmq_close (socket); zmq_ctx_term (ctx); @@ -122,22 +122,22 @@ void test_setsockopt_bindtodevice () size_t buflen = BOUNDDEVBUFSZ; rc = zmq_getsockopt (socket, ZMQ_BINDTODEVICE, devname, &buflen); - assert(rc == 0); - assert(devname[0] == '\0'); - assert(buflen == 1); + assert (rc == 0); + assert (devname[0] == '\0'); + assert (buflen == 1); - sprintf(devname, "testdev"); - buflen = strlen(devname); + sprintf (devname, "testdev"); + buflen = strlen (devname); rc = zmq_setsockopt (socket, ZMQ_BINDTODEVICE, devname, buflen); - assert(rc == 0); + assert (rc == 0); buflen = BOUNDDEVBUFSZ; - memset(devname, 0, buflen); + memset (devname, 0, buflen); rc = zmq_getsockopt (socket, ZMQ_BINDTODEVICE, devname, &buflen); - assert(rc == 0); - assert(!strncmp("testdev", devname, buflen)); + assert (rc == 0); + assert (!strncmp ("testdev", devname, buflen)); #endif zmq_close (socket); diff --git a/tests/test_shutdown_stress.cpp b/tests/test_shutdown_stress.cpp index d34f357734..ef9aa4b177 100644 --- a/tests/test_shutdown_stress.cpp +++ b/tests/test_shutdown_stress.cpp @@ -31,42 +31,41 @@ #define THREAD_COUNT 100 -struct thread_data { +struct thread_data +{ void *ctx; char endpoint[MAX_SOCKET_STRING]; }; -extern "C" +extern "C" { +static void worker (void *data) { - static void worker (void *data) - { - int rc; - void *socket; - struct thread_data *tdata = (struct thread_data *)data; + int rc; + void *socket; + struct thread_data *tdata = (struct thread_data *) data; - socket = zmq_socket (tdata->ctx, ZMQ_SUB); - assert (socket); + socket = zmq_socket (tdata->ctx, ZMQ_SUB); + assert (socket); - rc = zmq_connect (socket, tdata->endpoint); - assert (rc == 0); + rc = zmq_connect (socket, tdata->endpoint); + assert (rc == 0); - // Start closing the socket while the connecting process is underway. - rc = zmq_close (socket); - assert (rc == 0); - } + // Start closing the socket while the connecting process is underway. + rc = zmq_close (socket); + assert (rc == 0); +} } int main (void) { - setup_test_environment(); + setup_test_environment (); void *socket; int i; int j; int rc; - void* threads [THREAD_COUNT]; + void *threads[THREAD_COUNT]; for (j = 0; j != 10; j++) { - // Check the shutdown with many parallel I/O threads. struct thread_data tdata; tdata.ctx = zmq_ctx_new (); @@ -83,11 +82,11 @@ int main (void) assert (rc == 0); for (i = 0; i != THREAD_COUNT; i++) { - threads [i] = zmq_threadstart(&worker, &tdata); + threads[i] = zmq_threadstart (&worker, &tdata); } for (i = 0; i != THREAD_COUNT; i++) { - zmq_threadclose(threads [i]); + zmq_threadclose (threads[i]); } rc = zmq_close (socket); diff --git a/tests/test_shutdown_stress_tipc.cpp b/tests/test_shutdown_stress_tipc.cpp index 0fade8e52c..68f78ca509 100644 --- a/tests/test_shutdown_stress_tipc.cpp +++ b/tests/test_shutdown_stress_tipc.cpp @@ -31,21 +31,20 @@ #define THREAD_COUNT 100 -extern "C" +extern "C" { +static void *worker (void *s) { - static void *worker (void *s) - { - int rc; + int rc; - rc = zmq_connect (s, "tipc://{5560,0}@0.0.0"); - assert (rc == 0); + rc = zmq_connect (s, "tipc://{5560,0}@0.0.0"); + assert (rc == 0); - // Start closing the socket while the connecting process is underway. - rc = zmq_close (s); - assert (rc == 0); + // Start closing the socket while the connecting process is underway. + rc = zmq_close (s); + assert (rc == 0); - return NULL; - } + return NULL; +} } int main (void) @@ -56,12 +55,11 @@ int main (void) int i; int j; int rc; - pthread_t threads [THREAD_COUNT]; + pthread_t threads[THREAD_COUNT]; fprintf (stderr, "test_shutdown_stress_tipc running...\n"); for (j = 0; j != 10; j++) { - // Check the shutdown with many parallel I/O threads. ctx = zmq_init (7); assert (ctx); @@ -75,12 +73,12 @@ int main (void) for (i = 0; i != THREAD_COUNT; i++) { s2 = zmq_socket (ctx, ZMQ_SUB); assert (s2); - rc = pthread_create (&threads [i], NULL, worker, s2); + rc = pthread_create (&threads[i], NULL, worker, s2); assert (rc == 0); } for (i = 0; i != THREAD_COUNT; i++) { - rc = pthread_join (threads [i], NULL); + rc = pthread_join (threads[i], NULL); assert (rc == 0); } diff --git a/tests/test_sockopt_hwm.cpp b/tests/test_sockopt_hwm.cpp index 170f2332d4..55735f67c6 100644 --- a/tests/test_sockopt_hwm.cpp +++ b/tests/test_sockopt_hwm.cpp @@ -31,76 +31,78 @@ const int MAX_SENDS = 10000; -void test_change_before_connected() +void test_change_before_connected () { int rc; - void *ctx = zmq_ctx_new(); + void *ctx = zmq_ctx_new (); - void *bind_socket = zmq_socket(ctx, ZMQ_PUSH); - void *connect_socket = zmq_socket(ctx, ZMQ_PULL); + void *bind_socket = zmq_socket (ctx, ZMQ_PUSH); + void *connect_socket = zmq_socket (ctx, ZMQ_PULL); int val = 2; - rc = zmq_setsockopt(connect_socket, ZMQ_RCVHWM, &val, sizeof(val)); - assert(rc == 0); - rc = zmq_setsockopt(bind_socket, ZMQ_SNDHWM, &val, sizeof(val)); - assert(rc == 0); + rc = zmq_setsockopt (connect_socket, ZMQ_RCVHWM, &val, sizeof (val)); + assert (rc == 0); + rc = zmq_setsockopt (bind_socket, ZMQ_SNDHWM, &val, sizeof (val)); + assert (rc == 0); - zmq_connect(connect_socket, "inproc://a"); - zmq_bind(bind_socket, "inproc://a"); + zmq_connect (connect_socket, "inproc://a"); + zmq_bind (bind_socket, "inproc://a"); - size_t placeholder = sizeof(val); + size_t placeholder = sizeof (val); val = 0; - rc = zmq_getsockopt(bind_socket, ZMQ_SNDHWM, &val, &placeholder); - assert(rc == 0); - assert(val == 2); + rc = zmq_getsockopt (bind_socket, ZMQ_SNDHWM, &val, &placeholder); + assert (rc == 0); + assert (val == 2); int send_count = 0; - while (send_count < MAX_SENDS && zmq_send(bind_socket, NULL, 0, ZMQ_DONTWAIT) == 0) + while (send_count < MAX_SENDS + && zmq_send (bind_socket, NULL, 0, ZMQ_DONTWAIT) == 0) ++send_count; - assert(send_count == 4); + assert (send_count == 4); - zmq_close(bind_socket); - zmq_close(connect_socket); - zmq_ctx_term(ctx); + zmq_close (bind_socket); + zmq_close (connect_socket); + zmq_ctx_term (ctx); } -void test_change_after_connected() +void test_change_after_connected () { int rc; - void *ctx = zmq_ctx_new(); + void *ctx = zmq_ctx_new (); - void *bind_socket = zmq_socket(ctx, ZMQ_PUSH); - void *connect_socket = zmq_socket(ctx, ZMQ_PULL); + void *bind_socket = zmq_socket (ctx, ZMQ_PUSH); + void *connect_socket = zmq_socket (ctx, ZMQ_PULL); int val = 1; - rc = zmq_setsockopt(connect_socket, ZMQ_RCVHWM, &val, sizeof(val)); - assert(rc == 0); - rc = zmq_setsockopt(bind_socket, ZMQ_SNDHWM, &val, sizeof(val)); - assert(rc == 0); + rc = zmq_setsockopt (connect_socket, ZMQ_RCVHWM, &val, sizeof (val)); + assert (rc == 0); + rc = zmq_setsockopt (bind_socket, ZMQ_SNDHWM, &val, sizeof (val)); + assert (rc == 0); - zmq_connect(connect_socket, "inproc://a"); - zmq_bind(bind_socket, "inproc://a"); + zmq_connect (connect_socket, "inproc://a"); + zmq_bind (bind_socket, "inproc://a"); val = 5; - rc = zmq_setsockopt(bind_socket, ZMQ_SNDHWM, &val, sizeof(val)); - assert(rc == 0); + rc = zmq_setsockopt (bind_socket, ZMQ_SNDHWM, &val, sizeof (val)); + assert (rc == 0); - size_t placeholder = sizeof(val); + size_t placeholder = sizeof (val); val = 0; - rc = zmq_getsockopt(bind_socket, ZMQ_SNDHWM, &val, &placeholder); - assert(rc == 0); - assert(val == 5); + rc = zmq_getsockopt (bind_socket, ZMQ_SNDHWM, &val, &placeholder); + assert (rc == 0); + assert (val == 5); int send_count = 0; - while (send_count < MAX_SENDS && zmq_send(bind_socket, NULL, 0, ZMQ_DONTWAIT) == 0) + while (send_count < MAX_SENDS + && zmq_send (bind_socket, NULL, 0, ZMQ_DONTWAIT) == 0) ++send_count; - assert(send_count == 6); + assert (send_count == 6); - zmq_close(bind_socket); - zmq_close(connect_socket); - zmq_ctx_term(ctx); + zmq_close (bind_socket); + zmq_close (connect_socket); + zmq_ctx_term (ctx); } int send_until_wouldblock (void *socket) @@ -117,43 +119,44 @@ int send_until_wouldblock (void *socket) int test_fill_up_to_hwm (void *socket, int sndhwm) { int send_count = send_until_wouldblock (socket); - fprintf(stderr, "sndhwm==%i, send_count==%i\n", sndhwm, send_count); + fprintf (stderr, "sndhwm==%i, send_count==%i\n", sndhwm, send_count); assert (send_count <= sndhwm + 1 && send_count > (sndhwm / 10)); return send_count; } -void test_decrease_when_full() +void test_decrease_when_full () { int rc; - void *ctx = zmq_ctx_new(); + void *ctx = zmq_ctx_new (); - void *bind_socket = zmq_socket(ctx, ZMQ_PUSH); - void *connect_socket = zmq_socket(ctx, ZMQ_PULL); + void *bind_socket = zmq_socket (ctx, ZMQ_PUSH); + void *connect_socket = zmq_socket (ctx, ZMQ_PULL); int val = 1; - rc = zmq_setsockopt(connect_socket, ZMQ_RCVHWM, &val, sizeof(val)); - assert(rc == 0); + rc = zmq_setsockopt (connect_socket, ZMQ_RCVHWM, &val, sizeof (val)); + assert (rc == 0); int sndhwm = 100; rc = zmq_setsockopt (bind_socket, ZMQ_SNDHWM, &sndhwm, sizeof (sndhwm)); assert (rc == 0); - zmq_bind(bind_socket, "inproc://a"); - zmq_connect(connect_socket, "inproc://a"); + zmq_bind (bind_socket, "inproc://a"); + zmq_connect (connect_socket, "inproc://a"); // Fill up to hwm int send_count = test_fill_up_to_hwm (bind_socket, sndhwm); // Decrease snd hwm sndhwm = 70; - rc = zmq_setsockopt(bind_socket, ZMQ_SNDHWM, &sndhwm, sizeof(sndhwm)); - assert(rc == 0); + rc = zmq_setsockopt (bind_socket, ZMQ_SNDHWM, &sndhwm, sizeof (sndhwm)); + assert (rc == 0); int sndhwm_read = 0; - size_t sndhwm_read_size = sizeof(sndhwm_read); - rc = zmq_getsockopt(bind_socket, ZMQ_SNDHWM, &sndhwm_read, &sndhwm_read_size); - assert(rc == 0); - assert(sndhwm_read == sndhwm); + size_t sndhwm_read_size = sizeof (sndhwm_read); + rc = + zmq_getsockopt (bind_socket, ZMQ_SNDHWM, &sndhwm_read, &sndhwm_read_size); + assert (rc == 0); + assert (sndhwm_read == sndhwm); msleep (SETTLE_TIME); @@ -164,11 +167,11 @@ void test_decrease_when_full() read_count < MAX_SENDS && zmq_recv (connect_socket, &read_data, sizeof (read_data), ZMQ_DONTWAIT) == sizeof (read_data)) { - assert(read_count == read_data); + assert (read_count == read_data); ++read_count; } - assert(read_count == send_count); + assert (read_count == send_count); // Give io thread some time to catch up msleep (SETTLE_TIME); @@ -176,15 +179,15 @@ void test_decrease_when_full() // Fill up to new hwm test_fill_up_to_hwm (bind_socket, sndhwm); - zmq_close(bind_socket); - zmq_close(connect_socket); - zmq_ctx_term(ctx); + zmq_close (bind_socket); + zmq_close (connect_socket); + zmq_ctx_term (ctx); } -int main() +int main () { - test_change_before_connected(); - test_change_after_connected(); - test_decrease_when_full(); + test_change_before_connected (); + test_change_after_connected (); + test_decrease_when_full (); } diff --git a/tests/test_sodium.cpp b/tests/test_sodium.cpp index d6dfe42e67..209088002b 100644 --- a/tests/test_sodium.cpp +++ b/tests/test_sodium.cpp @@ -33,12 +33,12 @@ void test__zmq_curve_keypair__always__success (void) { errno = 0; - char public_key[41] = { 0 }; - char secret_key[41] = { 0 }; + char public_key[41] = {0}; + char secret_key[41] = {0}; - const int rc = zmq_curve_keypair(public_key, secret_key); + const int rc = zmq_curve_keypair (public_key, secret_key); -#if defined (ZMQ_HAVE_CURVE) +#if defined(ZMQ_HAVE_CURVE) assert (rc == 0); #else assert (rc == -1); @@ -53,11 +53,11 @@ void test__zmq_curve_public__valid__success () static const char secret_key[] = "D:)Q[IlAW!ahhC2ac:9*A}h:p?([4%wOTJ%JR%cs"; errno = 0; - char out_public[41] = { 0 }; + char out_public[41] = {0}; const int rc = zmq_curve_public (out_public, secret_key); -#if defined (ZMQ_HAVE_CURVE) +#if defined(ZMQ_HAVE_CURVE) assert (rc == 0); assert (zmq_errno () == 0); assert (streq (out_public, public_key)); @@ -72,11 +72,11 @@ void test__zmq_curve_public__valid__success () void test__zmq_curve_public__invalid__failure (const char *secret) { errno = 0; - char out_public[41] = { 0 }; + char out_public[41] = {0}; - const int rc = zmq_curve_public(out_public, secret); + const int rc = zmq_curve_public (out_public, secret); -#if defined (ZMQ_HAVE_CURVE) +#if defined(ZMQ_HAVE_CURVE) assert (rc == -1); assert (zmq_errno () == EINVAL); assert (streq (out_public, "")); @@ -92,7 +92,8 @@ int main (void) test__zmq_curve_public__valid__success (); test__zmq_curve_public__invalid__failure ("42"); - test__zmq_curve_public__invalid__failure ("0123456789012345678901234567890123456789."); + test__zmq_curve_public__invalid__failure ( + "0123456789012345678901234567890123456789."); return 0; } diff --git a/tests/test_spec_dealer.cpp b/tests/test_spec_dealer.cpp index 6765222545..15215435aa 100644 --- a/tests/test_spec_dealer.cpp +++ b/tests/test_spec_dealer.cpp @@ -44,16 +44,16 @@ void test_round_robin_out (void *ctx) assert (rc == 0); const size_t services = 5; - void *rep [services]; + void *rep[services]; for (size_t peer = 0; peer < services; ++peer) { - rep [peer] = zmq_socket (ctx, ZMQ_REP); - assert (rep [peer]); + rep[peer] = zmq_socket (ctx, ZMQ_REP); + assert (rep[peer]); int timeout = 250; - rc = zmq_setsockopt (rep [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); + rc = zmq_setsockopt (rep[peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); - rc = zmq_connect (rep [peer], connect_address); + rc = zmq_connect (rep[peer], connect_address); assert (rc == 0); } @@ -69,7 +69,7 @@ void test_round_robin_out (void *ctx) zmq_msg_init (&msg); for (size_t peer = 0; peer < services; ++peer) - s_recv_seq (rep [peer], "ABC", SEQ_END); + s_recv_seq (rep[peer], "ABC", SEQ_END); rc = zmq_msg_close (&msg); assert (rc == 0); @@ -77,7 +77,7 @@ void test_round_robin_out (void *ctx) close_zero_linger (dealer); for (size_t peer = 0; peer < services; ++peer) - close_zero_linger (rep [peer]); + close_zero_linger (rep[peer]); // Wait for disconnects. msleep (SETTLE_TIME); @@ -99,15 +99,16 @@ void test_fair_queue_in (void *ctx) assert (rc == 0); const size_t services = 5; - void *senders [services]; + void *senders[services]; for (size_t peer = 0; peer < services; ++peer) { - senders [peer] = zmq_socket (ctx, ZMQ_DEALER); - assert (senders [peer]); + senders[peer] = zmq_socket (ctx, ZMQ_DEALER); + assert (senders[peer]); - rc = zmq_setsockopt (senders [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); + rc = + zmq_setsockopt (senders[peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); - rc = zmq_connect (senders [peer], connect_address); + rc = zmq_connect (senders[peer], connect_address); assert (rc == 0); } @@ -115,15 +116,15 @@ void test_fair_queue_in (void *ctx) rc = zmq_msg_init (&msg); assert (rc == 0); - s_send_seq (senders [0], "A", SEQ_END); + s_send_seq (senders[0], "A", SEQ_END); s_recv_seq (receiver, "A", SEQ_END); - s_send_seq (senders [0], "A", SEQ_END); + s_send_seq (senders[0], "A", SEQ_END); s_recv_seq (receiver, "A", SEQ_END); // send our requests for (size_t peer = 0; peer < services; ++peer) - s_send_seq (senders [peer], "B", SEQ_END); + s_send_seq (senders[peer], "B", SEQ_END); // Wait for data. msleep (SETTLE_TIME); @@ -138,7 +139,7 @@ void test_fair_queue_in (void *ctx) close_zero_linger (receiver); for (size_t peer = 0; peer < services; ++peer) - close_zero_linger (senders [peer]); + close_zero_linger (senders[peer]); // Wait for disconnects. msleep (SETTLE_TIME); @@ -169,7 +170,7 @@ void test_destroy_queue_on_disconnect (void *ctx) assert (rc == 0); // Disconnect may take time and need command processing. - zmq_pollitem_t poller [2] = { { A, 0, 0, 0 }, { B, 0, 0, 0 } }; + zmq_pollitem_t poller[2] = {{A, 0, 0, 0}, {B, 0, 0, 0}}; rc = zmq_poll (poller, 2, 100); assert (rc == 0); rc = zmq_poll (poller, 2, 100); @@ -232,14 +233,14 @@ void test_block_on_send_no_peers (void *ctx) int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); - const char *binds [] = { "inproc://a", "tcp://127.0.0.1:*" }; + const char *binds[] = {"inproc://a", "tcp://127.0.0.1:*"}; for (int transports = 0; transports < 2; ++transports) { - bind_address = binds [transports]; + bind_address = binds[transports]; // SHALL route outgoing messages to available peers using a round-robin // strategy. @@ -262,5 +263,5 @@ int main (void) int rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_spec_pushpull.cpp b/tests/test_spec_pushpull.cpp index 43b6b342ee..3f0da5afc0 100644 --- a/tests/test_spec_pushpull.cpp +++ b/tests/test_spec_pushpull.cpp @@ -44,16 +44,16 @@ void test_push_round_robin_out (void *ctx) assert (rc == 0); const size_t services = 5; - void *pulls [services]; + void *pulls[services]; for (size_t peer = 0; peer < services; ++peer) { - pulls [peer] = zmq_socket (ctx, ZMQ_PULL); - assert (pulls [peer]); + pulls[peer] = zmq_socket (ctx, ZMQ_PULL); + assert (pulls[peer]); int timeout = 250; - rc = zmq_setsockopt (pulls [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); + rc = zmq_setsockopt (pulls[peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); - rc = zmq_connect (pulls [peer], connect_address); + rc = zmq_connect (pulls[peer], connect_address); assert (rc == 0); } @@ -68,14 +68,14 @@ void test_push_round_robin_out (void *ctx) // Expect every PULL got one of each for (size_t peer = 0; peer < services; ++peer) { - s_recv_seq (pulls [peer], "ABC", SEQ_END); - s_recv_seq (pulls [peer], "DEF", SEQ_END); + s_recv_seq (pulls[peer], "ABC", SEQ_END); + s_recv_seq (pulls[peer], "DEF", SEQ_END); } close_zero_linger (push); for (size_t peer = 0; peer < services; ++peer) - close_zero_linger (pulls [peer]); + close_zero_linger (pulls[peer]); // Wait for disconnects. msleep (SETTLE_TIME); @@ -93,13 +93,12 @@ void test_pull_fair_queue_in (void *ctx) assert (rc == 0); const size_t services = 5; - void *pushs [services]; - for (size_t peer = 0; peer < services; ++peer) - { - pushs [peer] = zmq_socket (ctx, ZMQ_PUSH); - assert (pushs [peer]); + void *pushs[services]; + for (size_t peer = 0; peer < services; ++peer) { + pushs[peer] = zmq_socket (ctx, ZMQ_PUSH); + assert (pushs[peer]); - rc = zmq_connect (pushs [peer], connect_address); + rc = zmq_connect (pushs[peer], connect_address); assert (rc == 0); } @@ -111,15 +110,15 @@ void test_pull_fair_queue_in (void *ctx) // Send 2N messages for (size_t peer = 0; peer < services; ++peer) { - char *str = strdup("A"); + char *str = strdup ("A"); - str [0] += peer; - s_send_seq (pushs [peer], str, SEQ_END); - first_half += str [0]; + str[0] += peer; + s_send_seq (pushs[peer], str, SEQ_END); + first_half += str[0]; - str [0] += services; - s_send_seq (pushs [peer], str, SEQ_END); - second_half += str [0]; + str[0] += services; + s_send_seq (pushs[peer], str, SEQ_END); + second_half += str[0]; free (str); } @@ -135,8 +134,8 @@ void test_pull_fair_queue_in (void *ctx) for (size_t peer = 0; peer < services; ++peer) { rc = zmq_msg_recv (&msg, pull, 0); assert (rc == 2); - const char *str = (const char *)zmq_msg_data (&msg); - first_half -= str [0]; + const char *str = (const char *) zmq_msg_data (&msg); + first_half -= str[0]; } assert (first_half == 0); @@ -144,8 +143,8 @@ void test_pull_fair_queue_in (void *ctx) for (size_t peer = 0; peer < services; ++peer) { rc = zmq_msg_recv (&msg, pull, 0); assert (rc == 2); - const char *str = (const char *)zmq_msg_data (&msg); - second_half -= str [0]; + const char *str = (const char *) zmq_msg_data (&msg); + second_half -= str[0]; } assert (second_half == 0); @@ -155,7 +154,7 @@ void test_pull_fair_queue_in (void *ctx) close_zero_linger (pull); for (size_t peer = 0; peer < services; ++peer) - close_zero_linger (pushs [peer]); + close_zero_linger (pushs[peer]); // Wait for disconnects. msleep (SETTLE_TIME); @@ -220,7 +219,7 @@ void test_destroy_queue_on_disconnect (void *ctx) assert (rc == 0); // Disconnect may take time and need command processing. - zmq_pollitem_t poller [2] = { { A, 0, 0, 0 }, { B, 0, 0, 0 } }; + zmq_pollitem_t poller[2] = {{A, 0, 0, 0}, {B, 0, 0, 0}}; rc = zmq_poll (poller, 2, 100); assert (rc == 0); rc = zmq_poll (poller, 2, 100); @@ -269,14 +268,14 @@ void test_destroy_queue_on_disconnect (void *ctx) int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); - const char *binds [] = { "inproc://a", "tcp://127.0.0.1:*" }; + const char *binds[] = {"inproc://a", "tcp://127.0.0.1:*"}; for (int transport = 0; transport < 2; ++transport) { - bind_address = binds [transport]; + bind_address = binds[transport]; // PUSH: SHALL route outgoing messages to connected peers using a // round-robin strategy. @@ -300,5 +299,5 @@ int main (void) int rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_spec_rep.cpp b/tests/test_spec_rep.cpp index 815e848e2e..b679a7f485 100644 --- a/tests/test_spec_rep.cpp +++ b/tests/test_spec_rep.cpp @@ -48,55 +48,55 @@ void test_fair_queue_in (void *ctx) assert (rc == 0); const size_t services = 5; - void *reqs [services]; + void *reqs[services]; for (size_t peer = 0; peer < services; ++peer) { - reqs [peer] = zmq_socket (ctx, ZMQ_REQ); - assert (reqs [peer]); + reqs[peer] = zmq_socket (ctx, ZMQ_REQ); + assert (reqs[peer]); - rc = zmq_setsockopt (reqs [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); + rc = zmq_setsockopt (reqs[peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); - rc = zmq_connect (reqs [peer], connect_address); + rc = zmq_connect (reqs[peer], connect_address); assert (rc == 0); } msleep (SETTLE_TIME); - s_send_seq (reqs [0], "A", SEQ_END); + s_send_seq (reqs[0], "A", SEQ_END); s_recv_seq (rep, "A", SEQ_END); s_send_seq (rep, "A", SEQ_END); - s_recv_seq (reqs [0], "A", SEQ_END); + s_recv_seq (reqs[0], "A", SEQ_END); - s_send_seq (reqs [0], "A", SEQ_END); + s_send_seq (reqs[0], "A", SEQ_END); s_recv_seq (rep, "A", SEQ_END); s_send_seq (rep, "A", SEQ_END); - s_recv_seq (reqs [0], "A", SEQ_END); + s_recv_seq (reqs[0], "A", SEQ_END); // TODO: following test fails randomly on some boxes #ifdef SOMEONE_FIXES_THIS // send N requests for (size_t peer = 0; peer < services; ++peer) { - char * str = strdup("A"); - str [0] += peer; - s_send_seq (reqs [peer], str, SEQ_END); + char *str = strdup ("A"); + str[0] += peer; + s_send_seq (reqs[peer], str, SEQ_END); free (str); } // handle N requests for (size_t peer = 0; peer < services; ++peer) { - char * str = strdup("A"); - str [0] += peer; + char *str = strdup ("A"); + str[0] += peer; // Test fails here s_recv_seq (rep, str, SEQ_END); s_send_seq (rep, str, SEQ_END); - s_recv_seq (reqs [peer], str, SEQ_END); + s_recv_seq (reqs[peer], str, SEQ_END); free (str); } #endif close_zero_linger (rep); for (size_t peer = 0; peer < services; ++peer) - close_zero_linger (reqs [peer]); + close_zero_linger (reqs[peer]); // Wait for disconnects. msleep (SETTLE_TIME); @@ -140,14 +140,14 @@ void test_envelope (void *ctx) int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); - const char *binds [] = { "inproc://a", "tcp://127.0.0.1:*" }; + const char *binds[] = {"inproc://a", "tcp://127.0.0.1:*"}; for (int transport = 0; transport < 2; ++transport) { - bind_address = binds [transport]; + bind_address = binds[transport]; // SHALL receive incoming messages from its peers using a fair-queuing // strategy. @@ -165,5 +165,5 @@ int main (void) int rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_spec_req.cpp b/tests/test_spec_req.cpp index 9a1876f335..96872ce6eb 100644 --- a/tests/test_spec_req.cpp +++ b/tests/test_spec_req.cpp @@ -44,34 +44,34 @@ void test_round_robin_out (void *ctx) assert (rc == 0); const size_t services = 5; - void *rep [services]; + void *rep[services]; for (size_t peer = 0; peer < services; peer++) { - rep [peer] = zmq_socket (ctx, ZMQ_REP); - assert (rep [peer]); + rep[peer] = zmq_socket (ctx, ZMQ_REP); + assert (rep[peer]); int timeout = 250; - rc = zmq_setsockopt (rep [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); + rc = zmq_setsockopt (rep[peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); - rc = zmq_connect (rep [peer], connect_address); + rc = zmq_connect (rep[peer], connect_address); assert (rc == 0); } - // We have to give the connects time to finish otherwise the requests + // We have to give the connects time to finish otherwise the requests // will not properly round-robin. We could alternatively connect the // REQ sockets to the REP sockets. msleep (SETTLE_TIME); - + // Send our peer-replies, and expect every REP it used once in order for (size_t peer = 0; peer < services; peer++) { s_send_seq (req, "ABC", SEQ_END); - s_recv_seq (rep [peer], "ABC", SEQ_END); - s_send_seq (rep [peer], "DEF", SEQ_END); + s_recv_seq (rep[peer], "ABC", SEQ_END); + s_send_seq (rep[peer], "DEF", SEQ_END); s_recv_seq (req, "DEF", SEQ_END); } close_zero_linger (req); for (size_t peer = 0; peer < services; peer++) - close_zero_linger (rep [peer]); + close_zero_linger (rep[peer]); // Wait for disconnects. msleep (SETTLE_TIME); @@ -82,7 +82,7 @@ void test_req_only_listens_to_current_peer (void *ctx) void *req = zmq_socket (ctx, ZMQ_REQ); assert (req); - int rc = zmq_setsockopt(req, ZMQ_ROUTING_ID, "A", 2); + int rc = zmq_setsockopt (req, ZMQ_ROUTING_ID, "A", 2); assert (rc == 0); rc = zmq_bind (req, bind_address); @@ -92,21 +92,23 @@ void test_req_only_listens_to_current_peer (void *ctx) assert (rc == 0); const size_t services = 3; - void *router [services]; - + void *router[services]; + for (size_t i = 0; i < services; ++i) { - router [i] = zmq_socket (ctx, ZMQ_ROUTER); - assert (router [i]); + router[i] = zmq_socket (ctx, ZMQ_ROUTER); + assert (router[i]); int timeout = 250; - rc = zmq_setsockopt (router [i], ZMQ_RCVTIMEO, &timeout, sizeof (timeout)); + rc = + zmq_setsockopt (router[i], ZMQ_RCVTIMEO, &timeout, sizeof (timeout)); assert (rc == 0); int enabled = 1; - rc = zmq_setsockopt (router [i], ZMQ_ROUTER_MANDATORY, &enabled, sizeof (enabled)); + rc = zmq_setsockopt (router[i], ZMQ_ROUTER_MANDATORY, &enabled, + sizeof (enabled)); assert (rc == 0); - rc = zmq_connect (router [i], connect_address); + rc = zmq_connect (router[i], connect_address); assert (rc == 0); } @@ -123,13 +125,13 @@ void test_req_only_listens_to_current_peer (void *ctx) s_send_seq (req, "ABC", SEQ_END); // Receive on router i - s_recv_seq (router [i], "A", 0, "ABC", SEQ_END); + s_recv_seq (router[i], "A", 0, "ABC", SEQ_END); // Send back replies on all routers for (size_t j = 0; j < services; ++j) { - const char *replies [] = { "WRONG", "GOOD" }; - const char *reply = replies [i == j ? 1 : 0]; - s_send_seq (router [j], "A", 0, reply, SEQ_END); + const char *replies[] = {"WRONG", "GOOD"}; + const char *reply = replies[i == j ? 1 : 0]; + s_send_seq (router[j], "A", 0, reply, SEQ_END); } // Receive only the good reply @@ -138,7 +140,7 @@ void test_req_only_listens_to_current_peer (void *ctx) close_zero_linger (req); for (size_t i = 0; i < services; ++i) - close_zero_linger (router [i]); + close_zero_linger (router[i]); // Wait for disconnects. msleep (SETTLE_TIME); @@ -228,14 +230,14 @@ void test_block_on_send_no_peers (void *ctx) int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); - const char *binds [] = { "inproc://a", "tcp://127.0.0.1:*" }; + const char *binds[] = {"inproc://a", "tcp://127.0.0.1:*"}; for (int transport = 0; transport < 2; transport++) { - bind_address = binds [transport]; + bind_address = binds[transport]; // SHALL route outgoing messages to connected peers using a round-robin // strategy. @@ -247,7 +249,7 @@ int main (void) // application. test_req_message_format (ctx); - // SHALL block on sending, or return a suitable error, when it has no + // SHALL block on sending, or return a suitable error, when it has no // connected peers. test_block_on_send_no_peers (ctx); @@ -262,5 +264,5 @@ int main (void) int rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_spec_router.cpp b/tests/test_spec_router.cpp index b23a4e493f..5cafaf8877 100644 --- a/tests/test_spec_router.cpp +++ b/tests/test_spec_router.cpp @@ -48,21 +48,22 @@ void test_fair_queue_in (void *ctx) assert (rc == 0); const size_t services = 5; - void *senders [services]; + void *senders[services]; for (size_t peer = 0; peer < services; ++peer) { - senders [peer] = zmq_socket (ctx, ZMQ_DEALER); - assert (senders [peer]); + senders[peer] = zmq_socket (ctx, ZMQ_DEALER); + assert (senders[peer]); - rc = zmq_setsockopt (senders [peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); + rc = + zmq_setsockopt (senders[peer], ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); - char *str = strdup("A"); - str [0] += peer; - rc = zmq_setsockopt (senders [peer], ZMQ_ROUTING_ID, str, 2); + char *str = strdup ("A"); + str[0] += peer; + rc = zmq_setsockopt (senders[peer], ZMQ_ROUTING_ID, str, 2); assert (rc == 0); free (str); - rc = zmq_connect (senders [peer], connect_address); + rc = zmq_connect (senders[peer], connect_address); assert (rc == 0); } @@ -72,17 +73,17 @@ void test_fair_queue_in (void *ctx) rc = zmq_msg_init (&msg); assert (rc == 0); - s_send_seq (senders [0], "M", SEQ_END); + s_send_seq (senders[0], "M", SEQ_END); s_recv_seq (receiver, "A", "M", SEQ_END); - s_send_seq (senders [0], "M", SEQ_END); + s_send_seq (senders[0], "M", SEQ_END); s_recv_seq (receiver, "A", "M", SEQ_END); int sum = 0; // send N requests for (size_t peer = 0; peer < services; ++peer) { - s_send_seq (senders [peer], "M", SEQ_END); + s_send_seq (senders[peer], "M", SEQ_END); sum += 'A' + peer; } @@ -92,8 +93,8 @@ void test_fair_queue_in (void *ctx) for (size_t peer = 0; peer < services; ++peer) { rc = zmq_msg_recv (&msg, receiver, 0); assert (rc == 2); - const char *id = (const char *)zmq_msg_data (&msg); - sum -= id [0]; + const char *id = (const char *) zmq_msg_data (&msg); + sum -= id[0]; s_recv_seq (receiver, "M", SEQ_END); } @@ -106,7 +107,7 @@ void test_fair_queue_in (void *ctx) close_zero_linger (receiver); for (size_t peer = 0; peer < services; ++peer) - close_zero_linger (senders [peer]); + close_zero_linger (senders[peer]); // Wait for disconnects. msleep (SETTLE_TIME); @@ -118,7 +119,8 @@ void test_destroy_queue_on_disconnect (void *ctx) assert (A); int enabled = 1; - int rc = zmq_setsockopt (A, ZMQ_ROUTER_MANDATORY, &enabled, sizeof (enabled)); + int rc = + zmq_setsockopt (A, ZMQ_ROUTER_MANDATORY, &enabled, sizeof (enabled)); assert (rc == 0); rc = zmq_bind (A, bind_address); @@ -147,7 +149,7 @@ void test_destroy_queue_on_disconnect (void *ctx) assert (rc == 0); // Disconnect may take time and need command processing. - zmq_pollitem_t poller [2] = { { A, 0, 0, 0 }, { B, 0, 0, 0 } }; + zmq_pollitem_t poller[2] = {{A, 0, 0, 0}, {B, 0, 0, 0}}; rc = zmq_poll (poller, 2, 100); assert (rc == 0); rc = zmq_poll (poller, 2, 100); @@ -190,14 +192,14 @@ void test_destroy_queue_on_disconnect (void *ctx) int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); - const char *binds [] = { "inproc://a", "tcp://127.0.0.1:*" }; + const char *binds[] = {"inproc://a", "tcp://127.0.0.1:*"}; for (int transport = 0; transport < 2; ++transport) { - bind_address = binds [transport]; + bind_address = binds[transport]; // SHALL receive incoming messages from its peers using a fair-queuing // strategy. @@ -213,5 +215,5 @@ int main (void) int rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_srcfd.cpp b/tests/test_srcfd.cpp index 89fbebc5ca..a9d2c5d44e 100644 --- a/tests/test_srcfd.cpp +++ b/tests/test_srcfd.cpp @@ -46,7 +46,7 @@ int main (void) size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; - setup_test_environment(); + setup_test_environment (); // Create the infrastructure void *ctx = zmq_ctx_new (); assert (ctx); @@ -56,31 +56,31 @@ int main (void) void *req = zmq_socket (ctx, ZMQ_REQ); assert (req); - rc = zmq_bind(rep, "tcp://127.0.0.1:*"); + rc = zmq_bind (rep, "tcp://127.0.0.1:*"); assert (rc == 0); - rc = zmq_getsockopt(rep, ZMQ_LAST_ENDPOINT, my_endpoint, &len); + rc = zmq_getsockopt (rep, ZMQ_LAST_ENDPOINT, my_endpoint, &len); assert (rc == 0); - rc = zmq_connect(req, my_endpoint); + rc = zmq_connect (req, my_endpoint); assert (rc == 0); char tmp[MSG_SIZE]; memset (tmp, 0, MSG_SIZE); - zmq_send(req, tmp, MSG_SIZE, 0); + zmq_send (req, tmp, MSG_SIZE, 0); zmq_msg_t msg; - rc = zmq_msg_init(&msg); + rc = zmq_msg_init (&msg); assert (rc == 0); - zmq_recvmsg(rep, &msg, 0); - assert(zmq_msg_size(&msg) == MSG_SIZE); + zmq_recvmsg (rep, &msg, 0); + assert (zmq_msg_size (&msg) == MSG_SIZE); // get the messages source file descriptor - int srcFd = zmq_msg_get(&msg, ZMQ_SRCFD); - assert(srcFd >= 0); + int srcFd = zmq_msg_get (&msg, ZMQ_SRCFD); + assert (srcFd >= 0); - rc = zmq_msg_close(&msg); + rc = zmq_msg_close (&msg); assert (rc == 0); // get the remote endpoint @@ -90,16 +90,16 @@ int main (void) #else socklen_t addrlen = sizeof ss; #endif - rc = getpeername (srcFd, (struct sockaddr*) &ss, &addrlen); + rc = getpeername (srcFd, (struct sockaddr *) &ss, &addrlen); assert (rc == 0); - char host [NI_MAXHOST]; - rc = getnameinfo ((struct sockaddr*) &ss, addrlen, host, sizeof host, - NULL, 0, NI_NUMERICHOST); + char host[NI_MAXHOST]; + rc = getnameinfo ((struct sockaddr *) &ss, addrlen, host, sizeof host, NULL, + 0, NI_NUMERICHOST); assert (rc == 0); // assert it is localhost which connected - assert (strcmp(host, "127.0.0.1") == 0); + assert (strcmp (host, "127.0.0.1") == 0); rc = zmq_close (rep); assert (rc == 0); @@ -110,10 +110,10 @@ int main (void) msleep (SETTLE_TIME); // getting name from closed socket will fail - rc = getpeername (srcFd, (struct sockaddr*) &ss, &addrlen); + rc = getpeername (srcFd, (struct sockaddr *) &ss, &addrlen); #ifdef ZMQ_HAVE_WINDOWS assert (rc == SOCKET_ERROR); - assert (WSAGetLastError() == WSAENOTSOCK); + assert (WSAGetLastError () == WSAENOTSOCK); #else assert (rc == -1); assert (errno == EBADF); @@ -122,6 +122,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } - diff --git a/tests/test_stream.cpp b/tests/test_stream.cpp index e3f13389b5..b139b4d2b9 100644 --- a/tests/test_stream.cpp +++ b/tests/test_stream.cpp @@ -32,29 +32,24 @@ // ZMTP protocol greeting structure typedef unsigned char byte; -typedef struct { - byte signature [10]; // 0xFF 8*0x00 0x7F - byte version [2]; // 0x03 0x00 for ZMTP/3.0 - byte mechanism [20]; // "NULL" +typedef struct +{ + byte signature[10]; // 0xFF 8*0x00 0x7F + byte version[2]; // 0x03 0x00 for ZMTP/3.0 + byte mechanism[20]; // "NULL" byte as_server; - byte filler [31]; + byte filler[31]; } zmtp_greeting_t; -#define ZMTP_DEALER 5 // Socket type constants +#define ZMTP_DEALER 5 // Socket type constants // This is a greeting matching what 0MQ will send us; note the // 8-byte size is set to 1 for backwards compatibility -static zmtp_greeting_t - greeting = { { 0xFF, 0, 0, 0, 0, 0, 0, 0, 1, 0x7F }, - { 3, 0 }, - { 'N', 'U', 'L', 'L'}, - 0, - { 0 } - }; +static zmtp_greeting_t greeting = { + {0xFF, 0, 0, 0, 0, 0, 0, 0, 1, 0x7F}, {3, 0}, {'N', 'U', 'L', 'L'}, 0, {0}}; -static void -test_stream_to_dealer (void) +static void test_stream_to_dealer (void) { int rc; size_t len = MAX_SOCKET_STRING; @@ -106,7 +101,7 @@ test_stream_to_dealer (void) assert (streq (peer_address, "127.0.0.1")); // Second frame is zero - byte buffer [255]; + byte buffer[255]; rc = zmq_recv (stream, buffer, 255, 0); assert (rc == 0); @@ -152,11 +147,12 @@ test_stream_to_dealer (void) } // First two bytes are major and minor version numbers. - assert (buffer [0] == 3); // ZMTP/3.0 - assert (buffer [1] == 0); + assert (buffer[0] == 3); // ZMTP/3.0 + assert (buffer[1] == 0); // Mechanism is "NULL" - assert (memcmp (buffer + 2, "NULL\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) == 0); + assert (memcmp (buffer + 2, "NULL\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 20) + == 0); assert (memcmp (buffer + 54, "\4\51\5READY", 8) == 0); assert (memcmp (buffer + 62, "\13Socket-Type\0\0\0\6DEALER", 22) == 0); assert (memcmp (buffer + 84, "\10Identity\0\0\0\0", 13) == 0); @@ -183,14 +179,14 @@ test_stream_to_dealer (void) assert (rc == 7); // Then we have a 5-byte message "Hello" - assert (buffer [0] == 0); // Flags = 0 - assert (buffer [1] == 5); // Size = 5 + assert (buffer[0] == 0); // Flags = 0 + assert (buffer[1] == 5); // Size = 5 assert (memcmp (buffer + 2, "Hello", 5) == 0); // Send "World" back to DEALER rc = zmq_msg_send (&routing_id, stream, ZMQ_SNDMORE); assert (rc > 0); - byte world [] = { 0, 5, 'W', 'o', 'r', 'l', 'd' }; + byte world[] = {0, 5, 'W', 'o', 'r', 'l', 'd'}; rc = zmq_send (stream, world, sizeof (world), 0); assert (rc == sizeof (world)); @@ -200,12 +196,12 @@ test_stream_to_dealer (void) assert (memcmp (buffer, "World", 5) == 0); // Test large messages over STREAM socket -# define size 64000 - uint8_t msgout [size]; +#define size 64000 + uint8_t msgout[size]; memset (msgout, 0xAB, size); zmq_send (dealer, msgout, size, 0); - uint8_t msgin [9 + size]; + uint8_t msgin[9 + size]; memset (msgin, 0, 9 + size); bytes_read = 0; while (bytes_read < 9 + size) { @@ -219,7 +215,7 @@ test_stream_to_dealer (void) } int byte_nbr; for (byte_nbr = 0; byte_nbr < size; byte_nbr++) { - if (msgin [9 + byte_nbr] != 0xAB) + if (msgin[9 + byte_nbr] != 0xAB) assert (false); } rc = zmq_close (dealer); @@ -233,8 +229,7 @@ test_stream_to_dealer (void) } -static void -test_stream_to_stream (void) +static void test_stream_to_stream (void) { int rc; size_t len = MAX_SOCKET_STRING; @@ -259,9 +254,9 @@ test_stream_to_stream (void) assert (rc == 0); rc = zmq_connect (client, my_endpoint); assert (rc == 0); - uint8_t id [256]; + uint8_t id[256]; size_t id_size = 256; - uint8_t buffer [256]; + uint8_t buffer[256]; // Connecting sends a zero message // Server: First frame is routing id, second frame is zero @@ -294,11 +289,10 @@ test_stream_to_stream (void) assert (memcmp (buffer, "GET /\n\n", 7) == 0); // Send reply back to client - char http_response [] = - "HTTP/1.0 200 OK\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - "Hello, World!"; + char http_response[] = "HTTP/1.0 200 OK\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Hello, World!"; rc = zmq_send (server, id, id_size, ZMQ_SNDMORE); assert (rc != -1); rc = zmq_send (server, http_response, sizeof (http_response), ZMQ_SNDMORE); @@ -336,7 +330,7 @@ test_stream_to_stream (void) int main (void) { - setup_test_environment(); + setup_test_environment (); test_stream_to_dealer (); test_stream_to_stream (); } diff --git a/tests/test_stream_disconnect.cpp b/tests/test_stream_disconnect.cpp index 9f4cb5649e..1071730ccb 100644 --- a/tests/test_stream_disconnect.cpp +++ b/tests/test_stream_disconnect.cpp @@ -32,68 +32,71 @@ static const int SERVER = 0; static const int CLIENT = 1; -struct test_message_t { +struct test_message_t +{ int turn; - const char * text; + const char *text; }; // NOTE: messages are sent without null terminator. -const test_message_t dialog [] = { - {CLIENT, "i can haz cheez burger?"}, - {SERVER, "y u no disonnect?"}, - {CLIENT, ""}, +const test_message_t dialog[] = { + {CLIENT, "i can haz cheez burger?"}, + {SERVER, "y u no disonnect?"}, + {CLIENT, ""}, }; -const int steps = sizeof(dialog) / sizeof(dialog[0]); +const int steps = sizeof (dialog) / sizeof (dialog[0]); -bool has_more (void* socket) +bool has_more (void *socket) { int more = 0; - size_t more_size = sizeof(more); + size_t more_size = sizeof (more); int rc = zmq_getsockopt (socket, ZMQ_RCVMORE, &more, &more_size); if (rc != 0) return false; return more != 0; } -bool get_routing_id (void* socket, char* data, size_t* size) +bool get_routing_id (void *socket, char *data, size_t *size) { int rc = zmq_getsockopt (socket, ZMQ_ROUTING_ID, data, size); return rc == 0; } -int main(int, char**) +int main (int, char **) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char bind_endpoint[MAX_SOCKET_STRING]; char connect_endpoint[MAX_SOCKET_STRING]; void *context = zmq_ctx_new (); - void *sockets [2]; + void *sockets[2]; int rc = 0; - sockets [SERVER] = zmq_socket (context, ZMQ_STREAM); + sockets[SERVER] = zmq_socket (context, ZMQ_STREAM); int enabled = 1; - rc = zmq_setsockopt (sockets [SERVER], ZMQ_STREAM_NOTIFY, &enabled, sizeof (enabled)); + rc = zmq_setsockopt (sockets[SERVER], ZMQ_STREAM_NOTIFY, &enabled, + sizeof (enabled)); assert (rc == 0); - rc = zmq_bind (sockets [SERVER], "tcp://0.0.0.0:*"); + rc = zmq_bind (sockets[SERVER], "tcp://0.0.0.0:*"); assert (rc == 0); - rc = zmq_getsockopt (sockets [SERVER], ZMQ_LAST_ENDPOINT, bind_endpoint, - &len); + rc = + zmq_getsockopt (sockets[SERVER], ZMQ_LAST_ENDPOINT, bind_endpoint, &len); assert (rc == 0); // Apparently Windows can't connect to 0.0.0.0. A better fix would be welcome. #ifdef ZMQ_HAVE_WINDOWS sprintf (connect_endpoint, "tcp://127.0.0.1:%s", - strrchr(bind_endpoint, ':') + 1); + strrchr (bind_endpoint, ':') + 1); #else strcpy (connect_endpoint, bind_endpoint); #endif - sockets [CLIENT] = zmq_socket (context, ZMQ_STREAM); - rc = zmq_setsockopt (sockets [CLIENT], ZMQ_STREAM_NOTIFY, &enabled, sizeof (enabled)); + sockets[CLIENT] = zmq_socket (context, ZMQ_STREAM); + rc = zmq_setsockopt (sockets[CLIENT], ZMQ_STREAM_NOTIFY, &enabled, + sizeof (enabled)); assert (rc == 0); - rc = zmq_connect (sockets [CLIENT], connect_endpoint); + rc = zmq_connect (sockets[CLIENT], connect_endpoint); assert (rc == 0); // wait for connect notification @@ -101,10 +104,10 @@ int main(int, char**) zmq_msg_t peer_frame; rc = zmq_msg_init (&peer_frame); assert (rc == 0); - rc = zmq_msg_recv (&peer_frame, sockets [SERVER], 0); + rc = zmq_msg_recv (&peer_frame, sockets[SERVER], 0); assert (rc != -1); - assert(zmq_msg_size (&peer_frame) > 0); - assert (has_more (sockets [SERVER])); + assert (zmq_msg_size (&peer_frame) > 0); + assert (has_more (sockets[SERVER])); rc = zmq_msg_close (&peer_frame); assert (rc == 0); @@ -112,49 +115,50 @@ int main(int, char**) zmq_msg_t data_frame; rc = zmq_msg_init (&data_frame); assert (rc == 0); - rc = zmq_msg_recv (&data_frame, sockets [SERVER], 0); + rc = zmq_msg_recv (&data_frame, sockets[SERVER], 0); assert (rc != -1); - assert(zmq_msg_size (&data_frame) == 0); + assert (zmq_msg_size (&data_frame) == 0); rc = zmq_msg_close (&data_frame); assert (rc == 0); // Client: Grab the 1st frame (peer routing id). rc = zmq_msg_init (&peer_frame); assert (rc == 0); - rc = zmq_msg_recv (&peer_frame, sockets [CLIENT], 0); + rc = zmq_msg_recv (&peer_frame, sockets[CLIENT], 0); assert (rc != -1); - assert(zmq_msg_size (&peer_frame) > 0); - assert (has_more (sockets [CLIENT])); + assert (zmq_msg_size (&peer_frame) > 0); + assert (has_more (sockets[CLIENT])); rc = zmq_msg_close (&peer_frame); assert (rc == 0); // Client: Grab the 2nd frame (actual payload). rc = zmq_msg_init (&data_frame); assert (rc == 0); - rc = zmq_msg_recv (&data_frame, sockets [CLIENT], 0); + rc = zmq_msg_recv (&data_frame, sockets[CLIENT], 0); assert (rc != -1); - assert(zmq_msg_size (&data_frame) == 0); + assert (zmq_msg_size (&data_frame) == 0); rc = zmq_msg_close (&data_frame); assert (rc == 0); // Send initial message. - char blob_data [256]; - size_t blob_size = sizeof(blob_data); - rc = zmq_getsockopt (sockets [CLIENT], ZMQ_ROUTING_ID, blob_data, &blob_size); + char blob_data[256]; + size_t blob_size = sizeof (blob_data); + rc = + zmq_getsockopt (sockets[CLIENT], ZMQ_ROUTING_ID, blob_data, &blob_size); assert (rc != -1); - assert(blob_size > 0); + assert (blob_size > 0); zmq_msg_t msg; rc = zmq_msg_init_size (&msg, blob_size); assert (rc == 0); memcpy (zmq_msg_data (&msg), blob_data, blob_size); - rc = zmq_msg_send (&msg, sockets [dialog [0].turn], ZMQ_SNDMORE); + rc = zmq_msg_send (&msg, sockets[dialog[0].turn], ZMQ_SNDMORE); assert (rc != -1); rc = zmq_msg_close (&msg); assert (rc == 0); - rc = zmq_msg_init_size (&msg, strlen(dialog [0].text)); + rc = zmq_msg_init_size (&msg, strlen (dialog[0].text)); assert (rc == 0); - memcpy (zmq_msg_data (&msg), dialog [0].text, strlen(dialog [0].text)); - rc = zmq_msg_send (&msg, sockets [dialog [0].turn], ZMQ_SNDMORE); + memcpy (zmq_msg_data (&msg), dialog[0].text, strlen (dialog[0].text)); + rc = zmq_msg_send (&msg, sockets[dialog[0].turn], ZMQ_SNDMORE); assert (rc != -1); rc = zmq_msg_close (&msg); assert (rc == 0); @@ -165,45 +169,44 @@ int main(int, char**) int step = 0; while (step < steps) { // Wait until something happens. - zmq_pollitem_t items [] = { - { sockets [SERVER], 0, ZMQ_POLLIN, 0 }, - { sockets [CLIENT], 0, ZMQ_POLLIN, 0 }, + zmq_pollitem_t items[] = { + {sockets[SERVER], 0, ZMQ_POLLIN, 0}, + {sockets[CLIENT], 0, ZMQ_POLLIN, 0}, }; int rc = zmq_poll (items, 2, 100); assert (rc >= 0); // Check for data received by the server. - if (items [SERVER].revents & ZMQ_POLLIN) { - assert (dialog [step].turn == CLIENT); + if (items[SERVER].revents & ZMQ_POLLIN) { + assert (dialog[step].turn == CLIENT); // Grab the 1st frame (peer routing id). zmq_msg_t peer_frame; rc = zmq_msg_init (&peer_frame); assert (rc == 0); - rc = zmq_msg_recv (&peer_frame, sockets [SERVER], 0); + rc = zmq_msg_recv (&peer_frame, sockets[SERVER], 0); assert (rc != -1); - assert(zmq_msg_size (&peer_frame) > 0); - assert (has_more (sockets [SERVER])); + assert (zmq_msg_size (&peer_frame) > 0); + assert (has_more (sockets[SERVER])); // Grab the 2nd frame (actual payload). zmq_msg_t data_frame; rc = zmq_msg_init (&data_frame); assert (rc == 0); - rc = zmq_msg_recv (&data_frame, sockets [SERVER], 0); + rc = zmq_msg_recv (&data_frame, sockets[SERVER], 0); assert (rc != -1); // Make sure payload matches what we expect. - const char * const data = (const char*)zmq_msg_data (&data_frame); + const char *const data = (const char *) zmq_msg_data (&data_frame); const int size = zmq_msg_size (&data_frame); // 0-length frame is a disconnection notification. The server // should receive it as the last step in the dialogue. if (size == 0) { ++step; assert (step == steps); - } - else { - assert ((size_t) size == strlen (dialog [step].text)); - int cmp = memcmp (dialog [step].text, data, size); + } else { + assert ((size_t) size == strlen (dialog[step].text)); + int cmp = memcmp (dialog[step].text, data, size); assert (cmp == 0); ++step; @@ -213,16 +216,16 @@ int main(int, char**) // Prepare the response. rc = zmq_msg_close (&data_frame); assert (rc == 0); - rc = zmq_msg_init_size (&data_frame, - strlen (dialog [step].text)); + rc = + zmq_msg_init_size (&data_frame, strlen (dialog[step].text)); assert (rc == 0); - memcpy (zmq_msg_data (&data_frame), dialog [step].text, + memcpy (zmq_msg_data (&data_frame), dialog[step].text, zmq_msg_size (&data_frame)); // Send the response. - rc = zmq_msg_send (&peer_frame, sockets [SERVER], ZMQ_SNDMORE); + rc = zmq_msg_send (&peer_frame, sockets[SERVER], ZMQ_SNDMORE); assert (rc != -1); - rc = zmq_msg_send (&data_frame, sockets [SERVER], ZMQ_SNDMORE); + rc = zmq_msg_send (&data_frame, sockets[SERVER], ZMQ_SNDMORE); assert (rc != -1); } @@ -234,31 +237,31 @@ int main(int, char**) } // Check for data received by the client. - if (items [CLIENT].revents & ZMQ_POLLIN) { - assert (dialog [step].turn == SERVER); + if (items[CLIENT].revents & ZMQ_POLLIN) { + assert (dialog[step].turn == SERVER); // Grab the 1st frame (peer routing id). zmq_msg_t peer_frame; rc = zmq_msg_init (&peer_frame); assert (rc == 0); - rc = zmq_msg_recv (&peer_frame, sockets [CLIENT], 0); + rc = zmq_msg_recv (&peer_frame, sockets[CLIENT], 0); assert (rc != -1); - assert(zmq_msg_size (&peer_frame) > 0); - assert (has_more (sockets [CLIENT])); + assert (zmq_msg_size (&peer_frame) > 0); + assert (has_more (sockets[CLIENT])); // Grab the 2nd frame (actual payload). zmq_msg_t data_frame; rc = zmq_msg_init (&data_frame); assert (rc == 0); - rc = zmq_msg_recv (&data_frame, sockets [CLIENT], 0); + rc = zmq_msg_recv (&data_frame, sockets[CLIENT], 0); assert (rc != -1); - assert(zmq_msg_size (&data_frame) > 0); + assert (zmq_msg_size (&data_frame) > 0); // Make sure payload matches what we expect. - const char * const data = (const char*)zmq_msg_data (&data_frame); + const char *const data = (const char *) zmq_msg_data (&data_frame); const int size = zmq_msg_size (&data_frame); - assert ((size_t)size == strlen(dialog [step].text)); - int cmp = memcmp(dialog [step].text, data, size); + assert ((size_t) size == strlen (dialog[step].text)); + int cmp = memcmp (dialog[step].text, data, size); assert (cmp == 0); ++step; @@ -267,14 +270,15 @@ int main(int, char**) assert (step < steps); rc = zmq_msg_close (&data_frame); assert (rc == 0); - rc = zmq_msg_init_size (&data_frame, strlen (dialog [step].text)); + rc = zmq_msg_init_size (&data_frame, strlen (dialog[step].text)); assert (rc == 0); - memcpy (zmq_msg_data (&data_frame), dialog [step].text, zmq_msg_size (&data_frame)); + memcpy (zmq_msg_data (&data_frame), dialog[step].text, + zmq_msg_size (&data_frame)); // Send the response. - rc = zmq_msg_send (&peer_frame, sockets [CLIENT], ZMQ_SNDMORE); + rc = zmq_msg_send (&peer_frame, sockets[CLIENT], ZMQ_SNDMORE); assert (rc != -1); - rc = zmq_msg_send (&data_frame, sockets [CLIENT], ZMQ_SNDMORE); + rc = zmq_msg_send (&data_frame, sockets[CLIENT], ZMQ_SNDMORE); assert (rc != -1); // Release resources. @@ -285,9 +289,9 @@ int main(int, char**) } } assert (step == steps); - rc = zmq_close (sockets [CLIENT]); + rc = zmq_close (sockets[CLIENT]); assert (rc == 0); - rc = zmq_close (sockets [SERVER]); + rc = zmq_close (sockets[SERVER]); assert (rc == 0); rc = zmq_ctx_term (context); assert (rc == 0); diff --git a/tests/test_stream_empty.cpp b/tests/test_stream_empty.cpp index 23a7b501f8..09d73df512 100644 --- a/tests/test_stream_empty.cpp +++ b/tests/test_stream_empty.cpp @@ -29,18 +29,19 @@ #include "testutil.hpp" -int main (void) { +int main (void) +{ setup_test_environment (); size_t len = MAX_SOCKET_STRING; char my_endpoint[MAX_SOCKET_STRING]; void *ctx = zmq_ctx_new (); assert (ctx); - + void *stream = zmq_socket (ctx, ZMQ_STREAM); assert (stream); void *dealer = zmq_socket (ctx, ZMQ_DEALER); assert (dealer); - + int rc = zmq_bind (stream, "tcp://127.0.0.1:*"); assert (rc >= 0); rc = zmq_getsockopt (stream, ZMQ_LAST_ENDPOINT, my_endpoint, &len); @@ -48,26 +49,26 @@ int main (void) { rc = zmq_connect (dealer, my_endpoint); assert (rc >= 0); zmq_send (dealer, "", 0, 0); - + zmq_msg_t ident, empty; zmq_msg_init (&ident); rc = zmq_msg_recv (&ident, stream, 0); assert (rc >= 0); rc = zmq_msg_init_data (&empty, (void *) "", 0, NULL, NULL); assert (rc >= 0); - + rc = zmq_msg_send (&ident, stream, ZMQ_SNDMORE); assert (rc >= 0); rc = zmq_msg_close (&ident); assert (rc >= 0); - + rc = zmq_msg_send (&empty, stream, 0); assert (rc >= 0); - + // This close used to fail with Bad Address rc = zmq_msg_close (&empty); assert (rc >= 0); - + close_zero_linger (dealer); close_zero_linger (stream); zmq_ctx_term (ctx); diff --git a/tests/test_stream_exceeds_buffer.cpp b/tests/test_stream_exceeds_buffer.cpp index 09a442d430..21823b537e 100644 --- a/tests/test_stream_exceeds_buffer.cpp +++ b/tests/test_stream_exceeds_buffer.cpp @@ -29,96 +29,96 @@ #include "testutil.hpp" -#if defined (ZMQ_HAVE_WINDOWS) -# include -# include -# include -# define close closesocket +#if defined(ZMQ_HAVE_WINDOWS) +#include +#include +#include +#define close closesocket #endif -int main() +int main () { const int msgsize = 8193; char sndbuf[msgsize] = "\xde\xad\xbe\xef"; unsigned char rcvbuf[msgsize]; char my_endpoint[MAX_SOCKET_STRING]; - int server_sock = socket(AF_INET, SOCK_STREAM, 0); - assert(server_sock!=-1); + int server_sock = socket (AF_INET, SOCK_STREAM, 0); + assert (server_sock != -1); int enable = 1; - int rc = setsockopt (server_sock, SOL_SOCKET, SO_REUSEADDR, (char *) &enable, sizeof(enable)); - assert(rc!=-1); + int rc = setsockopt (server_sock, SOL_SOCKET, SO_REUSEADDR, + (char *) &enable, sizeof (enable)); + assert (rc != -1); struct sockaddr_in saddr; - memset(&saddr, 0, sizeof(saddr)); + memset (&saddr, 0, sizeof (saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = INADDR_ANY; -#if !defined (_WIN32_WINNT) || (_WIN32_WINNT >= 0x0600) +#if !defined(_WIN32_WINNT) || (_WIN32_WINNT >= 0x0600) saddr.sin_port = 0; #else - saddr.sin_port = htons(12345); + saddr.sin_port = htons (12345); #endif - rc = bind(server_sock, (struct sockaddr *)&saddr, sizeof(saddr)); - assert(rc!=-1); - rc = listen(server_sock, 1); - assert(rc!=-1); + rc = bind (server_sock, (struct sockaddr *) &saddr, sizeof (saddr)); + assert (rc != -1); + rc = listen (server_sock, 1); + assert (rc != -1); -#if !defined (_WIN32_WINNT) || (_WIN32_WINNT >= 0x0600) +#if !defined(_WIN32_WINNT) || (_WIN32_WINNT >= 0x0600) socklen_t saddr_len = sizeof (saddr); - rc = getsockname (server_sock, (struct sockaddr *)&saddr, &saddr_len); + rc = getsockname (server_sock, (struct sockaddr *) &saddr, &saddr_len); assert (rc != -1); #endif - sprintf (my_endpoint, "tcp://127.0.0.1:%d", ntohs(saddr.sin_port)); + sprintf (my_endpoint, "tcp://127.0.0.1:%d", ntohs (saddr.sin_port)); - void *zctx = zmq_ctx_new(); - assert(zctx); - void *zsock = zmq_socket(zctx, ZMQ_STREAM); - assert(zsock); - rc = zmq_connect(zsock, my_endpoint); - assert(rc!=-1); + void *zctx = zmq_ctx_new (); + assert (zctx); + void *zsock = zmq_socket (zctx, ZMQ_STREAM); + assert (zsock); + rc = zmq_connect (zsock, my_endpoint); + assert (rc != -1); - int client_sock = accept(server_sock, NULL, NULL); - assert(client_sock!=-1); + int client_sock = accept (server_sock, NULL, NULL); + assert (client_sock != -1); - rc = close(server_sock); - assert(rc!=-1); + rc = close (server_sock); + assert (rc != -1); - rc = send(client_sock, sndbuf, msgsize, 0); - assert(rc==msgsize); + rc = send (client_sock, sndbuf, msgsize, 0); + assert (rc == msgsize); zmq_msg_t msg; - zmq_msg_init(&msg); + zmq_msg_init (&msg); int rcvbytes = 0; - while (rcvbytes==0) // skip connection notification, if any + while (rcvbytes == 0) // skip connection notification, if any { - rc = zmq_msg_recv(&msg, zsock, 0); // peerid - assert(rc!=-1); - assert(zmq_msg_more(&msg)); - rcvbytes = zmq_msg_recv(&msg, zsock, 0); - assert(rcvbytes!=-1); - assert(!zmq_msg_more(&msg)); + rc = zmq_msg_recv (&msg, zsock, 0); // peerid + assert (rc != -1); + assert (zmq_msg_more (&msg)); + rcvbytes = zmq_msg_recv (&msg, zsock, 0); + assert (rcvbytes != -1); + assert (!zmq_msg_more (&msg)); } // for this test, we only collect the first chunk // since the corruption already occurs in the first chunk - memcpy(rcvbuf, zmq_msg_data(&msg), zmq_msg_size(&msg)); + memcpy (rcvbuf, zmq_msg_data (&msg), zmq_msg_size (&msg)); - zmq_msg_close(&msg); - zmq_close(zsock); - close(client_sock); + zmq_msg_close (&msg); + zmq_close (zsock); + close (client_sock); - zmq_ctx_destroy(zctx); + zmq_ctx_destroy (zctx); - assert(rcvbytes >= 4); + assert (rcvbytes >= 4); // notice that only the 1st byte gets corrupted - assert(rcvbuf[3]==0xef); - assert(rcvbuf[2]==0xbe); - assert(rcvbuf[1]==0xad); - assert(rcvbuf[0]==0xde); + assert (rcvbuf[3] == 0xef); + assert (rcvbuf[2] == 0xbe); + assert (rcvbuf[1] == 0xad); + assert (rcvbuf[0] == 0xde); - (void)(rc); // avoid -Wunused-but-set-variable warning in release build + (void) (rc); // avoid -Wunused-but-set-variable warning in release build } - diff --git a/tests/test_stream_timeout.cpp b/tests/test_stream_timeout.cpp index d1421e9458..cfe08aab52 100644 --- a/tests/test_stream_timeout.cpp +++ b/tests/test_stream_timeout.cpp @@ -33,16 +33,15 @@ // by reference, if not null, and event number by value. Returns -1 // in case of error. -static int -get_monitor_event (void *monitor, int *value, char **address) +static int get_monitor_event (void *monitor, int *value, char **address) { // First frame in message contains event number and value - zmq_msg_t msg; + zmq_msg_t msg; zmq_msg_init (&msg); if (zmq_msg_recv (&msg, monitor, 0) == -1) - return -1; // Interruped, presumably + return -1; // Interruped, presumably assert (zmq_msg_more (&msg)); - + uint8_t *data = (uint8_t *) zmq_msg_data (&msg); uint16_t event = *(uint16_t *) (data); if (value) @@ -51,21 +50,20 @@ get_monitor_event (void *monitor, int *value, char **address) // Second frame in message contains event address zmq_msg_init (&msg); if (zmq_msg_recv (&msg, monitor, 0) == -1) - return -1; // Interruped, presumably + return -1; // Interruped, presumably assert (!zmq_msg_more (&msg)); - + if (address) { uint8_t *data = (uint8_t *) zmq_msg_data (&msg); size_t size = zmq_msg_size (&msg); *address = (char *) malloc (size + 1); memcpy (*address, data, size); - *address [size] = 0; + *address[size] = 0; } return event; } -static void -test_stream_handshake_timeout_accept (void) +static void test_stream_handshake_timeout_accept (void) { int rc; size_t len = MAX_SOCKET_STRING; @@ -89,21 +87,21 @@ test_stream_handshake_timeout_accept (void) rc = zmq_setsockopt (dealer, ZMQ_LINGER, &zero, sizeof (zero)); assert (rc == 0); int val, tenth = 100; - size_t vsize = sizeof(val); + size_t vsize = sizeof (val); // check for the expected default handshake timeout value - 30 sec rc = zmq_getsockopt (dealer, ZMQ_HANDSHAKE_IVL, &val, &vsize); assert (rc == 0); - assert (vsize == sizeof(val)); + assert (vsize == sizeof (val)); assert (val == 30000); // make handshake timeout faster - 1/10 sec rc = zmq_setsockopt (dealer, ZMQ_HANDSHAKE_IVL, &tenth, sizeof (tenth)); assert (rc == 0); - vsize = sizeof(val); + vsize = sizeof (val); // make sure zmq_setsockopt changed the value rc = zmq_getsockopt (dealer, ZMQ_HANDSHAKE_IVL, &val, &vsize); assert (rc == 0); - assert (vsize == sizeof(val)); + assert (vsize == sizeof (val)); assert (val == tenth); // Create and connect a socket for collecting monitor events on dealer @@ -111,7 +109,8 @@ test_stream_handshake_timeout_accept (void) assert (dealer_mon); rc = zmq_socket_monitor (dealer, "inproc://monitor-dealer", - ZMQ_EVENT_CONNECTED | ZMQ_EVENT_DISCONNECTED | ZMQ_EVENT_ACCEPTED); + ZMQ_EVENT_CONNECTED | ZMQ_EVENT_DISCONNECTED + | ZMQ_EVENT_ACCEPTED); assert (rc == 0); // Connect to the inproc endpoint so we'll get events @@ -146,8 +145,7 @@ test_stream_handshake_timeout_accept (void) assert (rc == 0); } -static void -test_stream_handshake_timeout_connect (void) +static void test_stream_handshake_timeout_connect (void) { int rc; size_t len = MAX_SOCKET_STRING; @@ -175,21 +173,21 @@ test_stream_handshake_timeout_connect (void) rc = zmq_setsockopt (dealer, ZMQ_LINGER, &zero, sizeof (zero)); assert (rc == 0); int val, tenth = 100; - size_t vsize = sizeof(val); + size_t vsize = sizeof (val); // check for the expected default handshake timeout value - 30 sec rc = zmq_getsockopt (dealer, ZMQ_HANDSHAKE_IVL, &val, &vsize); assert (rc == 0); - assert (vsize == sizeof(val)); + assert (vsize == sizeof (val)); assert (val == 30000); // make handshake timeout faster - 1/10 sec rc = zmq_setsockopt (dealer, ZMQ_HANDSHAKE_IVL, &tenth, sizeof (tenth)); assert (rc == 0); - vsize = sizeof(val); + vsize = sizeof (val); // make sure zmq_setsockopt changed the value rc = zmq_getsockopt (dealer, ZMQ_HANDSHAKE_IVL, &val, &vsize); assert (rc == 0); - assert (vsize == sizeof(val)); + assert (vsize == sizeof (val)); assert (val == tenth); // Create and connect a socket for collecting monitor events on dealer @@ -197,7 +195,8 @@ test_stream_handshake_timeout_connect (void) assert (dealer_mon); rc = zmq_socket_monitor (dealer, "inproc://monitor-dealer", - ZMQ_EVENT_CONNECTED | ZMQ_EVENT_DISCONNECTED | ZMQ_EVENT_ACCEPTED); + ZMQ_EVENT_CONNECTED | ZMQ_EVENT_DISCONNECTED + | ZMQ_EVENT_ACCEPTED); assert (rc == 0); // Connect to the inproc endpoint so we'll get events @@ -229,7 +228,7 @@ test_stream_handshake_timeout_connect (void) int main (void) { - setup_test_environment(); + setup_test_environment (); test_stream_handshake_timeout_accept (); test_stream_handshake_timeout_connect (); } diff --git a/tests/test_sub_forward.cpp b/tests/test_sub_forward.cpp index ccf3e77063..ace52a069b 100644 --- a/tests/test_sub_forward.cpp +++ b/tests/test_sub_forward.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); size_t len = MAX_SOCKET_STRING; char endpoint1[MAX_SOCKET_STRING]; char endpoint2[MAX_SOCKET_STRING]; @@ -70,7 +70,7 @@ int main (void) assert (rc == 0); // Pass the subscription upstream through the device - char buff [32]; + char buff[32]; rc = zmq_recv (xpub, buff, sizeof (buff), 0); assert (rc >= 0); rc = zmq_send (xsub, buff, rc, 0); @@ -105,5 +105,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_sub_forward_tipc.cpp b/tests/test_sub_forward_tipc.cpp index 7c49c664fd..173cb0252f 100644 --- a/tests/test_sub_forward_tipc.cpp +++ b/tests/test_sub_forward_tipc.cpp @@ -63,7 +63,7 @@ int main (void) assert (rc == 0); // Pass the subscription upstream through the device. - char buff [32]; + char buff[32]; rc = zmq_recv (xpub, buff, sizeof (buff), 0); assert (rc >= 0); rc = zmq_send (xsub, buff, rc, 0); @@ -98,5 +98,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_system.cpp b/tests/test_system.cpp index 96d82caa8d..f1c2c62ad6 100644 --- a/tests/test_system.cpp +++ b/tests/test_system.cpp @@ -29,22 +29,22 @@ #include "testutil.hpp" -#if defined (ZMQ_HAVE_WINDOWS) -# include -# include +#if defined(ZMQ_HAVE_WINDOWS) +#include +#include #else -# include -# include -# include +#include +#include +#include #endif -#if defined (ZMQ_HAVE_WINDOWS) +#if defined(ZMQ_HAVE_WINDOWS) void initialise_network (void) { WSADATA info; - if (WSAStartup(MAKEWORD(2,0), &info) != 0) - throw std::runtime_error("Could not start WSA"); + if (WSAStartup (MAKEWORD (2, 0), &info) != 0) + throw std::runtime_error ("Could not start WSA"); } #else @@ -68,31 +68,34 @@ int main (void) assert (ctx); void *dealer = zmq_socket (ctx, ZMQ_DEALER); if (zmq_bind (dealer, "tcp://127.0.0.1:*") == -1) { - printf ("E: Cannot find 127.0.0.1 -- your system does not have local\n"); - printf ("E: networking. Please fix this before running libzmq checks.\n"); + printf ( + "E: Cannot find 127.0.0.1 -- your system does not have local\n"); + printf ( + "E: networking. Please fix this before running libzmq checks.\n"); return -1; } // Check that we can create 1,000 sockets - int handle [1000]; + int handle[1000]; int count; for (count = 0; count < 1000; count++) { - handle [count] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (handle [count] == -1) { + handle[count] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (handle[count] == -1) { printf ("W: Only able to create %d sockets on this box\n", count); - printf ("I: Tune your system to increase maximum allowed file handles\n"); -#if defined (ZMQ_HAVE_OSX) + printf ( + "I: Tune your system to increase maximum allowed file handles\n"); +#if defined(ZMQ_HAVE_OSX) printf ("I: On OS/X, run 'ulimit -n 1200' in bash\n"); -#elif defined (ZMQ_HAVE_LINUX) +#elif defined(ZMQ_HAVE_LINUX) printf ("I: On Linux, run 'ulimit -n 1200' in bash\n"); -#endif +#endif return -1; } } // Release the socket handles for (count = 0; count < 1000; count++) { - close(handle[count]); + close (handle[count]); } - zmq_close(dealer); - zmq_ctx_term(ctx); + zmq_close (dealer); + zmq_ctx_term (ctx); } diff --git a/tests/test_term_endpoint.cpp b/tests/test_term_endpoint.cpp index d02c8e9542..885a5eef96 100644 --- a/tests/test_term_endpoint.cpp +++ b/tests/test_term_endpoint.cpp @@ -31,11 +31,11 @@ #include "testutil.hpp" /* Use the worst case filename size for the buffer (+1 for trailing NUL) */ -#define BUF_SIZE (FILENAME_MAX+1) +#define BUF_SIZE (FILENAME_MAX + 1) int main (void) { - setup_test_environment(); + setup_test_environment (); int rc; char buf[BUF_SIZE]; size_t buf_size; @@ -54,7 +54,7 @@ int main (void) assert (push); rc = zmq_bind (push, ep_wc_tcp); assert (rc == 0); - buf_size = sizeof(buf); + buf_size = sizeof (buf); rc = zmq_getsockopt (push, ZMQ_LAST_ENDPOINT, buf, &buf_size); assert (rc == 0); void *pull = zmq_socket (ctx, ZMQ_PULL); @@ -69,7 +69,7 @@ int main (void) assert (rc == 3); // Unbind the listening endpoint - buf_size = sizeof(buf); + buf_size = sizeof (buf); rc = zmq_getsockopt (push, ZMQ_LAST_ENDPOINT, buf, &buf_size); assert (rc == 0); rc = zmq_unbind (push, buf); @@ -97,7 +97,7 @@ int main (void) assert (pull); rc = zmq_bind (pull, ep_wc_tcp); assert (rc == 0); - buf_size = sizeof(buf); + buf_size = sizeof (buf); rc = zmq_getsockopt (pull, ZMQ_LAST_ENDPOINT, buf, &buf_size); assert (rc == 0); push = zmq_socket (ctx, ZMQ_PUSH); @@ -112,7 +112,7 @@ int main (void) assert (rc == 3); // Disconnect the bound endpoint - buf_size = sizeof(buf); + buf_size = sizeof (buf); rc = zmq_getsockopt (pull, ZMQ_LAST_ENDPOINT, buf, &buf_size); assert (rc == 0); rc = zmq_disconnect (push, buf); @@ -140,8 +140,8 @@ int main (void) assert (push); rc = zmq_bind (push, ep_wc_tcp); assert (rc == 0); - pull = zmq_socket(ctx, ZMQ_PULL); - assert(pull); + pull = zmq_socket (ctx, ZMQ_PULL); + assert (pull); #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS rc = zmq_bind (pull, ep_wc_ipc); assert (rc == 0); @@ -154,23 +154,23 @@ int main (void) #endif // Unbind sockets binded by wild-card address - buf_size = sizeof(buf); + buf_size = sizeof (buf); rc = zmq_getsockopt (push, ZMQ_LAST_ENDPOINT, buf, &buf_size); assert (rc == 0); rc = zmq_unbind (push, buf); assert (rc == 0); #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS - buf_size = sizeof(buf); + buf_size = sizeof (buf); rc = zmq_getsockopt (pull, ZMQ_LAST_ENDPOINT, buf, &buf_size); assert (rc == 0); rc = zmq_unbind (pull, buf); assert (rc == 0); #endif #if defined ZMQ_HAVE_VMCI - buf_size = sizeof(buf); + buf_size = sizeof (buf); rc = zmq_getsockopt (req, ZMQ_LAST_ENDPOINT, buf, &buf_size); assert (rc == 0); - rc = zmq_unbind(req, buf); + rc = zmq_unbind (req, buf); assert (rc == 0); #endif @@ -189,9 +189,9 @@ int main (void) assert (push); rc = zmq_bind (push, ep_wc_tcp); assert (rc == 0); - pull = zmq_socket(ctx, ZMQ_PULL); - assert(pull); -#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS + pull = zmq_socket (ctx, ZMQ_PULL); + assert (pull); +#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS rc = zmq_bind (pull, ep_wc_ipc); assert (rc == 0); #endif diff --git a/tests/test_thread_safe.cpp b/tests/test_thread_safe.cpp index bd9976e51f..3d27a23a66 100644 --- a/tests/test_thread_safe.cpp +++ b/tests/test_thread_safe.cpp @@ -72,7 +72,7 @@ int main (void) while (threads_completed < 2) { zmq_recv (server, &data, 1, 0); if (data == 1) - threads_completed++; // Thread ended + threads_completed++; // Thread ended } zmq_threadclose (t1); zmq_threadclose (t2); @@ -86,5 +86,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_timeo.cpp b/tests/test_timeo.cpp index f5fe8edcee..fb5e2b57c5 100644 --- a/tests/test_timeo.cpp +++ b/tests/test_timeo.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -41,21 +41,21 @@ int main (void) assert (rc == 0); // Receive on disconnected socket returns immediately - char buffer [32]; + char buffer[32]; rc = zmq_recv (frontend, buffer, 32, ZMQ_DONTWAIT); assert (rc == -1); - assert (zmq_errno() == EAGAIN); - + assert (zmq_errno () == EAGAIN); + // Check whether receive timeout is honored int timeout = 250; rc = zmq_setsockopt (frontend, ZMQ_RCVTIMEO, &timeout, sizeof (int)); assert (rc == 0); - void* stopwatch = zmq_stopwatch_start(); + void *stopwatch = zmq_stopwatch_start (); rc = zmq_recv (frontend, buffer, 32, 0); assert (rc == -1); assert (zmq_errno () == EAGAIN); - unsigned int elapsed = zmq_stopwatch_stop(stopwatch) / 1000; + unsigned int elapsed = zmq_stopwatch_stop (stopwatch) / 1000; assert (elapsed > 200 && elapsed < 300); // Check that normal message flow works as expected @@ -74,12 +74,12 @@ int main (void) // Clean-up rc = zmq_close (backend); assert (rc == 0); - + rc = zmq_close (frontend); assert (rc == 0); - + rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_timers.cpp b/tests/test_timers.cpp index 065848ab89..f29ea519b4 100644 --- a/tests/test_timers.cpp +++ b/tests/test_timers.cpp @@ -30,23 +30,23 @@ #define __STDC_LIMIT_MACROS // to define SIZE_MAX with older compilers #include "testutil.hpp" -void handler (int timer_id, void* arg) +void handler (int timer_id, void *arg) { - (void) timer_id; // Stop 'unused' compiler warnings - *((bool *)arg) = true; + (void) timer_id; // Stop 'unused' compiler warnings + *((bool *) arg) = true; } -int sleep_and_execute(void *timers_) +int sleep_and_execute (void *timers_) { int timeout = zmq_timers_timeout (timers_); // Sleep methods are inaccurate, so we sleep in a loop until time arrived while (timeout > 0) { msleep (timeout); - timeout = zmq_timers_timeout(timers_); + timeout = zmq_timers_timeout (timers_); } - return zmq_timers_execute(timers_); + return zmq_timers_execute (timers_); } void test_null_timer_pointers () @@ -138,7 +138,7 @@ void test_corner_cases () assert (rc == -1 && errno == EINVAL); // timeout without any timers active - rc = zmq_timers_timeout(timers); + rc = zmq_timers_timeout (timers); assert (rc == -1); rc = zmq_timers_destroy (&timers); @@ -149,7 +149,7 @@ int main (void) { setup_test_environment (); - void* timers = zmq_timers_new (); + void *timers = zmq_timers_new (); assert (timers); bool timer_invoked = false; @@ -163,14 +163,14 @@ int main (void) assert (!timer_invoked); // Wait half the time and check again - long timeout = zmq_timers_timeout(timers); + long timeout = zmq_timers_timeout (timers); assert (rc != -1); msleep (timeout / 2); rc = zmq_timers_execute (timers); assert (rc == 0); assert (!timer_invoked); - // Wait until the end + // Wait until the end rc = sleep_and_execute (timers); assert (rc == 0); assert (timer_invoked); @@ -193,7 +193,7 @@ int main (void) assert (!timer_invoked); // Wait until the end - rc = sleep_and_execute(timers); + rc = sleep_and_execute (timers); assert (rc == 0); assert (timer_invoked); timer_invoked = false; @@ -201,7 +201,7 @@ int main (void) // reschedule rc = zmq_timers_set_interval (timers, timer_id, 50); assert (rc == 0); - rc = sleep_and_execute(timers); + rc = sleep_and_execute (timers); assert (rc == 0); assert (timer_invoked); timer_invoked = false; diff --git a/tests/test_udp.cpp b/tests/test_udp.cpp index 265972f519..c3b7642bb6 100644 --- a/tests/test_udp.cpp +++ b/tests/test_udp.cpp @@ -29,7 +29,7 @@ #include "testutil.hpp" -int msg_send (zmq_msg_t *msg_, void *s_, const char* group_, const char* body_) +int msg_send (zmq_msg_t *msg_, void *s_, const char *group_, const char *body_) { int rc = zmq_msg_init_size (msg_, strlen (body_)); if (rc != 0) @@ -50,7 +50,10 @@ int msg_send (zmq_msg_t *msg_, void *s_, const char* group_, const char* body_) return rc; } -int msg_recv_cmp (zmq_msg_t *msg_, void *s_, const char* group_, const char* body_) +int msg_recv_cmp (zmq_msg_t *msg_, + void *s_, + const char *group_, + const char *body_) { int rc = zmq_msg_init (msg_); if (rc != 0) @@ -58,24 +61,22 @@ int msg_recv_cmp (zmq_msg_t *msg_, void *s_, const char* group_, const char* bod int recv_rc = zmq_msg_recv (msg_, s_, 0); if (recv_rc == -1) { - zmq_msg_close(msg_); + zmq_msg_close (msg_); return -1; } - if (strcmp (zmq_msg_group (msg_), group_) != 0) - { + if (strcmp (zmq_msg_group (msg_), group_) != 0) { zmq_msg_close (msg_); return -1; } - char * body = (char*) malloc (sizeof(char) * (zmq_msg_size (msg_) + 1)); + char *body = (char *) malloc (sizeof (char) * (zmq_msg_size (msg_) + 1)); memcpy (body, zmq_msg_data (msg_), zmq_msg_size (msg_)); - body [zmq_msg_size (msg_)] = '\0'; + body[zmq_msg_size (msg_)] = '\0'; - if (strcmp (body, body_) != 0) - { + if (strcmp (body, body_) != 0) { zmq_msg_close (msg_); - free(body); + free (body); return -1; } @@ -129,5 +130,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_unbind_inproc.cpp b/tests/test_unbind_inproc.cpp index b72a182207..6311e8d851 100644 --- a/tests/test_unbind_inproc.cpp +++ b/tests/test_unbind_inproc.cpp @@ -21,7 +21,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); diff --git a/tests/test_unbind_wildcard.cpp b/tests/test_unbind_wildcard.cpp index 12088c5bc6..c9bcef869d 100644 --- a/tests/test_unbind_wildcard.cpp +++ b/tests/test_unbind_wildcard.cpp @@ -21,7 +21,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); int ipv6 = is_ipv6_available (); @@ -37,14 +37,14 @@ int main (void) char bindEndpoint[256]; char connectEndpoint[256]; - size_t endpoint_len = sizeof (bindEndpoint); + size_t endpoint_len = sizeof (bindEndpoint); rc = zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, bindEndpoint, &endpoint_len); assert (rc == 0); // Apparently Windows can't connect to 0.0.0.0. A better fix would be welcome. #ifdef ZMQ_HAVE_WINDOWS sprintf (connectEndpoint, "tcp://127.0.0.1:%s", - strrchr(bindEndpoint, ':') + 1); + strrchr (bindEndpoint, ':') + 1); #else strcpy (connectEndpoint, bindEndpoint); #endif @@ -79,17 +79,17 @@ int main (void) assert (rc == 0); endpoint_len = sizeof (bindEndpoint); - memset(bindEndpoint, 0, endpoint_len); + memset (bindEndpoint, 0, endpoint_len); rc = zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, bindEndpoint, &endpoint_len); assert (rc == 0); #ifdef ZMQ_HAVE_WINDOWS if (ipv6) sprintf (connectEndpoint, "tcp://[::1]:%s", - strrchr(bindEndpoint, ':') + 1); + strrchr (bindEndpoint, ':') + 1); else sprintf (connectEndpoint, "tcp://127.0.0.1:%s", - strrchr(bindEndpoint, ':') + 1); + strrchr (bindEndpoint, ':') + 1); #else strcpy (connectEndpoint, bindEndpoint); #endif @@ -120,7 +120,7 @@ int main (void) char endpoint[256]; endpoint_len = sizeof (endpoint); - memset(endpoint, 0, endpoint_len); + memset (endpoint, 0, endpoint_len); rc = zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, endpoint, &endpoint_len); assert (rc == 0); @@ -154,7 +154,7 @@ int main (void) assert (rc == 0); endpoint_len = sizeof (endpoint); - memset(endpoint, 0, endpoint_len); + memset (endpoint, 0, endpoint_len); rc = zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, endpoint, &endpoint_len); assert (rc == 0); @@ -189,7 +189,7 @@ int main (void) assert (rc == 0); endpoint_len = sizeof (endpoint); - memset(endpoint, 0, endpoint_len); + memset (endpoint, 0, endpoint_len); rc = zmq_getsockopt (sb, ZMQ_LAST_ENDPOINT, endpoint, &endpoint_len); assert (rc == 0); diff --git a/tests/test_use_fd_ipc.cpp b/tests/test_use_fd_ipc.cpp index f1d8528a46..c0f1e1f16b 100644 --- a/tests/test_use_fd_ipc.cpp +++ b/tests/test_use_fd_ipc.cpp @@ -29,9 +29,9 @@ #include "testutil.hpp" -#if !defined (ZMQ_HAVE_WINDOWS) -# include -# include +#if !defined(ZMQ_HAVE_WINDOWS) +#include +#include void pre_allocate_sock (void *zmq_socket, const char *path) { @@ -44,16 +44,15 @@ void pre_allocate_sock (void *zmq_socket, const char *path) int s_pre = socket (AF_UNIX, SOCK_STREAM, 0); assert (s_pre != -1); - int rc = bind (s_pre, (struct sockaddr *) &addr, - sizeof (struct sockaddr_un)); + int rc = + bind (s_pre, (struct sockaddr *) &addr, sizeof (struct sockaddr_un)); assert (rc == 0); rc = listen (s_pre, SOMAXCONN); assert (rc == 0); - rc = zmq_setsockopt (zmq_socket, ZMQ_USE_FD, &s_pre, - sizeof (s_pre)); - assert(rc == 0); + rc = zmq_setsockopt (zmq_socket, ZMQ_USE_FD, &s_pre, sizeof (s_pre)); + assert (rc == 0); } void test_req_rep () @@ -64,7 +63,7 @@ void test_req_rep () void *sb = zmq_socket (ctx, ZMQ_REP); assert (sb); - pre_allocate_sock(sb, "/tmp/test_use_fd_ipc"); + pre_allocate_sock (sb, "/tmp/test_use_fd_ipc"); int rc = zmq_bind (sb, "ipc:///tmp/test_use_fd_ipc"); assert (rc == 0); @@ -97,7 +96,7 @@ void test_pair () void *sb = zmq_socket (ctx, ZMQ_PAIR); assert (sb); - pre_allocate_sock(sb, "/tmp/test_use_fd_ipc"); + pre_allocate_sock (sb, "/tmp/test_use_fd_ipc"); int rc = zmq_bind (sb, "ipc:///tmp/test_use_fd_ipc"); assert (rc == 0); @@ -131,7 +130,7 @@ void test_client_server () void *sb = zmq_socket (ctx, ZMQ_SERVER); assert (sb); - pre_allocate_sock(sb, "/tmp/test_use_fd_ipc"); + pre_allocate_sock (sb, "/tmp/test_use_fd_ipc"); int rc = zmq_bind (sb, "ipc:///tmp/test_use_fd_ipc"); assert (rc == 0); @@ -146,7 +145,7 @@ void test_client_server () assert (rc == 0); char *data = (char *) zmq_msg_data (&msg); - data [0] = 1; + data[0] = 1; rc = zmq_msg_send (&msg, sc, ZMQ_SNDMORE); assert (rc == -1); @@ -169,7 +168,7 @@ void test_client_server () rc = zmq_msg_init_size (&msg, 1); assert (rc == 0); - data = (char *)zmq_msg_data (&msg); + data = (char *) zmq_msg_data (&msg); data[0] = 2; rc = zmq_msg_set_routing_id (&msg, routing_id); @@ -206,18 +205,18 @@ void test_client_server () int main (void) { - setup_test_environment(); + setup_test_environment (); - test_req_rep(); - test_pair(); - test_client_server(); + test_req_rep (); + test_pair (); + test_client_server (); - return 0 ; + return 0; } #else int main (void) { - return 0 ; + return 0; } #endif diff --git a/tests/test_use_fd_tcp.cpp b/tests/test_use_fd_tcp.cpp index e4404f7f53..b9bee79152 100644 --- a/tests/test_use_fd_tcp.cpp +++ b/tests/test_use_fd_tcp.cpp @@ -29,21 +29,21 @@ #include "testutil.hpp" -#if !defined (ZMQ_HAVE_WINDOWS) +#if !defined(ZMQ_HAVE_WINDOWS) #include -uint16_t pre_allocate_sock (void *zmq_socket, const char *address, - const char *port) +uint16_t +pre_allocate_sock (void *zmq_socket, const char *address, const char *port) { struct addrinfo *addr, hint; - hint.ai_flags=0; - hint.ai_family=AF_INET; - hint.ai_socktype=SOCK_STREAM; - hint.ai_protocol=IPPROTO_TCP; - hint.ai_addrlen=0; - hint.ai_canonname=NULL; - hint.ai_addr=NULL; - hint.ai_next=NULL; + hint.ai_flags = 0; + hint.ai_family = AF_INET; + hint.ai_socktype = SOCK_STREAM; + hint.ai_protocol = IPPROTO_TCP; + hint.ai_addrlen = 0; + hint.ai_canonname = NULL; + hint.ai_addr = NULL; + hint.ai_next = NULL; int rc = getaddrinfo (address, port, &hint, &addr); assert (rc == 0); @@ -61,18 +61,17 @@ uint16_t pre_allocate_sock (void *zmq_socket, const char *address, rc = listen (s_pre, SOMAXCONN); assert (rc == 0); - rc = zmq_setsockopt (zmq_socket, ZMQ_USE_FD, &s_pre, - sizeof (s_pre)); - assert(rc == 0); + rc = zmq_setsockopt (zmq_socket, ZMQ_USE_FD, &s_pre, sizeof (s_pre)); + assert (rc == 0); struct sockaddr_in sin; - socklen_t len = sizeof(sin); - rc = getsockname(s_pre, (struct sockaddr *)&sin, &len); + socklen_t len = sizeof (sin); + rc = getsockname (s_pre, (struct sockaddr *) &sin, &len); assert (rc != -1); - freeaddrinfo(addr); + freeaddrinfo (addr); - return ntohs(sin.sin_port); + return ntohs (sin.sin_port); } void test_req_rep () @@ -84,7 +83,7 @@ void test_req_rep () void *sb = zmq_socket (ctx, ZMQ_REP); assert (sb); - uint16_t port = pre_allocate_sock(sb, "127.0.0.1", "0"); + uint16_t port = pre_allocate_sock (sb, "127.0.0.1", "0"); sprintf (my_endpoint, "tcp://127.0.0.1:%u", port); int rc = zmq_bind (sb, my_endpoint); @@ -116,7 +115,7 @@ void test_pair () void *sb = zmq_socket (ctx, ZMQ_PAIR); assert (sb); - uint16_t port = pre_allocate_sock(sb, "127.0.0.1", "0"); + uint16_t port = pre_allocate_sock (sb, "127.0.0.1", "0"); sprintf (my_endpoint, "tcp://127.0.0.1:%u", port); int rc = zmq_bind (sb, my_endpoint); @@ -149,7 +148,7 @@ void test_client_server () void *sb = zmq_socket (ctx, ZMQ_SERVER); assert (sb); - uint16_t port = pre_allocate_sock(sb, "127.0.0.1", "0"); + uint16_t port = pre_allocate_sock (sb, "127.0.0.1", "0"); sprintf (my_endpoint, "tcp://127.0.0.1:%u", port); int rc = zmq_bind (sb, my_endpoint); @@ -165,7 +164,7 @@ void test_client_server () assert (rc == 0); char *data = (char *) zmq_msg_data (&msg); - data [0] = 1; + data[0] = 1; rc = zmq_msg_send (&msg, sc, ZMQ_SNDMORE); assert (rc == -1); @@ -188,7 +187,7 @@ void test_client_server () rc = zmq_msg_init_size (&msg, 1); assert (rc == 0); - data = (char *)zmq_msg_data (&msg); + data = (char *) zmq_msg_data (&msg); data[0] = 2; rc = zmq_msg_set_routing_id (&msg, routing_id); @@ -222,17 +221,17 @@ void test_client_server () int main (void) { - setup_test_environment(); + setup_test_environment (); - test_req_rep(); - test_pair(); - test_client_server(); + test_req_rep (); + test_pair (); + test_client_server (); - return 0 ; + return 0; } #else int main (void) { - return 0 ; + return 0; } #endif diff --git a/tests/test_xpub_manual.cpp b/tests/test_xpub_manual.cpp index 5ec49edc91..432dc916bd 100644 --- a/tests/test_xpub_manual.cpp +++ b/tests/test_xpub_manual.cpp @@ -29,7 +29,7 @@ #include "testutil.hpp" -int test_basic() +int test_basic () { void *ctx = zmq_ctx_new (); assert (ctx); @@ -38,7 +38,7 @@ int test_basic() void *pub = zmq_socket (ctx, ZMQ_XPUB); assert (pub); int manual = 1; - int rc = zmq_setsockopt(pub, ZMQ_XPUB_MANUAL, &manual, 4); + int rc = zmq_setsockopt (pub, ZMQ_XPUB_MANUAL, &manual, 4); assert (rc == 0); rc = zmq_bind (pub, "inproc://soname"); assert (rc == 0); @@ -50,32 +50,32 @@ int test_basic() assert (rc == 0); // Subscribe for A - char subscription[2] = { 1, 'A'}; - rc = zmq_send_const(sub, subscription, 2, 0); + char subscription[2] = {1, 'A'}; + rc = zmq_send_const (sub, subscription, 2, 0); assert (rc == 2); char buffer[2]; // Receive subscriptions from subscriber - rc = zmq_recv(pub, buffer, 2, 0); - assert(rc == 2); - assert(buffer[0] == 1); - assert(buffer[1] == 'A'); + rc = zmq_recv (pub, buffer, 2, 0); + assert (rc == 2); + assert (buffer[0] == 1); + assert (buffer[1] == 'A'); // Subscribe socket for B instead - rc = zmq_setsockopt(pub, ZMQ_SUBSCRIBE, "B", 1); - assert(rc == 0); + rc = zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "B", 1); + assert (rc == 0); // Sending A message and B Message - rc = zmq_send_const(pub, "A", 1, 0); - assert(rc == 1); + rc = zmq_send_const (pub, "A", 1, 0); + assert (rc == 1); - rc = zmq_send_const(pub, "B", 1, 0); - assert(rc == 1); + rc = zmq_send_const (pub, "B", 1, 0); + assert (rc == 1); - rc = zmq_recv(sub, buffer, 1, ZMQ_DONTWAIT); - assert(rc == 1); - assert(buffer[0] == 'B'); + rc = zmq_recv (sub, buffer, 1, ZMQ_DONTWAIT); + assert (rc == 1); + assert (buffer[0] == 'B'); // Clean up. rc = zmq_close (pub); @@ -85,11 +85,11 @@ int test_basic() rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } -int test_unsubscribe_manual() +int test_unsubscribe_manual () { void *ctx = zmq_ctx_new (); assert (ctx); @@ -102,7 +102,7 @@ int test_unsubscribe_manual() // set pub socket options int manual = 1; - rc = zmq_setsockopt(pub, ZMQ_XPUB_MANUAL, &manual, 4); + rc = zmq_setsockopt (pub, ZMQ_XPUB_MANUAL, &manual, 4); assert (rc == 0); // Create a subscriber @@ -112,77 +112,77 @@ int test_unsubscribe_manual() assert (rc == 0); // Subscribe for A - char subscription1[2] = { 1, 'A'}; - rc = zmq_send_const(sub, subscription1, 2, 0); + char subscription1[2] = {1, 'A'}; + rc = zmq_send_const (sub, subscription1, 2, 0); assert (rc == 2); // Subscribe for B - char subscription2[2] = { 1, 'B'}; - rc = zmq_send_const(sub, subscription2, 2, 0); + char subscription2[2] = {1, 'B'}; + rc = zmq_send_const (sub, subscription2, 2, 0); assert (rc == 2); char buffer[3]; // Receive subscription "A" from subscriber - rc = zmq_recv(pub, buffer, 2, 0); - assert(rc == 2); - assert(buffer[0] == 1); - assert(buffer[1] == 'A'); + rc = zmq_recv (pub, buffer, 2, 0); + assert (rc == 2); + assert (buffer[0] == 1); + assert (buffer[1] == 'A'); // Subscribe socket for XA instead - rc = zmq_setsockopt(pub, ZMQ_SUBSCRIBE, "XA", 2); - assert(rc == 0); + rc = zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XA", 2); + assert (rc == 0); // Receive subscription "B" from subscriber - rc = zmq_recv(pub, buffer, 2, 0); - assert(rc == 2); - assert(buffer[0] == 1); - assert(buffer[1] == 'B'); + rc = zmq_recv (pub, buffer, 2, 0); + assert (rc == 2); + assert (buffer[0] == 1); + assert (buffer[1] == 'B'); // Subscribe socket for XB instead - rc = zmq_setsockopt(pub, ZMQ_SUBSCRIBE, "XB", 2); - assert(rc == 0); + rc = zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XB", 2); + assert (rc == 0); // Unsubscribe from A - char unsubscription1[2] = { 0, 'A'}; - rc = zmq_send_const(sub, unsubscription1, 2, 0); + char unsubscription1[2] = {0, 'A'}; + rc = zmq_send_const (sub, unsubscription1, 2, 0); assert (rc == 2); // Receive unsubscription "A" from subscriber - rc = zmq_recv(pub, buffer, 2, 0); - assert(rc == 2); - assert(buffer[0] == 0); - assert(buffer[1] == 'A'); + rc = zmq_recv (pub, buffer, 2, 0); + assert (rc == 2); + assert (buffer[0] == 0); + assert (buffer[1] == 'A'); // Unsubscribe socket from XA instead - rc = zmq_setsockopt(pub, ZMQ_UNSUBSCRIBE, "XA", 2); - assert(rc == 0); + rc = zmq_setsockopt (pub, ZMQ_UNSUBSCRIBE, "XA", 2); + assert (rc == 0); // Sending messages XA, XB - rc = zmq_send_const(pub, "XA", 2, 0); - assert(rc == 2); - rc = zmq_send_const(pub, "XB", 2, 0); - assert(rc == 2); + rc = zmq_send_const (pub, "XA", 2, 0); + assert (rc == 2); + rc = zmq_send_const (pub, "XB", 2, 0); + assert (rc == 2); // Subscriber should receive XB only - rc = zmq_recv(sub, buffer, 2, ZMQ_DONTWAIT); - assert(rc == 2); - assert(buffer[0] == 'X'); - assert(buffer[1] == 'B'); + rc = zmq_recv (sub, buffer, 2, ZMQ_DONTWAIT); + assert (rc == 2); + assert (buffer[0] == 'X'); + assert (buffer[1] == 'B'); // Close subscriber rc = zmq_close (sub); assert (rc == 0); // Receive unsubscription "B" - rc = zmq_recv(pub, buffer, 2, 0); - assert(rc == 2); - assert(buffer[0] == 0); - assert(buffer[1] == 'B'); + rc = zmq_recv (pub, buffer, 2, 0); + assert (rc == 2); + assert (buffer[0] == 0); + assert (buffer[1] == 'B'); // Unsubscribe socket from XB instead - rc = zmq_setsockopt(pub, ZMQ_UNSUBSCRIBE, "XB", 2); - assert(rc == 0); + rc = zmq_setsockopt (pub, ZMQ_UNSUBSCRIBE, "XB", 2); + assert (rc == 0); // Clean up. rc = zmq_close (pub); @@ -190,14 +190,14 @@ int test_unsubscribe_manual() rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } -int test_xpub_proxy_unsubscribe_on_disconnect(void) +int test_xpub_proxy_unsubscribe_on_disconnect (void) { - const char* topic = "1"; - const char* payload = "X"; + const char *topic = "1"; + const char *payload = "X"; size_t len = MAX_SOCKET_STRING; char my_endpoint_backend[MAX_SOCKET_STRING]; @@ -212,8 +212,8 @@ int test_xpub_proxy_unsubscribe_on_disconnect(void) void *xsub_proxy = zmq_socket (ctx, ZMQ_XSUB); assert (xsub_proxy); assert (zmq_bind (xsub_proxy, "tcp://127.0.0.1:*") == 0); - int rc = zmq_getsockopt (xsub_proxy, ZMQ_LAST_ENDPOINT, my_endpoint_frontend, - &len); + int rc = zmq_getsockopt (xsub_proxy, ZMQ_LAST_ENDPOINT, + my_endpoint_frontend, &len); assert (rc == 0); // proxy backend @@ -222,8 +222,8 @@ int test_xpub_proxy_unsubscribe_on_disconnect(void) assert (zmq_setsockopt (xpub_proxy, ZMQ_XPUB_MANUAL, &manual, 4) == 0); assert (zmq_bind (xpub_proxy, "tcp://127.0.0.1:*") == 0); len = MAX_SOCKET_STRING; - rc = zmq_getsockopt (xpub_proxy, ZMQ_LAST_ENDPOINT, my_endpoint_backend, - &len); + rc = + zmq_getsockopt (xpub_proxy, ZMQ_LAST_ENDPOINT, my_endpoint_backend, &len); assert (rc == 0); // publisher @@ -242,8 +242,8 @@ int test_xpub_proxy_unsubscribe_on_disconnect(void) // proxy reroutes and confirms subscriptions char sub_buff[2]; assert (zmq_recv (xpub_proxy, sub_buff, 2, ZMQ_DONTWAIT) == 2); - assert (sub_buff [0] == 1); - assert (sub_buff [1] == *topic); + assert (sub_buff[0] == 1); + assert (sub_buff[1] == *topic); assert (zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic, 1) == 0); assert (zmq_send (xsub_proxy, sub_buff, 2, 0) == 2); @@ -258,8 +258,8 @@ int test_xpub_proxy_unsubscribe_on_disconnect(void) // proxy reroutes assert (zmq_recv (xpub_proxy, sub_buff, 2, ZMQ_DONTWAIT) == 2); - assert (sub_buff [0] == 1); - assert (sub_buff [1] == *topic); + assert (sub_buff[0] == 1); + assert (sub_buff[1] == *topic); assert (zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic, 1) == 0); assert (zmq_send (xsub_proxy, sub_buff, 2, 0) == 2); @@ -277,9 +277,9 @@ int test_xpub_proxy_unsubscribe_on_disconnect(void) char topic_buff[1]; char data_buff[1]; assert (zmq_recv (xsub_proxy, topic_buff, 1, ZMQ_DONTWAIT) == 1); - assert (topic_buff [0] == *topic); + assert (topic_buff[0] == *topic); assert (zmq_recv (xsub_proxy, data_buff, 1, ZMQ_DONTWAIT) == 1); - assert (data_buff [0] == *payload); + assert (data_buff[0] == *payload); assert (zmq_send (xpub_proxy, topic_buff, 1, ZMQ_SNDMORE) == 1); assert (zmq_send (xpub_proxy, data_buff, 1, 0) == 1); @@ -288,14 +288,14 @@ int test_xpub_proxy_unsubscribe_on_disconnect(void) // each subscriber should now get a message assert (zmq_recv (sub2, topic_buff, 1, ZMQ_DONTWAIT) == 1); - assert (topic_buff [0] == *topic); + assert (topic_buff[0] == *topic); assert (zmq_recv (sub2, data_buff, 1, ZMQ_DONTWAIT) == 1); - assert (data_buff [0] == *payload); + assert (data_buff[0] == *payload); assert (zmq_recv (sub1, topic_buff, 1, ZMQ_DONTWAIT) == 1); - assert (topic_buff [0] == *topic); + assert (topic_buff[0] == *topic); assert (zmq_recv (sub1, data_buff, 1, ZMQ_DONTWAIT) == 1); - assert (data_buff [0] == *payload); + assert (data_buff[0] == *payload); // Disconnect both subscribers assert (zmq_close (sub1) == 0); @@ -306,16 +306,16 @@ int test_xpub_proxy_unsubscribe_on_disconnect(void) // unsubscribe messages are passed from proxy to publisher assert (zmq_recv (xpub_proxy, sub_buff, 2, 0) == 2); - assert (sub_buff [0] == 0); - assert (sub_buff [1] == *topic); + assert (sub_buff[0] == 0); + assert (sub_buff[1] == *topic); assert (zmq_setsockopt (xpub_proxy, ZMQ_UNSUBSCRIBE, topic, 1) == 0); assert (zmq_send (xsub_proxy, sub_buff, 2, 0) == 2); // should receive another unsubscribe msg assert (zmq_recv (xpub_proxy, sub_buff, 2, 0) == 2 - && "Should receive the second unsubscribe message."); - assert (sub_buff [0] == 0); - assert (sub_buff [1] == *topic); + && "Should receive the second unsubscribe message."); + assert (sub_buff[0] == 0); + assert (sub_buff[1] == *topic); assert (zmq_setsockopt (xpub_proxy, ZMQ_UNSUBSCRIBE, topic, 1) == 0); assert (zmq_send (xsub_proxy, sub_buff, 2, 0) == 2); @@ -326,7 +326,7 @@ int test_xpub_proxy_unsubscribe_on_disconnect(void) assert (zmq_send (pub, topic, 1, ZMQ_SNDMORE) == 1); assert (zmq_send (pub, payload, 1, 0) == 1); - // wait + // wait msleep (SETTLE_TIME); // nothing should come to the proxy @@ -341,11 +341,11 @@ int test_xpub_proxy_unsubscribe_on_disconnect(void) return 0; } -int test_missing_subscriptions(void) +int test_missing_subscriptions (void) { - const char* topic1 = "1"; - const char* topic2 = "2"; - const char* payload = "X"; + const char *topic1 = "1"; + const char *topic2 = "2"; + const char *payload = "X"; size_t len = MAX_SOCKET_STRING; char my_endpoint_backend[MAX_SOCKET_STRING]; @@ -360,8 +360,8 @@ int test_missing_subscriptions(void) void *xsub_proxy = zmq_socket (ctx, ZMQ_XSUB); assert (xsub_proxy); assert (zmq_bind (xsub_proxy, "tcp://127.0.0.1:*") == 0); - int rc = zmq_getsockopt (xsub_proxy, ZMQ_LAST_ENDPOINT, my_endpoint_frontend, - &len); + int rc = zmq_getsockopt (xsub_proxy, ZMQ_LAST_ENDPOINT, + my_endpoint_frontend, &len); assert (rc == 0); // proxy backend @@ -370,8 +370,8 @@ int test_missing_subscriptions(void) assert (zmq_setsockopt (xpub_proxy, ZMQ_XPUB_MANUAL, &manual, 4) == 0); assert (zmq_bind (xpub_proxy, "tcp://127.0.0.1:*") == 0); len = MAX_SOCKET_STRING; - rc = zmq_getsockopt (xpub_proxy, ZMQ_LAST_ENDPOINT, my_endpoint_backend, - &len); + rc = + zmq_getsockopt (xpub_proxy, ZMQ_LAST_ENDPOINT, my_endpoint_backend, &len); assert (rc == 0); // publisher @@ -400,14 +400,14 @@ int test_missing_subscriptions(void) // proxy now reroutes and confirms subscriptions char buffer[2]; assert (zmq_recv (xpub_proxy, buffer, 2, ZMQ_DONTWAIT) == 2); - assert (buffer [0] == 1); - assert (buffer [1] == *topic1); + assert (buffer[0] == 1); + assert (buffer[1] == *topic1); assert (zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic1, 1) == 0); assert (zmq_send (xsub_proxy, buffer, 2, 0) == 2); assert (zmq_recv (xpub_proxy, buffer, 2, ZMQ_DONTWAIT) == 2); - assert (buffer [0] == 1); - assert (buffer [1] == *topic2); + assert (buffer[0] == 1); + assert (buffer[1] == *topic2); assert (zmq_setsockopt (xpub_proxy, ZMQ_SUBSCRIBE, topic2, 1) == 0); assert (zmq_send (xsub_proxy, buffer, 2, 0) == 2); @@ -424,19 +424,19 @@ int test_missing_subscriptions(void) msleep (SETTLE_TIME); // proxy reroutes data messages to subscribers - char topic_buff [1]; - char data_buff [1]; + char topic_buff[1]; + char data_buff[1]; assert (zmq_recv (xsub_proxy, topic_buff, 1, ZMQ_DONTWAIT) == 1); - assert (topic_buff [0] == *topic1); + assert (topic_buff[0] == *topic1); assert (zmq_recv (xsub_proxy, data_buff, 1, ZMQ_DONTWAIT) == 1); - assert (data_buff [0] == *payload); + assert (data_buff[0] == *payload); assert (zmq_send (xpub_proxy, topic_buff, 1, ZMQ_SNDMORE) == 1); assert (zmq_send (xpub_proxy, data_buff, 1, 0) == 1); assert (zmq_recv (xsub_proxy, topic_buff, 1, ZMQ_DONTWAIT) == 1); - assert (topic_buff [0] == *topic2); + assert (topic_buff[0] == *topic2); assert (zmq_recv (xsub_proxy, data_buff, 1, ZMQ_DONTWAIT) == 1); - assert (data_buff [0] == *payload); + assert (data_buff[0] == *payload); assert (zmq_send (xpub_proxy, topic_buff, 1, ZMQ_SNDMORE) == 1); assert (zmq_send (xpub_proxy, data_buff, 1, 0) == 1); @@ -445,14 +445,14 @@ int test_missing_subscriptions(void) // each subscriber should now get a message assert (zmq_recv (sub2, topic_buff, 1, ZMQ_DONTWAIT) == 1); - assert (topic_buff [0] == *topic2); + assert (topic_buff[0] == *topic2); assert (zmq_recv (sub2, data_buff, 1, ZMQ_DONTWAIT) == 1); - assert (data_buff [0] == *payload); + assert (data_buff[0] == *payload); assert (zmq_recv (sub1, topic_buff, 1, ZMQ_DONTWAIT) == 1); - assert (topic_buff [0] == *topic1); + assert (topic_buff[0] == *topic1); assert (zmq_recv (sub1, data_buff, 1, ZMQ_DONTWAIT) == 1); - assert (data_buff [0] == *payload); + assert (data_buff[0] == *payload); // Clean up assert (zmq_close (sub1) == 0); @@ -492,14 +492,14 @@ int test_unsubscribe_cleanup (void) assert (rc == 0); // Subscribe for A - char subscription[2] = { 1, 'A'}; + char subscription[2] = {1, 'A'}; rc = zmq_send_const (sub, subscription, 2, 0); assert (rc == 2); char buffer[2]; // Receive subscriptions from subscriber - rc = zmq_recv(pub, buffer, 2, 0); + rc = zmq_recv (pub, buffer, 2, 0); assert (rc == 2); assert (buffer[0] == 1); assert (buffer[1] == 'A'); @@ -552,7 +552,7 @@ int test_unsubscribe_cleanup (void) rc = zmq_recv (pub, buffer, 2, 0); assert (rc == 2); assert (buffer[0] == 1); - assert(buffer[1] == 'B'); + assert (buffer[1] == 'B'); rc = zmq_setsockopt (pub, ZMQ_SUBSCRIBE, "XB", 2); assert (rc == 0); @@ -566,7 +566,7 @@ int test_unsubscribe_cleanup (void) rc = zmq_recv (sub, buffer, 2, 0); assert (rc == 2); assert (buffer[0] == 'X'); - assert (buffer[1] == 'B'); // this assertion will fail + assert (buffer[1] == 'B'); // this assertion will fail // should be nothing left in the queue rc = zmq_recv (sub, buffer, 2, ZMQ_DONTWAIT); @@ -580,11 +580,11 @@ int test_unsubscribe_cleanup (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } -int main(void) +int main (void) { setup_test_environment (); test_basic (); diff --git a/tests/test_xpub_nodrop.cpp b/tests/test_xpub_nodrop.cpp index 806824bb43..c56c620a50 100644 --- a/tests/test_xpub_nodrop.cpp +++ b/tests/test_xpub_nodrop.cpp @@ -31,7 +31,7 @@ int main (void) { - setup_test_environment(); + setup_test_environment (); void *ctx = zmq_ctx_new (); assert (ctx); @@ -40,8 +40,8 @@ int main (void) assert (pub); int hwm = 2000; - int rc = zmq_setsockopt(pub, ZMQ_SNDHWM, &hwm, 4); - assert(rc == 0); + int rc = zmq_setsockopt (pub, ZMQ_SNDHWM, &hwm, 4); + assert (rc == 0); rc = zmq_bind (pub, "inproc://soname"); assert (rc == 0); @@ -64,7 +64,7 @@ int main (void) int hwmlimit = hwm - 1; int send_count = 0; - + // Send an empty message for (int i = 0; i < hwmlimit; i++) { rc = zmq_send (pub, NULL, 0, 0); @@ -82,11 +82,10 @@ int main (void) assert (rc == 0); recv_count++; } - } - while (rc == 0); + } while (rc == 0); assert (send_count == recv_count); - + // Now test real blocking behavior // Set a timeout, default is infinite int timeout = 0; @@ -96,7 +95,7 @@ int main (void) send_count = 0; recv_count = 0; hwmlimit = hwm; - + // Send an empty message until we get an error, which must be EAGAIN while (zmq_send (pub, "", 0, 0) == 0) send_count++; @@ -114,5 +113,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_xpub_welcome_msg.cpp b/tests/test_xpub_welcome_msg.cpp index 01b6dda19d..819f6e3ba2 100644 --- a/tests/test_xpub_welcome_msg.cpp +++ b/tests/test_xpub_welcome_msg.cpp @@ -59,15 +59,15 @@ int main (void) char buffer[2]; // Receive the welcome subscription - rc = zmq_recv(pub, buffer, 2, 0); + rc = zmq_recv (pub, buffer, 2, 0); assert (rc == 2); - assert (buffer [0] == 1); - assert (buffer [1] == 'W'); + assert (buffer[0] == 1); + assert (buffer[1] == 'W'); // Receive the welcome message rc = zmq_recv (sub, buffer, 1, 0); assert (rc == 1); - assert (buffer [0] == 'W'); + assert (buffer[0] == 'W'); // Clean up. rc = zmq_close (pub); @@ -77,5 +77,5 @@ int main (void) rc = zmq_ctx_term (ctx); assert (rc == 0); - return 0 ; + return 0; } diff --git a/tests/test_zmq_poll_fd.cpp b/tests/test_zmq_poll_fd.cpp index 48c47d2a6e..ad46fffcf7 100644 --- a/tests/test_zmq_poll_fd.cpp +++ b/tests/test_zmq_poll_fd.cpp @@ -34,14 +34,14 @@ int main (void) { struct addrinfo *addr, hint; - hint.ai_flags=AI_NUMERICHOST; - hint.ai_family=AF_INET; - hint.ai_socktype=SOCK_DGRAM; - hint.ai_protocol=IPPROTO_UDP; - hint.ai_addrlen=0; - hint.ai_canonname=NULL; - hint.ai_addr=NULL; - hint.ai_next=NULL; + hint.ai_flags = AI_NUMERICHOST; + hint.ai_family = AF_INET; + hint.ai_socktype = SOCK_DGRAM; + hint.ai_protocol = IPPROTO_UDP; + hint.ai_addrlen = 0; + hint.ai_canonname = NULL; + hint.ai_addr = NULL; + hint.ai_next = NULL; int rc = getaddrinfo ("127.0.0.1", "6650", &hint, &addr); assert (rc == 0); @@ -50,7 +50,8 @@ int main (void) assert (recv_socket != -1); int flag = 1; - rc = setsockopt (recv_socket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int)); + rc = + setsockopt (recv_socket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int)); assert (rc == 0); rc = bind (recv_socket, addr->ai_addr, addr->ai_addrlen); @@ -65,9 +66,9 @@ int main (void) rc = zmq_bind (sb, "tcp://127.0.0.1:*"); assert (rc == 0); - zmq_pollitem_t pollitems [] = { - { sb, 0, ZMQ_POLLIN, 0 }, - { NULL, recv_socket, ZMQ_POLLIN, 0 }, + zmq_pollitem_t pollitems[] = { + {sb, 0, ZMQ_POLLIN, 0}, + {NULL, recv_socket, ZMQ_POLLIN, 0}, }; int send_socket = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); @@ -80,8 +81,8 @@ int main (void) assert (rc >= 0); assert (zmq_poll (pollitems, 2, 1) == 1); - assert ((pollitems [0].revents & ZMQ_POLLIN) == 0); - assert (pollitems [1].revents & ZMQ_POLLIN); + assert ((pollitems[0].revents & ZMQ_POLLIN) == 0); + assert (pollitems[1].revents & ZMQ_POLLIN); rc = zmq_close (sb); assert (rc == 0); @@ -92,7 +93,7 @@ int main (void) close (send_socket); close (recv_socket); - freeaddrinfo(addr); + freeaddrinfo (addr); - return 0 ; + return 0; } diff --git a/tests/testutil.hpp b/tests/testutil.hpp index cd7928ce29..296a6cd8c6 100644 --- a/tests/testutil.hpp +++ b/tests/testutil.hpp @@ -31,9 +31,9 @@ #define __TESTUTIL_HPP_INCLUDED__ #if defined ZMQ_CUSTOM_PLATFORM_HPP -# include "platform.hpp" +#include "platform.hpp" #else -# include "../src/platform.hpp" +#include "../src/platform.hpp" #endif #include "../include/zmq.h" #include "../src/stdint.hpp" @@ -41,9 +41,9 @@ // This defines the settle time used in tests; raise this if we // get test failures on slower systems due to binds/connects not // settled. Tested to work reliably at 1 msec on a fast PC. -#define SETTLE_TIME 300 // In msec +#define SETTLE_TIME 300 // In msec // Commonly used buffer size for ZMQ_LAST_ENDPOINT -#define MAX_SOCKET_STRING sizeof("tcp://127.0.0.1:65536") +#define MAX_SOCKET_STRING sizeof ("tcp://127.0.0.1:65536") // We need to test codepaths with non-random bind ports. List them here to // keep them unique, to allow parallel test runs. @@ -62,36 +62,35 @@ #include #if defined _WIN32 -# include "../src/windows.hpp" -# if defined _MSC_VER -# include -# pragma warning(disable:4996) +#include "../src/windows.hpp" +#if defined _MSC_VER +#include +#pragma warning(disable : 4996) // iphlpapi is needed for if_nametoindex (not on Windows XP) -# if !defined ZMQ_HAVE_WINDOWS_TARGET_XP -# pragma comment(lib,"iphlpapi") -# endif -# endif +#if !defined ZMQ_HAVE_WINDOWS_TARGET_XP +#pragma comment(lib, "iphlpapi") +#endif +#endif #else -# include -# include -# include -# include -# include -# include -# include -# include -# if defined (ZMQ_HAVE_AIX) -# include -# include -# endif +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(ZMQ_HAVE_AIX) +#include +#include +#endif #endif -#define LIBZMQ_UNUSED(object) (void)object +#define LIBZMQ_UNUSED(object) (void) object // Bounce a message from client to server and back // For REQ/REP or DEALER/DEALER pairs only -void -bounce (void *server, void *client) +void bounce (void *server, void *client) { const char *content = "12345678ABCDEFGH12345678abcdefgh"; @@ -102,7 +101,7 @@ bounce (void *server, void *client) assert (rc == 32); // Receive message at server side - char buffer [32]; + char buffer[32]; rc = zmq_recv (server, buffer, 32, 0); assert (rc == 32); // Check that message is still the same @@ -145,11 +144,10 @@ bounce (void *server, void *client) // Same as bounce, but expect messages to never arrive // for security or subscriber reasons. -void -expect_bounce_fail (void *server, void *client) +void expect_bounce_fail (void *server, void *client) { const char *content = "12345678ABCDEFGH12345678abcdefgh"; - char buffer [32]; + char buffer[32]; int timeout = 250; // Send message from client to server @@ -187,34 +185,34 @@ expect_bounce_fail (void *server, void *client) // Receive 0MQ string from socket and convert into C string // Caller must free returned string. Returns NULL if the context // is being terminated. -char * -s_recv (void *socket) { - char buffer [256]; +char *s_recv (void *socket) +{ + char buffer[256]; int size = zmq_recv (socket, buffer, 255, 0); if (size == -1) return NULL; if (size > 255) size = 255; - buffer [size] = 0; + buffer[size] = 0; return strdup (buffer); } // Convert C string to 0MQ string and send to socket -int -s_send (void *socket, const char *string) { +int s_send (void *socket, const char *string) +{ int size = zmq_send (socket, string, strlen (string), 0); return size; } // Sends string as 0MQ string, as multipart non-terminal -int -s_sendmore (void *socket, const char *string) { +int s_sendmore (void *socket, const char *string) +{ int size = zmq_send (socket, string, strlen (string), ZMQ_SNDMORE); return size; } -#define streq(s1,s2) (!strcmp ((s1), (s2))) -#define strneq(s1,s2) (strcmp ((s1), (s2))) +#define streq(s1, s2) (!strcmp ((s1), (s2))) +#define strneq(s1, s2) (strcmp ((s1), (s2))) const char *SEQ_END = (const char *) 1; @@ -222,24 +220,22 @@ const char *SEQ_END = (const char *) 1; // The list must be terminated by SEQ_END. // Example: s_send_seq (req, "ABC", 0, "DEF", SEQ_END); -void -s_send_seq (void *socket, ...) +void s_send_seq (void *socket, ...) { va_list ap; va_start (ap, socket); - const char * data = va_arg (ap, const char *); - while (true) - { - const char * prev = data; + const char *data = va_arg (ap, const char *); + while (true) { + const char *prev = data; data = va_arg (ap, const char *); bool end = data == SEQ_END; if (!prev) { int rc = zmq_send (socket, 0, 0, end ? 0 : ZMQ_SNDMORE); assert (rc != -1); - } - else { - int rc = zmq_send (socket, prev, strlen (prev)+1, end ? 0 : ZMQ_SNDMORE); + } else { + int rc = + zmq_send (socket, prev, strlen (prev) + 1, end ? 0 : ZMQ_SNDMORE); assert (rc != -1); } if (end) @@ -253,18 +249,17 @@ s_send_seq (void *socket, ...) // The list must be terminated by SEQ_END. // Example: s_recv_seq (rep, "ABC", 0, "DEF", SEQ_END); -void -s_recv_seq (void *socket, ...) +void s_recv_seq (void *socket, ...) { zmq_msg_t msg; zmq_msg_init (&msg); int more; - size_t more_size = sizeof(more); + size_t more_size = sizeof (more); va_list ap; va_start (ap, socket); - const char * data = va_arg (ap, const char *); + const char *data = va_arg (ap, const char *); while (true) { int rc = zmq_msg_recv (&msg, socket, 0); @@ -273,7 +268,7 @@ s_recv_seq (void *socket, ...) if (!data) assert (zmq_msg_size (&msg) == 0); else - assert (strcmp (data, (const char *)zmq_msg_data (&msg)) == 0); + assert (strcmp (data, (const char *) zmq_msg_data (&msg)) == 0); data = va_arg (ap, const char *); bool end = data == SEQ_END; @@ -292,40 +287,38 @@ s_recv_seq (void *socket, ...) // Sets a zero linger period on a socket and closes it. -void -close_zero_linger (void *socket) +void close_zero_linger (void *socket) { int linger = 0; - int rc = zmq_setsockopt (socket, ZMQ_LINGER, &linger, sizeof(linger)); + int rc = zmq_setsockopt (socket, ZMQ_LINGER, &linger, sizeof (linger)); assert (rc == 0 || errno == ETERM); rc = zmq_close (socket); assert (rc == 0); } -void -setup_test_environment (void) +void setup_test_environment (void) { #if defined _WIN32 -# if defined _MSC_VER - _set_abort_behavior( 0, _WRITE_ABORT_MSG); - _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE ); - _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR ); -# endif +#if defined _MSC_VER + _set_abort_behavior (0, _WRITE_ABORT_MSG); + _CrtSetReportMode (_CRT_ASSERT, _CRTDBG_MODE_FILE); + _CrtSetReportFile (_CRT_ASSERT, _CRTDBG_FILE_STDERR); +#endif #else #if defined ZMQ_HAVE_CYGWIN // abort test after 121 seconds - alarm(121); + alarm (121); #else -# if !defined ZMQ_DISABLE_TEST_TIMEOUT +#if !defined ZMQ_DISABLE_TEST_TIMEOUT // abort test after 60 seconds - alarm(60); -# endif + alarm (60); +#endif #endif #endif #if defined __MVS__ // z/OS UNIX System Services: Ignore SIGPIPE during test runs, as a // workaround for no SO_NOGSIGPIPE socket option. - signal(SIGPIPE, SIG_IGN); + signal (SIGPIPE, SIG_IGN); #endif } @@ -333,22 +326,20 @@ setup_test_environment (void) // http://www.cplusplus.com/forum/unices/60161/ // http://en.cppreference.com/w/cpp/thread/sleep_for -void -msleep (int milliseconds) +void msleep (int milliseconds) { #ifdef ZMQ_HAVE_WINDOWS Sleep (milliseconds); #else - usleep (static_cast (milliseconds) * 1000); + usleep (static_cast (milliseconds) * 1000); #endif } // check if IPv6 is available (0/false if not, 1/true if it is) // only way to reliably check is to actually open a socket and try to bind it -int -is_ipv6_available(void) +int is_ipv6_available (void) { -#if defined (ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) +#if defined(ZMQ_HAVE_WINDOWS) && (_WIN32_WINNT < 0x0600) return 0; #else int rc, ipv6 = 1; @@ -363,12 +354,14 @@ is_ipv6_available(void) if (fd == INVALID_SOCKET) ipv6 = 0; else { - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&ipv6, sizeof(int)); - rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&ipv6, sizeof(int)); + setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (const char *) &ipv6, + sizeof (int)); + rc = setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, (const char *) &ipv6, + sizeof (int)); if (rc == SOCKET_ERROR) ipv6 = 0; else { - rc = bind (fd, (struct sockaddr *)&test_addr, sizeof (test_addr)); + rc = bind (fd, (struct sockaddr *) &test_addr, sizeof (test_addr)); if (rc == SOCKET_ERROR) ipv6 = 0; } @@ -379,12 +372,12 @@ is_ipv6_available(void) if (fd == -1) ipv6 = 0; else { - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &ipv6, sizeof(int)); - rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6, sizeof(int)); + setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &ipv6, sizeof (int)); + rc = setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6, sizeof (int)); if (rc != 0) ipv6 = 0; else { - rc = bind (fd, (struct sockaddr *)&test_addr, sizeof (test_addr)); + rc = bind (fd, (struct sockaddr *) &test_addr, sizeof (test_addr)); if (rc != 0) ipv6 = 0; } @@ -396,7 +389,7 @@ is_ipv6_available(void) #endif // _WIN32_WINNT < 0x0600 } -#if defined (ZMQ_HAVE_WINDOWS) +#if defined(ZMQ_HAVE_WINDOWS) int close (int fd) { diff --git a/tests/testutil_security.hpp b/tests/testutil_security.hpp index 1fa2da9ad2..95e63bf619 100644 --- a/tests/testutil_security.hpp +++ b/tests/testutil_security.hpp @@ -117,8 +117,8 @@ void socket_config_curve_server (void *server, void *server_secret) #ifdef ZMQ_ZAP_ENFORCE_DOMAIN int required = 1; - rc = zmq_setsockopt (server, ZMQ_ZAP_ENFORCE_DOMAIN, &required, - sizeof (int)); + rc = + zmq_setsockopt (server, ZMQ_ZAP_ENFORCE_DOMAIN, &required, sizeof (int)); assert (rc == 0); #endif } @@ -519,7 +519,7 @@ void setup_handshake_socket_monitor (void *ctx, *server_mon = zmq_socket (ctx, ZMQ_PAIR); assert (*server_mon); int linger = 0; - rc = zmq_setsockopt (*server_mon, ZMQ_LINGER, &linger, sizeof(linger)); + rc = zmq_setsockopt (*server_mon, ZMQ_LINGER, &linger, sizeof (linger)); assert (rc == 0); // Connect it to the inproc endpoints so they'll get events @@ -552,7 +552,7 @@ void setup_context_and_server_side ( int rc = zmq_bind (*zap_control, "inproc://handler-control"); assert (rc == 0); int linger = 0; - rc = zmq_setsockopt (*zap_control, ZMQ_LINGER, &linger, sizeof(linger)); + rc = zmq_setsockopt (*zap_control, ZMQ_LINGER, &linger, sizeof (linger)); assert (rc == 0); if (zap_handler_) { @@ -568,7 +568,7 @@ void setup_context_and_server_side ( // Server socket will accept connections *server = zmq_socket (*ctx, ZMQ_DEALER); assert (*server); - rc = zmq_setsockopt (*server, ZMQ_LINGER, &linger, sizeof(linger)); + rc = zmq_setsockopt (*server, ZMQ_LINGER, &linger, sizeof (linger)); assert (rc == 0); socket_config_ (*server, socket_config_data_); diff --git a/tools/curve_keygen.cpp b/tools/curve_keygen.cpp index 2bbb8ca15c..ff495c4b22 100644 --- a/tools/curve_keygen.cpp +++ b/tools/curve_keygen.cpp @@ -33,19 +33,25 @@ int main (void) { - puts ("This tool generates a CurveZMQ keypair, as two printable strings you can"); - puts ("use in configuration files or source code. The encoding uses Z85, which"); - puts ("is a base-85 format that is described in 0MQ RFC 32, and which has an"); - puts ("implementation in the z85_codec.h source used by this tool. The keypair"); - puts ("always works with the secret key held by one party and the public key"); + puts ("This tool generates a CurveZMQ keypair, as two printable strings " + "you can"); + puts ("use in configuration files or source code. The encoding uses Z85, " + "which"); + puts ( + "is a base-85 format that is described in 0MQ RFC 32, and which has an"); + puts ("implementation in the z85_codec.h source used by this tool. The " + "keypair"); + puts ( + "always works with the secret key held by one party and the public key"); puts ("distributed (securely!) to peers wishing to connect to it."); - char public_key [41]; - char secret_key [41]; + char public_key[41]; + char secret_key[41]; if (zmq_curve_keypair (public_key, secret_key)) { - if (zmq_errno () == ENOTSUP) - puts ("To use curve_keygen, please install libsodium and then rebuild libzmq."); - exit (1); + if (zmq_errno () == ENOTSUP) + puts ("To use curve_keygen, please install libsodium and then " + "rebuild libzmq."); + exit (1); } puts ("\n== CURVE PUBLIC KEY =="); From 4161793d1907ce7402b42f9c96e6f9745b0e2a3a Mon Sep 17 00:00:00 2001 From: sigiesec Date: Thu, 1 Feb 2018 14:18:02 +0100 Subject: [PATCH 3/7] Problem: clang-format not run on CI Solution: add clang-format to cmake, and add another travis-ci build type --- .travis.yml | 2 ++ CMakeLists.txt | 2 ++ builds/cmake/Modules/ClangFormat.cmake | 36 ++++++++++++++++++++++++++ builds/cmake/ci_build.sh | 9 ++++++- builds/cmake/clang-format-check.sh.in | 14 ++++++++++ 5 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 builds/cmake/Modules/ClangFormat.cmake create mode 100644 builds/cmake/clang-format-check.sh.in diff --git a/.travis.yml b/.travis.yml index 3d2eda2918..9dc9ab88d1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -84,6 +84,8 @@ matrix: - env: BUILD_TYPE=android CURVE=tweetnacl os: linux dist: trusty + - env: BUILD_TYPE=cmake DO_CLANG_FORMAT_CHECK=1 + os: linux sudo: required diff --git a/CMakeLists.txt b/CMakeLists.txt index bbc451e880..15f99dfc73 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1138,3 +1138,5 @@ if (MSVC_VERSION EQUAL 1600) file (APPEND "${ZMQ_SLN_FILENAME}" "\n# This should be regenerated!\n") endif () endif () + +include(ClangFormat) diff --git a/builds/cmake/Modules/ClangFormat.cmake b/builds/cmake/Modules/ClangFormat.cmake new file mode 100644 index 0000000000..983c53e2f9 --- /dev/null +++ b/builds/cmake/Modules/ClangFormat.cmake @@ -0,0 +1,36 @@ +# additional target to perform clang-format run, requires clang-format + +# get all project files +file(GLOB_RECURSE ALL_SOURCE_FILES RELATIVE ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}/*.cpp ${CMAKE_SOURCE_DIR}/*.h ${CMAKE_SOURCE_DIR}/*.hpp ) + +if("${CLANG_FORMAT}" STREQUAL "") + set(CLANG_FORMAT "clang-format") +endif() + +add_custom_target( + clang-format + COMMAND ${CLANG_FORMAT} -style=file -i ${ALL_SOURCE_FILES} +) + +function(JOIN VALUES GLUE OUTPUT) + string (REPLACE ";" "${GLUE}" _TMP_STR "${VALUES}") + set (${OUTPUT} "${_TMP_STR}" PARENT_SCOPE) +endfunction() + +configure_file(builds/cmake/clang-format-check.sh.in clang-format-check.sh @ONLY) + +add_custom_target( + clang-format-check + COMMAND chmod +x clang-format-check.sh + COMMAND ./clang-format-check.sh + #COMMAND ${CLANG_FORMAT} -style=file -output-replacements-xml ${ALL_SOURCE_FILES} >clang-format-replacements.xml + #COMMAND grep \"/dev/null && exit 1 + COMMENT "Checking correct formatting according to .clang-format file" +) + +add_custom_target( + clang-format-diff + COMMAND ${CLANG_FORMAT} -style=file -i ${ALL_SOURCE_FILES} + COMMAND git diff ${ALL_SOURCE_FILES} + COMMENT "Formatting with clang-format and showing differences with latest commit" +) diff --git a/builds/cmake/ci_build.sh b/builds/cmake/ci_build.sh index 97eed51d44..2786317c96 100755 --- a/builds/cmake/ci_build.sh +++ b/builds/cmake/ci_build.sh @@ -31,4 +31,11 @@ elif [ $CURVE == "libsodium" ]; then fi # Build, check, and install from local source -( cd ../..; mkdir build_cmake && cd build_cmake && PKG_CONFIG_PATH=${BUILD_PREFIX}/lib/pkgconfig cmake "${CMAKE_OPTS[@]}" .. && make -j5 all VERBOSE=1 && make install && make -j5 test ) || exit 1 +if [ "$DO_CLANG_FORMAT_CHECK" -eq "1" ] ; then + if ! (cd ../..; mkdir build_cmake && cd build_cmake && PKG_CONFIG_PATH=${BUILD_PREFIX}/lib/pkgconfig cmake "${CMAKE_OPTS[@]}" .. && make clang-format-check) ; then + make clang-format-diff + exit 1 + fi +else + ( cd ../..; mkdir build_cmake && cd build_cmake && PKG_CONFIG_PATH=${BUILD_PREFIX}/lib/pkgconfig cmake "${CMAKE_OPTS[@]}" .. && make -j5 all VERBOSE=1 && make install && make -j5 test ) || exit 1 +fi diff --git a/builds/cmake/clang-format-check.sh.in b/builds/cmake/clang-format-check.sh.in new file mode 100644 index 0000000000..7ff40196ca --- /dev/null +++ b/builds/cmake/clang-format-check.sh.in @@ -0,0 +1,14 @@ +#!/bin/sh +FAILED=0 +IFS=";" +FILES="@ALL_SOURCE_FILES@" +IDS=$(echo -en "\n\b") +for FILE in $FILES +do + @CLANG_FORMAT@ -style=file -output-replacements-xml "$FILE" | grep "/dev/null && + { + echo "$FILE is not correctly formatted" + FAILED=1 + } +done +if [ "$FAILED" -eq "1" ] ; then exit 1 ; fi From 26b5b5b2d9ad22249170bfa14be3885659250d7b Mon Sep 17 00:00:00 2001 From: sigiesec Date: Thu, 1 Feb 2018 15:15:32 +0100 Subject: [PATCH 4/7] Problem: out-of-scope files are considered by cmake clang-format targets Solution: restrict to src, tests, perf, tools and include directories --- builds/cmake/Modules/ClangFormat.cmake | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/builds/cmake/Modules/ClangFormat.cmake b/builds/cmake/Modules/ClangFormat.cmake index 983c53e2f9..b31d97701f 100644 --- a/builds/cmake/Modules/ClangFormat.cmake +++ b/builds/cmake/Modules/ClangFormat.cmake @@ -1,7 +1,14 @@ # additional target to perform clang-format run, requires clang-format # get all project files -file(GLOB_RECURSE ALL_SOURCE_FILES RELATIVE ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}/*.cpp ${CMAKE_SOURCE_DIR}/*.h ${CMAKE_SOURCE_DIR}/*.hpp ) +file(GLOB_RECURSE ALL_SOURCE_FILES + RELATIVE ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_SOURCE_DIR}/src/*.cpp ${CMAKE_SOURCE_DIR}/src/*.h ${CMAKE_SOURCE_DIR}/src/*.hpp + ${CMAKE_SOURCE_DIR}/tests/*.cpp ${CMAKE_SOURCE_DIR}/tests/*.h ${CMAKE_SOURCE_DIR}/tests/*.hpp + ${CMAKE_SOURCE_DIR}/perf/*.cpp ${CMAKE_SOURCE_DIR}/perf/*.h ${CMAKE_SOURCE_DIR}/perf/*.hpp + ${CMAKE_SOURCE_DIR}/tools/*.cpp ${CMAKE_SOURCE_DIR}/tools/*.h ${CMAKE_SOURCE_DIR}/tools/*.hpp + ${CMAKE_SOURCE_DIR}/include/*.h + ) if("${CLANG_FORMAT}" STREQUAL "") set(CLANG_FORMAT "clang-format") From 749a85cb2198fc73ce57b2bc6a4f83602a75bfdb Mon Sep 17 00:00:00 2001 From: sigiesec Date: Thu, 1 Feb 2018 16:11:10 +0100 Subject: [PATCH 5/7] Problem: travis-ci is using outdated clang(-format) Solution: explicitly select clang-5.0 --- .travis.yml | 8 +++++++- builds/cmake/Modules/ClangFormat.cmake | 6 ++---- builds/cmake/ci_build.sh | 4 ++++ 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9dc9ab88d1..feb4ed3c5f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -84,8 +84,14 @@ matrix: - env: BUILD_TYPE=android CURVE=tweetnacl os: linux dist: trusty - - env: BUILD_TYPE=cmake DO_CLANG_FORMAT_CHECK=1 + - env: BUILD_TYPE=cmake DO_CLANG_FORMAT_CHECK=1 CLANG_FORMAT=/usr/local/clang-5.0.0/bin/clang-format os: linux + addons: + apt: + sources: + - llvm-toolchain-trusty-5.0 + packages: + - clang-5.0 sudo: required diff --git a/builds/cmake/Modules/ClangFormat.cmake b/builds/cmake/Modules/ClangFormat.cmake index b31d97701f..f36ea06922 100644 --- a/builds/cmake/Modules/ClangFormat.cmake +++ b/builds/cmake/Modules/ClangFormat.cmake @@ -30,14 +30,12 @@ add_custom_target( clang-format-check COMMAND chmod +x clang-format-check.sh COMMAND ./clang-format-check.sh - #COMMAND ${CLANG_FORMAT} -style=file -output-replacements-xml ${ALL_SOURCE_FILES} >clang-format-replacements.xml - #COMMAND grep \"/dev/null && exit 1 - COMMENT "Checking correct formatting according to .clang-format file" + COMMENT "Checking correct formatting according to .clang-format file using ${CLANG_FORMAT}" ) add_custom_target( clang-format-diff COMMAND ${CLANG_FORMAT} -style=file -i ${ALL_SOURCE_FILES} COMMAND git diff ${ALL_SOURCE_FILES} - COMMENT "Formatting with clang-format and showing differences with latest commit" + COMMENT "Formatting with clang-format (using ${CLANG_FORMAT}) and showing differences with latest commit" ) diff --git a/builds/cmake/ci_build.sh b/builds/cmake/ci_build.sh index 2786317c96..e838d5091a 100755 --- a/builds/cmake/ci_build.sh +++ b/builds/cmake/ci_build.sh @@ -18,6 +18,10 @@ CMAKE_OPTS+=("-DCMAKE_PREFIX_PATH:PATH=${BUILD_PREFIX}") CMAKE_OPTS+=("-DCMAKE_LIBRARY_PATH:PATH=${BUILD_PREFIX}/lib") CMAKE_OPTS+=("-DCMAKE_INCLUDE_PATH:PATH=${BUILD_PREFIX}/include") +if [ "$CLANG_FORMAT" != "" ] ; then + CMAKE_OPTS+=("-DCLANG_FORMAT=${CLANG_FORMAT}") +fi + if [ -z $CURVE ]; then CMAKE_OPTS+=("-DENABLE_CURVE=OFF") elif [ $CURVE == "libsodium" ]; then From ac775ba48b0fb92d9db38ac6f5b85ca18bed3089 Mon Sep 17 00:00:00 2001 From: sigiesec Date: Fri, 2 Feb 2018 12:02:27 +0100 Subject: [PATCH 6/7] Problem: clang-format-diff does not run Solution: fix execution directory --- builds/cmake/ci_build.sh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/builds/cmake/ci_build.sh b/builds/cmake/ci_build.sh index e838d5091a..736c461df1 100755 --- a/builds/cmake/ci_build.sh +++ b/builds/cmake/ci_build.sh @@ -35,11 +35,14 @@ elif [ $CURVE == "libsodium" ]; then fi # Build, check, and install from local source +cd ../.. +mkdir build_cmake +cd build_cmake if [ "$DO_CLANG_FORMAT_CHECK" -eq "1" ] ; then - if ! (cd ../..; mkdir build_cmake && cd build_cmake && PKG_CONFIG_PATH=${BUILD_PREFIX}/lib/pkgconfig cmake "${CMAKE_OPTS[@]}" .. && make clang-format-check) ; then + if ! ( PKG_CONFIG_PATH=${BUILD_PREFIX}/lib/pkgconfig cmake "${CMAKE_OPTS[@]}" .. && make clang-format-check) ; then make clang-format-diff exit 1 fi else - ( cd ../..; mkdir build_cmake && cd build_cmake && PKG_CONFIG_PATH=${BUILD_PREFIX}/lib/pkgconfig cmake "${CMAKE_OPTS[@]}" .. && make -j5 all VERBOSE=1 && make install && make -j5 test ) || exit 1 + ( PKG_CONFIG_PATH=${BUILD_PREFIX}/lib/pkgconfig cmake "${CMAKE_OPTS[@]}" .. && make -j5 all VERBOSE=1 && make install && make -j5 test ) || exit 1 fi From 43c11d0a61143b793ca00455c97e3220f7e0c75b Mon Sep 17 00:00:00 2001 From: sigiesec Date: Fri, 2 Feb 2018 13:52:51 +0100 Subject: [PATCH 7/7] Problem: cmake broken under Windows Solution: fix CMAKE_MODULES_PATH --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 15f99dfc73..df1c857ac4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1070,7 +1070,7 @@ if (MSVC AND ENABLE_CPACK) # add_crt_version (v100) # add_crt_version (v90) - set (CMAKE_MODULE_PATH "${CMAKE_CURRENT_BINARY_DIR}") + list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_BINARY_DIR}) set (CPACK_GENERATOR "NSIS") set (CPACK_PACKAGE_NAME "ZeroMQ") set (CPACK_PACKAGE_DESCRIPTION_SUMMARY "ZeroMQ lightweight messaging kernel")