Problem: formatting inconsistent

Solution: applied clang-format
This commit is contained in:
sigiesec
2018-02-01 11:46:09 +01:00
parent 6d8baea714
commit 41f459e1dc
331 changed files with 13208 additions and 13691 deletions

View File

@@ -242,10 +242,11 @@ ZMQ_EXPORT int zmq_ctx_destroy (void *context);
* alignment and raise sigbus on violations. Make sure applications allocate * 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. * zmq_msg_t on addresses aligned on a pointer-size boundary to avoid this issue.
*/ */
typedef struct zmq_msg_t { typedef struct zmq_msg_t
#if defined (__GNUC__) || defined ( __INTEL_COMPILER) || \ {
(defined (__SUNPRO_C) && __SUNPRO_C >= 0x590) || \ #if defined(__GNUC__) || defined(__INTEL_COMPILER) \
(defined (__SUNPRO_CC) && __SUNPRO_CC >= 0x590) || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x590) \
|| (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x590)
unsigned char _[64] __attribute__ ((aligned (sizeof (void *)))); unsigned char _[64] __attribute__ ((aligned (sizeof (void *))));
#elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
__declspec(align (8)) unsigned char _[64]; __declspec(align (8)) unsigned char _[64];
@@ -260,8 +261,8 @@ 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 (zmq_msg_t *msg);
ZMQ_EXPORT int zmq_msg_init_size (zmq_msg_t *msg, size_t size); 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, ZMQ_EXPORT int zmq_msg_init_data (
size_t size, zmq_free_fn *ffn, void *hint); 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_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_recv (zmq_msg_t *msg, void *s, int flags);
ZMQ_EXPORT int zmq_msg_close (zmq_msg_t *msg); 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_more (const zmq_msg_t *msg);
ZMQ_EXPORT int zmq_msg_get (const zmq_msg_t *msg, int property); 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 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. */ /* 0MQ socket definition. */
@@ -425,10 +427,10 @@ ZMQ_EXPORT const char *zmq_msg_gets (const zmq_msg_t *msg, const char *property)
ZMQ_EXPORT void *zmq_socket (void *, int type); ZMQ_EXPORT void *zmq_socket (void *, int type);
ZMQ_EXPORT int zmq_close (void *s); ZMQ_EXPORT int zmq_close (void *s);
ZMQ_EXPORT int zmq_setsockopt (void *s, int option, const void *optval, ZMQ_EXPORT int
size_t optvallen); zmq_setsockopt (void *s, int option, const void *optval, size_t optvallen);
ZMQ_EXPORT int zmq_getsockopt (void *s, int option, void *optval, ZMQ_EXPORT int
size_t *optvallen); 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_bind (void *s, const char *addr);
ZMQ_EXPORT int zmq_connect (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); ZMQ_EXPORT int zmq_unbind (void *s, const char *addr);
@@ -469,7 +471,10 @@ ZMQ_EXPORT int zmq_poll (zmq_pollitem_t *items, int nitems, long timeout);
/******************************************************************************/ /******************************************************************************/
ZMQ_EXPORT int zmq_proxy (void *frontend, void *backend, void *capture); 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 */ /* 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_sendmsg (void *s, zmq_msg_t *msg, int flags);
ZMQ_EXPORT int zmq_recvmsg (void *s, zmq_msg_t *msg, int flags); ZMQ_EXPORT int zmq_recvmsg (void *s, zmq_msg_t *msg, int flags);
struct iovec; struct iovec;
ZMQ_EXPORT int zmq_sendiov (void *s, struct iovec *iov, size_t count, int flags); ZMQ_EXPORT int
ZMQ_EXPORT int zmq_recviov (void *s, struct iovec *iov, size_t *count, int flags); 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 */ /* 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. */ /* Derive the z85-encoded public key from the z85-encoded secret key. */
/* Returns 0 on success. */ /* 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 */ /* Atomic utility methods */
@@ -650,18 +658,25 @@ typedef struct zmq_poller_event_t
ZMQ_EXPORT void *zmq_poller_new (void); ZMQ_EXPORT void *zmq_poller_new (void);
ZMQ_EXPORT int zmq_poller_destroy (void **poller_p); 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_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_modify (void *poller, void *socket, short events);
ZMQ_EXPORT int zmq_poller_remove (void *poller, void *socket); 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_EXPORT int zmq_poller_wait_all (void *poller, zmq_poller_event_t *events, int n_events, long timeout); 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 #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_modify_fd (void *poller, SOCKET fd, short events);
ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, SOCKET fd); ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, SOCKET fd);
#else #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_modify_fd (void *poller, int fd, short events);
ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, int fd); ZMQ_EXPORT int zmq_poller_remove_fd (void *poller, int fd);
#endif #endif
@@ -680,9 +695,11 @@ typedef void (zmq_timer_fn)(int timer_id, void *arg);
ZMQ_EXPORT void *zmq_timers_new (void); ZMQ_EXPORT void *zmq_timers_new (void);
ZMQ_EXPORT int zmq_timers_destroy (void **timers_p); 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_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_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_set_interval (void *timers, int timer_id, size_t interval);
ZMQ_EXPORT int zmq_timers_reset (void *timers, int timer_id); ZMQ_EXPORT int zmq_timers_reset (void *timers, int timer_id);
ZMQ_EXPORT long zmq_timers_timeout (void *timers); ZMQ_EXPORT long zmq_timers_timeout (void *timers);
ZMQ_EXPORT int zmq_timers_execute (void *timers); ZMQ_EXPORT int zmq_timers_execute (void *timers);

View File

@@ -34,14 +34,16 @@
compilers even have an equivalent concept. compilers even have an equivalent concept.
So in the worst case, this include file is treated as silently empty. */ 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__) #if defined(__GNUC__) || defined(__GNUG__)
#pragma GCC diagnostic push #pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wcpp" #pragma GCC diagnostic warning "-Wcpp"
#pragma GCC diagnostic ignored "-Werror" #pragma GCC diagnostic ignored "-Werror"
#pragma GCC diagnostic ignored "-Wall" #pragma GCC diagnostic ignored "-Wall"
#endif #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__) #if defined(__GNUC__) || defined(__GNUG__)
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif

View File

@@ -149,8 +149,7 @@ int main (int argc, char *argv [])
} }
#if defined ZMQ_HAVE_WINDOWS #if defined ZMQ_HAVE_WINDOWS
local_thread = (HANDLE) _beginthreadex (NULL, 0, local_thread = (HANDLE) _beginthreadex (NULL, 0, worker, ctx, 0, NULL);
worker, ctx, 0 , NULL);
if (local_thread == 0) { if (local_thread == 0) {
printf ("error in _beginthreadex\n"); printf ("error in _beginthreadex\n");
return -1; return -1;
@@ -237,4 +236,3 @@ int main (int argc, char *argv [])
return 0; return 0;
} }

View File

@@ -71,7 +71,6 @@ static void *worker (void *ctx_)
} }
for (i = 0; i != message_count; i++) { for (i = 0; i != message_count; i++) {
rc = zmq_msg_init_size (&msg, message_size); rc = zmq_msg_init_size (&msg, message_size);
if (rc != 0) { if (rc != 0) {
printf ("error in zmq_msg_init_size: %s\n", zmq_strerror (errno)); printf ("error in zmq_msg_init_size: %s\n", zmq_strerror (errno));
@@ -150,8 +149,7 @@ int main (int argc, char *argv [])
} }
#if defined ZMQ_HAVE_WINDOWS #if defined ZMQ_HAVE_WINDOWS
local_thread = (HANDLE) _beginthreadex (NULL, 0, local_thread = (HANDLE) _beginthreadex (NULL, 0, worker, ctx, 0, NULL);
worker, ctx, 0 , NULL);
if (local_thread == 0) { if (local_thread == 0) {
printf ("error in _beginthreadex\n"); printf ("error in _beginthreadex\n");
return -1; return -1;
@@ -238,8 +236,8 @@ int main (int argc, char *argv [])
return -1; return -1;
} }
throughput = (unsigned long) throughput =
((double) message_count / (double) elapsed * 1000000); (unsigned long) ((double) message_count / (double) elapsed * 1000000);
megabits = (double) (throughput * message_size * 8) / 1000000; megabits = (double) (throughput * message_size * 8) / 1000000;
printf ("mean throughput: %d [msg/s]\n", (int) throughput); printf ("mean throughput: %d [msg/s]\n", (int) throughput);
@@ -247,4 +245,3 @@ int main (int argc, char *argv [])
return 0; return 0;
} }

View File

@@ -51,7 +51,8 @@ int main (int argc, char *argv [])
int curve = 0; int curve = 0;
if (argc != 4 && argc != 5) { if (argc != 4 && argc != 5) {
printf ("usage: local_thr <bind-to> <message-size> <message-count> [<enable_curve>]\n"); printf ("usage: local_thr <bind-to> <message-size> <message-count> "
"[<enable_curve>]\n");
return 1; return 1;
} }
bind_to = argv[1]; bind_to = argv[1];
@@ -76,7 +77,8 @@ int main (int argc, char *argv [])
// Add your socket options here. // Add your socket options here.
// For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. // For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM.
if (curve) { 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) { if (rc != 0) {
printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno)); printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno));
return -1; return -1;
@@ -135,8 +137,7 @@ int main (int argc, char *argv [])
return -1; return -1;
} }
throughput = throughput = ((double) message_count / (double) elapsed * 1000000);
((double) message_count / (double) elapsed * 1000000);
megabits = ((double) throughput * message_size * 8) / 1000000; megabits = ((double) throughput * message_size * 8) / 1000000;
printf ("message size: %d [B]\n", (int) message_size); printf ("message size: %d [B]\n", (int) message_size);

View File

@@ -76,19 +76,22 @@ int main (int argc, char *argv [])
// Add your socket options here. // Add your socket options here.
// For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. // For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM.
if (curve) { 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) { if (rc != 0) {
printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno)); printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno));
return -1; 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) { if (rc != 0) {
printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno)); printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno));
return -1; 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) { if (rc != 0) {
printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno)); printf ("error in zmq_setsockoopt: %s\n", zmq_strerror (errno));
return -1; return -1;

View File

@@ -44,9 +44,10 @@
#include <string> #include <string>
#include <sstream> #include <sstream>
zmq::address_t::address_t ( zmq::address_t::address_t (const std::string &protocol_,
const std::string &protocol_, const std::string &address_, ctx_t *parent_) const std::string &address_,
: protocol (protocol_), ctx_t *parent_) :
protocol (protocol_),
address (address_), address (address_),
parent (parent_) parent (parent_)
{ {
@@ -66,24 +67,21 @@ zmq::address_t::~address_t ()
} }
} }
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS
else else if (protocol == "ipc") {
if (protocol == "ipc") {
if (resolved.ipc_addr) { if (resolved.ipc_addr) {
LIBZMQ_DELETE (resolved.ipc_addr); LIBZMQ_DELETE (resolved.ipc_addr);
} }
} }
#endif #endif
#if defined ZMQ_HAVE_TIPC #if defined ZMQ_HAVE_TIPC
else else if (protocol == "tipc") {
if (protocol == "tipc") {
if (resolved.tipc_addr) { if (resolved.tipc_addr) {
LIBZMQ_DELETE (resolved.tipc_addr); LIBZMQ_DELETE (resolved.tipc_addr);
} }
} }
#endif #endif
#if defined ZMQ_HAVE_VMCI #if defined ZMQ_HAVE_VMCI
else else if (protocol == "vmci") {
if (protocol == "vmci") {
if (resolved.vmci_addr) { if (resolved.vmci_addr) {
LIBZMQ_DELETE (resolved.vmci_addr); LIBZMQ_DELETE (resolved.vmci_addr);
} }
@@ -102,22 +100,19 @@ int zmq::address_t::to_string (std::string &addr_) const
return resolved.udp_addr->to_string (addr_); return resolved.udp_addr->to_string (addr_);
} }
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS
else else if (protocol == "ipc") {
if (protocol == "ipc") {
if (resolved.ipc_addr) if (resolved.ipc_addr)
return resolved.ipc_addr->to_string (addr_); return resolved.ipc_addr->to_string (addr_);
} }
#endif #endif
#if defined ZMQ_HAVE_TIPC #if defined ZMQ_HAVE_TIPC
else else if (protocol == "tipc") {
if (protocol == "tipc") {
if (resolved.tipc_addr) if (resolved.tipc_addr)
return resolved.tipc_addr->to_string (addr_); return resolved.tipc_addr->to_string (addr_);
} }
#endif #endif
#if defined ZMQ_HAVE_VMCI #if defined ZMQ_HAVE_VMCI
else else if (protocol == "vmci") {
if (protocol == "vmci") {
if (resolved.vmci_addr) if (resolved.vmci_addr)
return resolved.vmci_addr->to_string (addr_); return resolved.vmci_addr->to_string (addr_);
} }

View File

@@ -46,8 +46,11 @@ namespace zmq
#if defined ZMQ_HAVE_VMCI #if defined ZMQ_HAVE_VMCI
class vmci_address_t; class vmci_address_t;
#endif #endif
struct address_t { struct address_t
address_t (const std::string &protocol_, const std::string &address_, ctx_t *parent_); {
address_t (const std::string &protocol_,
const std::string &address_,
ctx_t *parent_);
~address_t (); ~address_t ();
@@ -56,7 +59,8 @@ namespace zmq
ctx_t *parent; ctx_t *parent;
// Protocol specific resolved address // Protocol specific resolved address
union { union
{
tcp_address_t *tcp_addr; tcp_address_t *tcp_addr;
udp_address_t *udp_addr; udp_address_t *udp_addr;
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS

View File

@@ -51,30 +51,17 @@ namespace zmq
template <int ID = 0> class array_item_t template <int ID = 0> class array_item_t
{ {
public: public:
inline array_item_t () : array_index (-1) {}
inline array_item_t () :
array_index (-1)
{
}
// The destructor doesn't have to be virtual. It is made virtual // The destructor doesn't have to be virtual. It is made virtual
// just to keep ICC and code checking tools from complaining. // just to keep ICC and code checking tools from complaining.
inline virtual ~array_item_t () inline virtual ~array_item_t () {}
{
}
inline void set_array_index (int index_) inline void set_array_index (int index_) { array_index = index_; }
{
array_index = index_;
}
inline int get_array_index () inline int get_array_index () { return array_index; }
{
return array_index;
}
private: private:
int array_index; int array_index;
array_item_t (const array_item_t &); array_item_t (const array_item_t &);
@@ -85,35 +72,20 @@ namespace zmq
template <typename T, int ID = 0> class array_t template <typename T, int ID = 0> class array_t
{ {
private: private:
typedef array_item_t<ID> item_t; typedef array_item_t<ID> item_t;
public: public:
typedef typename std::vector<T *>::size_type size_type; typedef typename std::vector<T *>::size_type size_type;
inline array_t () inline array_t () {}
{
}
inline ~array_t () inline ~array_t () {}
{
}
inline size_type size () inline size_type size () { return items.size (); }
{
return items.size ();
}
inline bool empty () inline bool empty () { return items.empty (); }
{
return items.empty ();
}
inline T *&operator [] (size_type index_) inline T *&operator[] (size_type index_) { return items[index_]; }
{
return items [index_];
}
inline void push_back (T *item_) inline void push_back (T *item_)
{ {
@@ -122,11 +94,13 @@ namespace zmq
items.push_back (item_); items.push_back (item_);
} }
inline void erase (T *item_) { inline void erase (T *item_)
{
erase (((item_t *) item_)->get_array_index ()); erase (((item_t *) item_)->get_array_index ());
} }
inline void erase (size_type index_) { inline void erase (size_type index_)
{
if (items.back ()) if (items.back ())
((item_t *) items.back ())->set_array_index ((int) index_); ((item_t *) items.back ())->set_array_index ((int) index_);
items[index_] = items.back (); items[index_] = items.back ();
@@ -142,10 +116,7 @@ namespace zmq
std::swap (items[index1_], items[index2_]); std::swap (items[index1_], items[index2_]);
} }
inline void clear () inline void clear () { items.clear (); }
{
items.clear ();
}
inline size_type index (T *item_) inline size_type index (T *item_)
{ {
@@ -153,15 +124,12 @@ namespace zmq
} }
private: private:
typedef std::vector<T *> items_t; typedef std::vector<T *> items_t;
items_t items; items_t items;
array_t (const array_t &); array_t (const array_t &);
const array_t &operator= (const array_t &); const array_t &operator= (const array_t &);
}; };
} }
#endif #endif

View File

@@ -44,7 +44,8 @@
#define ZMQ_ATOMIC_COUNTER_ARM #define ZMQ_ATOMIC_COUNTER_ARM
#elif defined ZMQ_HAVE_WINDOWS #elif defined ZMQ_HAVE_WINDOWS
#define ZMQ_ATOMIC_COUNTER_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 #define ZMQ_ATOMIC_COUNTER_ATOMIC_H
#elif defined __tile__ #elif defined __tile__
#define ZMQ_ATOMIC_COUNTER_TILE #define ZMQ_ATOMIC_COUNTER_TILE
@@ -66,7 +67,6 @@
namespace zmq namespace zmq
{ {
// This class represents an integer that can be incremented/decremented // This class represents an integer that can be incremented/decremented
// in atomic fashion. // in atomic fashion.
// //
@@ -87,23 +87,14 @@ namespace zmq
#endif #endif
{ {
public: public:
typedef uint32_t integer_t; typedef uint32_t integer_t;
inline atomic_counter_t (integer_t value_ = 0) : inline atomic_counter_t (integer_t value_ = 0) : value (value_) {}
value (value_)
{
}
inline ~atomic_counter_t () inline ~atomic_counter_t () {}
{
}
// Set counter value (not thread-safe). // Set counter value (not thread-safe).
inline void set (integer_t value_) inline void set (integer_t value_) { value = value_; }
{
value = value_;
}
// Atomic addition. Returns the old value. // Atomic addition. Returns the old value.
inline integer_t add (integer_t increment_) inline integer_t add (integer_t increment_)
@@ -122,22 +113,21 @@ namespace zmq
#elif defined ZMQ_ATOMIC_COUNTER_TILE #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 #elif defined ZMQ_ATOMIC_COUNTER_X86
__asm__ volatile ( __asm__ volatile("lock; xadd %0, %1 \n\t"
"lock; xadd %0, %1 \n\t"
: "=r"(old_value), "=m"(value) : "=r"(old_value), "=m"(value)
: "0"(increment_), "m"(value) : "0"(increment_), "m"(value)
: "cc", "memory"); : "cc", "memory");
#elif defined ZMQ_ATOMIC_COUNTER_ARM #elif defined ZMQ_ATOMIC_COUNTER_ARM
integer_t flag, tmp; integer_t flag, tmp;
__asm__ volatile ( __asm__ volatile(" dmb sy\n\t"
" dmb sy\n\t"
"1: ldrex %0, [%5]\n\t" "1: ldrex %0, [%5]\n\t"
" add %2, %0, %4\n\t" " add %2, %0, %4\n\t"
" strex %1, %2, [%5]\n\t" " strex %1, %2, [%5]\n\t"
" teq %1, #0\n\t" " teq %1, #0\n\t"
" bne 1b\n\t" " bne 1b\n\t"
" dmb sy\n\t" " dmb sy\n\t"
: "=&r"(old_value), "=&r"(flag), "=&r"(tmp), "+Qo"(value) : "=&r"(old_value), "=&r"(flag), "=&r"(tmp),
"+Qo"(value)
: "Ir"(increment_), "r"(&value) : "Ir"(increment_), "r"(&value)
: "cc"); : "cc");
#elif defined ZMQ_ATOMIC_COUNTER_MUTEX #elif defined ZMQ_ATOMIC_COUNTER_MUTEX
@@ -182,15 +172,15 @@ namespace zmq
return oldval != decrement; return oldval != decrement;
#elif defined ZMQ_ATOMIC_COUNTER_ARM #elif defined ZMQ_ATOMIC_COUNTER_ARM
integer_t old_value, flag, tmp; integer_t old_value, flag, tmp;
__asm__ volatile ( __asm__ volatile(" dmb sy\n\t"
" dmb sy\n\t"
"1: ldrex %0, [%5]\n\t" "1: ldrex %0, [%5]\n\t"
" sub %2, %0, %4\n\t" " sub %2, %0, %4\n\t"
" strex %1, %2, [%5]\n\t" " strex %1, %2, [%5]\n\t"
" teq %1, #0\n\t" " teq %1, #0\n\t"
" bne 1b\n\t" " bne 1b\n\t"
" dmb sy\n\t" " dmb sy\n\t"
: "=&r"(old_value), "=&r"(flag), "=&r"(tmp), "+Qo"(value) : "=&r"(old_value), "=&r"(flag), "=&r"(tmp),
"+Qo"(value)
: "Ir"(decrement), "r"(&value) : "Ir"(decrement), "r"(&value)
: "cc"); : "cc");
return old_value - decrement != 0; return old_value - decrement != 0;
@@ -205,13 +195,9 @@ namespace zmq
#endif #endif
} }
inline integer_t get () const inline integer_t get () const { return value; }
{
return value;
}
private: private:
#if defined ZMQ_ATOMIC_COUNTER_CXX11 #if defined ZMQ_ATOMIC_COUNTER_CXX11
std::atomic<integer_t> value; std::atomic<integer_t> value;
#else #else
@@ -226,14 +212,13 @@ namespace zmq
atomic_counter_t (const atomic_counter_t &); atomic_counter_t (const atomic_counter_t &);
const atomic_counter_t &operator= (const atomic_counter_t &); const atomic_counter_t &operator= (const atomic_counter_t &);
#endif #endif
#if defined (__GNUC__) || defined ( __INTEL_COMPILER) || \ #if defined(__GNUC__) || defined(__INTEL_COMPILER) \
(defined (__SUNPRO_C) && __SUNPRO_C >= 0x590) || \ || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x590) \
(defined (__SUNPRO_CC) && __SUNPRO_CC >= 0x590) || (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x590)
} __attribute__ ((aligned (sizeof (void *)))); } __attribute__ ((aligned (sizeof (void *))));
#else #else
}; };
#endif #endif
} }
// Remove macros local to this file. // Remove macros local to this file.

View File

@@ -44,7 +44,8 @@
#define ZMQ_ATOMIC_PTR_TILE #define ZMQ_ATOMIC_PTR_TILE
#elif defined ZMQ_HAVE_WINDOWS #elif defined ZMQ_HAVE_WINDOWS
#define ZMQ_ATOMIC_PTR_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 #define ZMQ_ATOMIC_PTR_ATOMIC_H
#else #else
#define ZMQ_ATOMIC_PTR_MUTEX #define ZMQ_ATOMIC_PTR_MUTEX
@@ -64,31 +65,21 @@
namespace zmq namespace zmq
{ {
// This class encapsulates several atomic operations on pointers. // This class encapsulates several atomic operations on pointers.
template <typename T> class atomic_ptr_t template <typename T> class atomic_ptr_t
{ {
public: public:
// Initialise atomic pointer // Initialise atomic pointer
inline atomic_ptr_t () inline atomic_ptr_t () { ptr = NULL; }
{
ptr = NULL;
}
// Destroy atomic pointer // Destroy atomic pointer
inline ~atomic_ptr_t () inline ~atomic_ptr_t () {}
{
}
// Set value of atomic pointer in a non-threadsafe way // Set value of atomic pointer in a non-threadsafe way
// Use this function only when you are sure that at most one // Use this function only when you are sure that at most one
// thread is accessing the pointer at the moment. // thread is accessing the pointer at the moment.
inline void set (T *ptr_) inline void set (T *ptr_) { this->ptr = ptr_; }
{
this->ptr = ptr_;
}
// Perform atomic 'exchange pointers' operation. Pointer is set // Perform atomic 'exchange pointers' operation. Pointer is set
// to the 'val' value. Old value is returned. // to the 'val' value. Old value is returned.
@@ -106,16 +97,14 @@ namespace zmq
return (T *) arch_atomic_exchange (&ptr, val_); return (T *) arch_atomic_exchange (&ptr, val_);
#elif defined ZMQ_ATOMIC_PTR_X86 #elif defined ZMQ_ATOMIC_PTR_X86
T *old; T *old;
__asm__ volatile ( __asm__ volatile("lock; xchg %0, %2"
"lock; xchg %0, %2"
: "=r"(old), "=m"(ptr) : "=r"(old), "=m"(ptr)
: "m"(ptr), "0"(val_)); : "m"(ptr), "0"(val_));
return old; return old;
#elif defined ZMQ_ATOMIC_PTR_ARM #elif defined ZMQ_ATOMIC_PTR_ARM
T *old; T *old;
unsigned int flag; unsigned int flag;
__asm__ volatile ( __asm__ volatile(" dmb sy\n\t"
" dmb sy\n\t"
"1: ldrex %1, [%3]\n\t" "1: ldrex %1, [%3]\n\t"
" strex %0, %4, [%3]\n\t" " strex %0, %4, [%3]\n\t"
" teq %0, #0\n\t" " teq %0, #0\n\t"
@@ -143,8 +132,8 @@ namespace zmq
inline T *cas (T *cmp_, T *val_) inline T *cas (T *cmp_, T *val_)
{ {
#if defined ZMQ_ATOMIC_PTR_WINDOWS #if defined ZMQ_ATOMIC_PTR_WINDOWS
return (T*) InterlockedCompareExchangePointer ( return (T *) InterlockedCompareExchangePointer ((volatile PVOID *) &ptr,
(volatile PVOID*) &ptr, val_, cmp_); val_, cmp_);
#elif defined ZMQ_ATOMIC_PTR_INTRINSIC #elif defined ZMQ_ATOMIC_PTR_INTRINSIC
T *old = cmp_; T *old = cmp_;
__atomic_compare_exchange_n (&ptr, (volatile T **) &old, val_, false, __atomic_compare_exchange_n (&ptr, (volatile T **) &old, val_, false,
@@ -159,8 +148,7 @@ namespace zmq
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 #elif defined ZMQ_ATOMIC_PTR_X86
T *old; T *old;
__asm__ volatile ( __asm__ volatile("lock; cmpxchg %2, %3"
"lock; cmpxchg %2, %3"
: "=a"(old), "=m"(ptr) : "=a"(old), "=m"(ptr)
: "r"(val_), "m"(ptr), "0"(cmp_) : "r"(val_), "m"(ptr), "0"(cmp_)
: "cc"); : "cc");
@@ -168,8 +156,7 @@ namespace zmq
#elif defined ZMQ_ATOMIC_PTR_ARM #elif defined ZMQ_ATOMIC_PTR_ARM
T *old; T *old;
unsigned int flag; unsigned int flag;
__asm__ volatile ( __asm__ volatile(" dmb sy\n\t"
" dmb sy\n\t"
"1: ldrex %1, [%3]\n\t" "1: ldrex %1, [%3]\n\t"
" mov %0, #0\n\t" " mov %0, #0\n\t"
" teq %1, %4\n\t" " teq %1, %4\n\t"
@@ -195,7 +182,6 @@ namespace zmq
} }
private: private:
#if defined ZMQ_ATOMIC_PTR_CXX11 #if defined ZMQ_ATOMIC_PTR_CXX11
std::atomic<T *> ptr; std::atomic<T *> ptr;
#else #else
@@ -211,7 +197,6 @@ namespace zmq
const atomic_ptr_t &operator= (const atomic_ptr_t &); const atomic_ptr_t &operator= (const atomic_ptr_t &);
#endif #endif
}; };
} }
// Remove macros local to this file. // Remove macros local to this file.

View File

@@ -47,7 +47,9 @@
namespace zmq namespace zmq
{ {
struct reference_tag_t {}; struct reference_tag_t
{
};
// Object to hold dynamically allocated opaque binary data. // Object to hold dynamically allocated opaque binary data.
// On modern compilers, it will be movable but not copyable. Copies // On modern compilers, it will be movable but not copyable. Copies
@@ -59,19 +61,19 @@ namespace zmq
blob_t () : data_ (0), size_ (0), owned_ (true) {} blob_t () : data_ (0), size_ (0), owned_ (true) {}
// Creates a blob_t of a given size, with uninitialized content. // Creates a blob_t of a given size, with uninitialized content.
blob_t (const size_t size) blob_t (const size_t size) :
: data_ ((unsigned char*)malloc (size)) data_ ((unsigned char *) malloc (size)),
, size_ (size) size_ (size),
, owned_ (true) owned_ (true)
{ {
} }
// Creates a blob_t of a given size, an initializes content by copying // Creates a blob_t of a given size, an initializes content by copying
// from another buffer. // from another buffer.
blob_t(const unsigned char * const data, const size_t size) blob_t (const unsigned char *const data, const size_t size) :
: data_ ((unsigned char*)malloc (size)) data_ ((unsigned char *) malloc (size)),
, size_ (size) size_ (size),
, owned_ (true) owned_ (true)
{ {
memcpy (data_, data, size_); memcpy (data_, data, size_);
} }
@@ -80,10 +82,10 @@ namespace zmq
// pre-allocated block of data. // pre-allocated block of data.
// Use with caution and ensure that the blob_t will not outlive // Use with caution and ensure that the blob_t will not outlive
// the referenced data. // the referenced data.
blob_t (unsigned char * const data, const size_t size, reference_tag_t) blob_t (unsigned char *const data, const size_t size, reference_tag_t) :
: data_ (data) data_ (data),
, size_ (size) size_ (size),
, owned_ (false) owned_ (false)
{ {
} }
@@ -91,17 +93,14 @@ namespace zmq
size_t size () const { return size_; } size_t size () const { return size_; }
// Returns a pointer to the data of the blob_t. // Returns a pointer to the data of the blob_t.
const unsigned char *data() const { const unsigned char *data () const { return data_; }
return data_;
}
// Returns a pointer to the data of the blob_t. // Returns a pointer to the data of the blob_t.
unsigned char *data() { unsigned char *data () { return data_; }
return data_;
}
// Defines an order relationship on blob_t. // Defines an order relationship on blob_t.
bool operator< (blob_t const &other) const { bool operator< (blob_t const &other) const
{
int cmpres = memcmp (data_, other.data_, std::min (size_, other.size_)); int cmpres = memcmp (data_, other.data_, std::min (size_, other.size_));
return cmpres < 0 || (cmpres == 0 && size_ < other.size_); return cmpres < 0 || (cmpres == 0 && size_ < other.size_);
} }
@@ -127,29 +126,36 @@ namespace zmq
} }
// Empties a blob_t. // Empties a blob_t.
void clear () { void clear ()
if (owned_) { free (data_); } {
data_ = 0; size_ = 0; if (owned_) {
free (data_);
}
data_ = 0;
size_ = 0;
} }
~blob_t () { ~blob_t ()
if (owned_) { free (data_); } {
if (owned_) {
free (data_);
}
} }
#ifdef ZMQ_HAS_MOVE_SEMANTICS #ifdef ZMQ_HAS_MOVE_SEMANTICS
blob_t (const blob_t &) = delete; blob_t (const blob_t &) = delete;
blob_t &operator= (const blob_t &) = delete; blob_t &operator= (const blob_t &) = delete;
blob_t (blob_t&& other) blob_t (blob_t &&other) :
: data_ (other.data_) data_ (other.data_),
, size_ (other.size_) size_ (other.size_),
, owned_ (other.owned_) owned_ (other.owned_)
{ {
other.owned_ = false; other.owned_ = false;
} }
blob_t &operator= (blob_t&& other) { blob_t &operator= (blob_t &&other)
if (this != &other)
{ {
if (this != &other) {
clear (); clear ();
data_ = other.data_; data_ = other.data_;
size_ = other.size_; size_ = other.size_;
@@ -159,14 +165,10 @@ namespace zmq
return *this; return *this;
} }
#else #else
blob_t (const blob_t &other) blob_t (const blob_t &other) : owned_ (false) { set_deep_copy (other); }
: owned_(false) blob_t &operator= (const blob_t &other)
{
set_deep_copy (other);
}
blob_t &operator= (const blob_t &other) {
if (this != &other)
{ {
if (this != &other) {
clear (); clear ();
set_deep_copy (other); set_deep_copy (other);
} }
@@ -179,8 +181,6 @@ namespace zmq
size_t size_; size_t size_;
bool owned_; bool owned_;
}; };
} }
#endif #endif

View File

@@ -69,7 +69,6 @@ int zmq::client_t::xrecv (msg_t *msg_)
// Drop any messages with more flag // Drop any messages with more flag
while (rc == 0 && msg_->flags () & msg_t::more) { while (rc == 0 && msg_->flags () & msg_t::more) {
// drop all frames of the current multi-frame message // drop all frames of the current multi-frame message
rc = fq.recvpipe (msg_, NULL); rc = fq.recvpipe (msg_, NULL);

View File

@@ -37,23 +37,19 @@
namespace zmq namespace zmq
{ {
class ctx_t; class ctx_t;
class msg_t; class msg_t;
class pipe_t; class pipe_t;
class io_thread_t; class io_thread_t;
class socket_base_t; class socket_base_t;
class client_t : class client_t : public socket_base_t
public socket_base_t
{ {
public: public:
client_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); client_t (zmq::ctx_t *parent_, uint32_t tid_, int sid);
~client_t (); ~client_t ();
protected: protected:
// Overrides of functions from socket_base_t. // Overrides of functions from socket_base_t.
void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_);
int xsend (zmq::msg_t *msg_); int xsend (zmq::msg_t *msg_);
@@ -66,7 +62,6 @@ namespace zmq
void xpipe_terminated (zmq::pipe_t *pipe_); void xpipe_terminated (zmq::pipe_t *pipe_);
private: private:
// Messages are fair-queued from inbound pipes. And load-balanced to // Messages are fair-queued from inbound pipes. And load-balanced to
// the outbound pipes. // the outbound pipes.
fq_t fq; fq_t fq;
@@ -75,7 +70,6 @@ namespace zmq
client_t (const client_t &); client_t (const client_t &);
const client_t &operator= (const client_t &); const client_t &operator= (const client_t &);
}; };
} }
#endif #endif

View File

@@ -92,7 +92,8 @@ ULONGLONG compatible_get_tick_count64()
++s_wrap; ++s_wrap;
s_last_tick = current_tick; s_last_tick = current_tick;
const ULONGLONG result = (static_cast<ULONGLONG>(s_wrap) << 32) + static_cast<ULONGLONG>(current_tick); const ULONGLONG result = (static_cast<ULONGLONG> (s_wrap) << 32)
+ static_cast<ULONGLONG> (current_tick);
return result; return result;
#endif #endif
@@ -105,7 +106,8 @@ f_compatible_get_tick_count64 init_compatible_get_tick_count64()
HMODULE module = ::LoadLibraryA ("Kernel32.dll"); HMODULE module = ::LoadLibraryA ("Kernel32.dll");
if (module != NULL) if (module != NULL)
func = reinterpret_cast<f_compatible_get_tick_count64>(::GetProcAddress(module, "GetTickCount64")); func = reinterpret_cast<f_compatible_get_tick_count64> (
::GetProcAddress (module, "GetTickCount64"));
#endif #endif
if (func == NULL) if (func == NULL)
func = compatible_get_tick_count64; func = compatible_get_tick_count64;
@@ -117,7 +119,8 @@ f_compatible_get_tick_count64 init_compatible_get_tick_count64()
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 #endif
zmq::clock_t::clock_t () : zmq::clock_t::clock_t () :
@@ -156,7 +159,8 @@ uint64_t zmq::clock_t::now_us ()
// Use POSIX clock_gettime function to get precise monotonic time. // Use POSIX clock_gettime function to get precise monotonic time.
struct timespec tv; 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); int rc = alt_clock_gettime (SYSTEM_CLOCK, &tv);
#else #else
int rc = clock_gettime (CLOCK_MONOTONIC, &tv); int rc = clock_gettime (CLOCK_MONOTONIC, &tv);
@@ -193,8 +197,7 @@ uint64_t zmq::clock_t::now_ms ()
uint64_t tsc = rdtsc (); uint64_t tsc = rdtsc ();
// If TSC is not supported, get precise time and chop off the microseconds. // If TSC is not supported, get precise time and chop off the microseconds.
if (!tsc) if (!tsc) {
{
#ifdef ZMQ_HAVE_WINDOWS #ifdef ZMQ_HAVE_WINDOWS
// Under Windows, now_us is not so reliable since QueryPerformanceCounter // Under Windows, now_us is not so reliable since QueryPerformanceCounter
// does not guarantee that it will use a hardware that offers a monotonic timer. // does not guarantee that it will use a hardware that offers a monotonic timer.
@@ -229,9 +232,10 @@ uint64_t zmq::clock_t::rdtsc ()
uint32_t low, high; uint32_t low, high;
__asm__ volatile("rdtsc" : "=a"(low), "=d"(high)); __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
return (uint64_t) high << 32 | low; return (uint64_t) high << 32 | low;
#elif (defined __SUNPRO_CC && (__SUNPRO_CC >= 0x5100) && (defined __i386 || \ #elif (defined __SUNPRO_CC && (__SUNPRO_CC >= 0x5100) \
defined __amd64 || defined __x86_64)) && (defined __i386 || defined __amd64 || defined __x86_64))
union { union
{
uint64_t u64val; uint64_t u64val;
uint32_t u32val[2]; uint32_t u32val[2];
} tsc; } tsc;
@@ -243,7 +247,8 @@ uint64_t zmq::clock_t::rdtsc ()
return (tsc); return (tsc);
#else #else
struct timespec ts; struct timespec ts;
#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
alt_clock_gettime (SYSTEM_CLOCK, &ts); alt_clock_gettime (SYSTEM_CLOCK, &ts);
#else #else
clock_gettime (CLOCK_MONOTONIC, &ts); clock_gettime (CLOCK_MONOTONIC, &ts);

View File

@@ -48,11 +48,9 @@ int alt_clock_gettime (int clock_id, timespec *ts);
namespace zmq namespace zmq
{ {
class clock_t class clock_t
{ {
public: public:
clock_t (); clock_t ();
~clock_t (); ~clock_t ();
@@ -67,7 +65,6 @@ namespace zmq
uint64_t now_ms (); uint64_t now_ms ();
private: private:
// TSC timestamp of when last time measurement was made. // TSC timestamp of when last time measurement was made.
uint64_t last_tsc; uint64_t last_tsc;
@@ -77,7 +74,6 @@ namespace zmq
clock_t (const clock_t &); clock_t (const clock_t &);
const clock_t &operator= (const clock_t &); const clock_t &operator= (const clock_t &);
}; };
} }
#endif #endif

View File

@@ -35,7 +35,6 @@
namespace zmq namespace zmq
{ {
class object_t; class object_t;
class own_t; class own_t;
struct i_engine; struct i_engine;
@@ -79,101 +78,118 @@ namespace zmq
union args_t union args_t
{ {
// Sent to I/O thread to let it know that it should // Sent to I/O thread to let it know that it should
// terminate itself. // terminate itself.
struct { struct
{
} stop; } stop;
// Sent to I/O object to make it register with its I/O thread. // Sent to I/O object to make it register with its I/O thread.
struct { struct
{
} plug; } plug;
// Sent to socket to let it know about the newly created object. // Sent to socket to let it know about the newly created object.
struct { struct
{
zmq::own_t *object; zmq::own_t *object;
} own; } own;
// Attach the engine to the session. If engine is NULL, it informs // Attach the engine to the session. If engine is NULL, it informs
// session that the connection have failed. // session that the connection have failed.
struct { struct
{
struct i_engine *engine; struct i_engine *engine;
} attach; } attach;
// Sent from session to socket to establish pipe(s) between them. // Sent from session to socket to establish pipe(s) between them.
// Caller have used inc_seqnum beforehand sending the command. // Caller have used inc_seqnum beforehand sending the command.
struct { struct
{
zmq::pipe_t *pipe; zmq::pipe_t *pipe;
} bind; } bind;
// Sent by pipe writer to inform dormant pipe reader that there // Sent by pipe writer to inform dormant pipe reader that there
// are messages in the pipe. // are messages in the pipe.
struct { struct
{
} activate_read; } activate_read;
// Sent by pipe reader to inform pipe writer about how many // Sent by pipe reader to inform pipe writer about how many
// messages it has read so far. // messages it has read so far.
struct { struct
{
uint64_t msgs_read; uint64_t msgs_read;
} activate_write; } activate_write;
// Sent by pipe reader to writer after creating a new inpipe. // Sent by pipe reader to writer after creating a new inpipe.
// The parameter is actually of type pipe_t::upipe_t, however, // The parameter is actually of type pipe_t::upipe_t, however,
// its definition is private so we'll have to do with void*. // its definition is private so we'll have to do with void*.
struct { struct
{
void *pipe; void *pipe;
} hiccup; } hiccup;
// Sent by pipe reader to pipe writer to ask it to terminate // Sent by pipe reader to pipe writer to ask it to terminate
// its end of the pipe. // its end of the pipe.
struct { struct
{
} pipe_term; } pipe_term;
// Pipe writer acknowledges pipe_term command. // Pipe writer acknowledges pipe_term command.
struct { struct
{
} pipe_term_ack; } pipe_term_ack;
// Sent by one of pipe to another part for modify hwm // Sent by one of pipe to another part for modify hwm
struct { struct
{
int inhwm; int inhwm;
int outhwm; int outhwm;
} pipe_hwm; } pipe_hwm;
// Sent by I/O object ot the socket to request the shutdown of // Sent by I/O object ot the socket to request the shutdown of
// the I/O object. // the I/O object.
struct { struct
{
zmq::own_t *object; zmq::own_t *object;
} term_req; } term_req;
// Sent by socket to I/O object to start its shutdown. // Sent by socket to I/O object to start its shutdown.
struct { struct
{
int linger; int linger;
} term; } term;
// Sent by I/O object to the socket to acknowledge it has // Sent by I/O object to the socket to acknowledge it has
// shut down. // shut down.
struct { struct
{
} term_ack; } term_ack;
// Sent by session_base (I/O thread) to socket (application thread) // Sent by session_base (I/O thread) to socket (application thread)
// to ask to disconnect the endpoint. // to ask to disconnect the endpoint.
struct { struct
{
std::string *endpoint; std::string *endpoint;
} term_endpoint; } term_endpoint;
// Transfers the ownership of the closed socket // Transfers the ownership of the closed socket
// to the reaper thread. // to the reaper thread.
struct { struct
{
zmq::socket_base_t *socket; zmq::socket_base_t *socket;
} reap; } reap;
// Closed socket notifies the reaper that it's already deallocated. // Closed socket notifies the reaper that it's already deallocated.
struct { struct
{
} reaped; } reaped;
// Sent by reaper thread to the term thread when all the sockets // Sent by reaper thread to the term thread when all the sockets
// are successfully deallocated. // are successfully deallocated.
struct { struct
{
} done; } done;
} args; } args;

View File

@@ -58,19 +58,12 @@
namespace zmq namespace zmq
{ {
class condition_variable_t class condition_variable_t
{ {
public: public:
inline condition_variable_t () inline condition_variable_t () { zmq_assert (false); }
{
zmq_assert(false);
}
inline ~condition_variable_t () inline ~condition_variable_t () {}
{
}
inline int wait (mutex_t *mutex_, int timeout_) inline int wait (mutex_t *mutex_, int timeout_)
{ {
@@ -78,18 +71,13 @@ namespace zmq
return -1; return -1;
} }
inline void broadcast () inline void broadcast () { zmq_assert (false); }
{
zmq_assert(false);
}
private: private:
// Disable copy construction and assignment. // Disable copy construction and assignment.
condition_variable_t (const condition_variable_t &); condition_variable_t (const condition_variable_t &);
void operator= (const condition_variable_t &); void operator= (const condition_variable_t &);
}; };
} }
#else #else
@@ -106,15 +94,9 @@ namespace zmq
class condition_variable_t class condition_variable_t
{ {
public: public:
inline condition_variable_t () inline condition_variable_t () { InitializeConditionVariable (&cv); }
{
InitializeConditionVariable (&cv);
}
inline ~condition_variable_t () inline ~condition_variable_t () {}
{
}
inline int wait (mutex_t *mutex_, int timeout_) inline int wait (mutex_t *mutex_, int timeout_)
{ {
@@ -132,13 +114,9 @@ namespace zmq
return -1; return -1;
} }
inline void broadcast () inline void broadcast () { WakeAllConditionVariable (&cv); }
{
WakeAllConditionVariable(&cv);
}
private: private:
CONDITION_VARIABLE cv; CONDITION_VARIABLE cv;
// Disable copy construction and assignment. // Disable copy construction and assignment.
@@ -149,15 +127,9 @@ namespace zmq
class condition_variable_t class condition_variable_t
{ {
public: public:
inline condition_variable_t() inline condition_variable_t () {}
{
} inline ~condition_variable_t () {}
inline ~condition_variable_t()
{
}
inline int wait (mutex_t *mutex_, int timeout_) inline int wait (mutex_t *mutex_, int timeout_)
{ {
@@ -165,8 +137,10 @@ namespace zmq
mutex_->unlock (); // unlock mutex_ mutex_->unlock (); // unlock mutex_
int res = 0; int res = 0;
if (timeout_ == -1) { if (timeout_ == -1) {
cv.wait(lck); // unlock mtx and wait cv.notify_all(), lock mtx after cv.notify_all() cv.wait (
} else if (cv.wait_for(lck, std::chrono::milliseconds(timeout_)) == std::cv_status::timeout) { 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 // time expired
errno = EAGAIN; errno = EAGAIN;
res = -1; res = -1;
@@ -183,7 +157,6 @@ namespace zmq
} }
private: private:
std::condition_variable cv; std::condition_variable cv;
std::mutex mtx; std::mutex mtx;
@@ -203,7 +176,6 @@ namespace zmq
namespace zmq namespace zmq
{ {
class condition_variable_t class condition_variable_t
{ {
public: public:
@@ -226,7 +198,8 @@ namespace zmq
if (timeout_ != -1) { if (timeout_ != -1) {
struct timespec timeout; struct timespec timeout;
#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
alt_clock_gettime (SYSTEM_CLOCK, &timeout); alt_clock_gettime (SYSTEM_CLOCK, &timeout);
#else #else
clock_gettime (CLOCK_MONOTONIC, &timeout); clock_gettime (CLOCK_MONOTONIC, &timeout);
@@ -241,8 +214,7 @@ namespace zmq
} }
rc = pthread_cond_timedwait (&cond, mutex_->get_mutex (), &timeout); rc = pthread_cond_timedwait (&cond, mutex_->get_mutex (), &timeout);
} } else
else
rc = pthread_cond_wait (&cond, mutex_->get_mutex ()); rc = pthread_cond_wait (&cond, mutex_->get_mutex ());
if (rc == 0) if (rc == 0)
@@ -264,7 +236,6 @@ namespace zmq
} }
private: private:
pthread_cond_t cond; pthread_cond_t cond;
// Disable copy construction and assignment. // Disable copy construction and assignment.

View File

@@ -32,7 +32,6 @@
namespace zmq namespace zmq
{ {
// Compile-time settings. // Compile-time settings.
enum enum
@@ -92,7 +91,6 @@ namespace zmq
// https://github.com/zeromq/libzmq/issues/1542 // https://github.com/zeromq/libzmq/issues/1542
signaler_port = 0 signaler_port = 0
}; };
} }
#endif #endif

View File

@@ -57,7 +57,8 @@
int clipped_maxsocket (int max_requested) 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. // -1 because we need room for the reaper mailbox.
max_requested = zmq::poller_t::max_fds () - 1; max_requested = zmq::poller_t::max_fds () - 1;
@@ -141,7 +142,8 @@ int zmq::ctx_t::terminate ()
// Connect up any pending inproc connections, otherwise we will hang // Connect up any pending inproc connections, otherwise we will hang
pending_connections_t copy = pending_connections; 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); zmq::socket_base_t *s = create_socket (ZMQ_PAIR);
// create_socket might fail eg: out of memory/sockets limit reached // create_socket might fail eg: out of memory/sockets limit reached
zmq_assert (s); zmq_assert (s);
@@ -229,38 +231,26 @@ int zmq::ctx_t::shutdown ()
int zmq::ctx_t::set (int option_, int optval_) int zmq::ctx_t::set (int option_, int optval_)
{ {
int rc = 0; int rc = 0;
if (option_ == ZMQ_MAX_SOCKETS if (option_ == ZMQ_MAX_SOCKETS && optval_ >= 1
&& optval_ >= 1 && optval_ == clipped_maxsocket (optval_)) { && optval_ == clipped_maxsocket (optval_)) {
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
max_sockets = optval_; max_sockets = optval_;
} } else if (option_ == ZMQ_IO_THREADS && optval_ >= 0) {
else
if (option_ == ZMQ_IO_THREADS && optval_ >= 0) {
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
io_thread_count = optval_; io_thread_count = optval_;
} } else if (option_ == ZMQ_IPV6 && optval_ >= 0) {
else
if (option_ == ZMQ_IPV6 && optval_ >= 0) {
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
ipv6 = (optval_ != 0); ipv6 = (optval_ != 0);
} } else if (option_ == ZMQ_THREAD_PRIORITY && optval_ >= 0) {
else
if (option_ == ZMQ_THREAD_PRIORITY && optval_ >= 0) {
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
thread_priority = optval_; thread_priority = optval_;
} } else if (option_ == ZMQ_THREAD_SCHED_POLICY && optval_ >= 0) {
else
if (option_ == ZMQ_THREAD_SCHED_POLICY && optval_ >= 0) {
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
thread_sched_policy = optval_; thread_sched_policy = optval_;
} } else if (option_ == ZMQ_THREAD_AFFINITY_CPU_ADD && optval_ >= 0) {
else
if (option_ == ZMQ_THREAD_AFFINITY_CPU_ADD && optval_ >= 0) {
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
thread_affinity_cpus.insert (optval_); thread_affinity_cpus.insert (optval_);
} } else if (option_ == ZMQ_THREAD_AFFINITY_CPU_REMOVE && optval_ >= 0) {
else
if (option_ == ZMQ_THREAD_AFFINITY_CPU_REMOVE && optval_ >= 0) {
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
std::set<int>::iterator it = thread_affinity_cpus.find (optval_); std::set<int>::iterator it = thread_affinity_cpus.find (optval_);
if (it != thread_affinity_cpus.end ()) { if (it != thread_affinity_cpus.end ()) {
@@ -269,25 +259,18 @@ int zmq::ctx_t::set (int option_, int optval_)
errno = EINVAL; errno = EINVAL;
rc = -1; rc = -1;
} }
} } else if (option_ == ZMQ_THREAD_NAME_PREFIX && optval_ >= 0) {
else
if (option_ == ZMQ_THREAD_NAME_PREFIX && optval_ >= 0) {
std::ostringstream s; std::ostringstream s;
s << optval_; s << optval_;
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
thread_name_prefix = s.str (); thread_name_prefix = s.str ();
} } else if (option_ == ZMQ_BLOCKY && optval_ >= 0) {
else
if (option_ == ZMQ_BLOCKY && optval_ >= 0) {
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
blocky = (optval_ != 0); blocky = (optval_ != 0);
} } else if (option_ == ZMQ_MAX_MSGSZ && optval_ >= 0) {
else
if (option_ == ZMQ_MAX_MSGSZ && optval_ >= 0) {
scoped_lock_t locker (opt_sync); scoped_lock_t locker (opt_sync);
max_msgsz = optval_ < INT_MAX ? optval_ : INT_MAX; max_msgsz = optval_ < INT_MAX ? optval_ : INT_MAX;
} } else {
else {
errno = EINVAL; errno = EINVAL;
rc = -1; rc = -1;
} }
@@ -299,23 +282,17 @@ int zmq::ctx_t::get (int option_)
int rc = 0; int rc = 0;
if (option_ == ZMQ_MAX_SOCKETS) if (option_ == ZMQ_MAX_SOCKETS)
rc = max_sockets; rc = max_sockets;
else else if (option_ == ZMQ_SOCKET_LIMIT)
if (option_ == ZMQ_SOCKET_LIMIT)
rc = clipped_maxsocket (65535); rc = clipped_maxsocket (65535);
else else if (option_ == ZMQ_IO_THREADS)
if (option_ == ZMQ_IO_THREADS)
rc = io_thread_count; rc = io_thread_count;
else else if (option_ == ZMQ_IPV6)
if (option_ == ZMQ_IPV6)
rc = ipv6; rc = ipv6;
else else if (option_ == ZMQ_BLOCKY)
if (option_ == ZMQ_BLOCKY)
rc = blocky; rc = blocky;
else else if (option_ == ZMQ_MAX_MSGSZ)
if (option_ == ZMQ_MAX_MSGSZ)
rc = max_msgsz; rc = max_msgsz;
else else if (option_ == ZMQ_MSG_T_SIZE)
if (option_ == ZMQ_MSG_T_SIZE)
rc = sizeof (zmq_msg_t); rc = sizeof (zmq_msg_t);
else { else {
errno = EINVAL; errno = EINVAL;
@@ -457,11 +434,14 @@ zmq::object_t *zmq::ctx_t::get_reaper ()
return 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; static unsigned int nthreads_started = 0;
thread_.setSchedulingParameters(thread_priority, thread_sched_policy, thread_affinity_cpus); thread_.setSchedulingParameters (thread_priority, thread_sched_policy,
thread_affinity_cpus);
thread_.start (tfn_, arg_); thread_.start (tfn_, arg_);
#ifndef ZMQ_HAVE_ANDROID #ifndef ZMQ_HAVE_ANDROID
std::ostringstream s; std::ostringstream s;
@@ -503,8 +483,8 @@ int zmq::ctx_t::register_endpoint (const char *addr_,
{ {
scoped_lock_t locker (endpoints_sync); scoped_lock_t locker (endpoints_sync);
const bool inserted = endpoints.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, const bool inserted =
endpoint_).second; endpoints.ZMQ_MAP_INSERT_OR_EMPLACE (addr_, endpoint_).second;
if (!inserted) { if (!inserted) {
errno = EADDRINUSE; errno = EADDRINUSE;
return -1; return -1;
@@ -512,8 +492,8 @@ int zmq::ctx_t::register_endpoint (const char *addr_,
return 0; return 0;
} }
int zmq::ctx_t::unregister_endpoint ( int zmq::ctx_t::unregister_endpoint (const std::string &addr_,
const std::string &addr_, socket_base_t *socket_) socket_base_t *socket_)
{ {
scoped_lock_t locker (endpoints_sync); scoped_lock_t locker (endpoints_sync);
@@ -567,36 +547,47 @@ zmq::endpoint_t zmq::ctx_t::find_endpoint (const char *addr_)
} }
void zmq::ctx_t::pend_connection (const std::string &addr_, 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_); endpoints_t::iterator it = endpoints.find (addr_);
if (it == endpoints.end ()) { if (it == endpoints.end ()) {
// Still no bind. // Still no bind.
endpoint_.socket->inc_seqnum (); 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 { } else {
// Bind has happened in the mean time, connect directly // 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_connections_t::iterator, pending_connections_t::iterator> pending = pending_connections.equal_range(addr_); std::pair<pending_connections_t::iterator, pending_connections_t::iterator>
for (pending_connections_t::iterator p = pending.first; p != pending.second; ++p) pending = pending_connections.equal_range (addr_);
connect_inproc_sockets(bind_socket_, endpoints[addr_].options, p->second, bind_side); 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_, void zmq::ctx_t::connect_inproc_sockets (
options_t& bind_options, const pending_connection_t &pending_connection_, side side_) 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 ()); pending_connection_.bind_pipe->set_tid (bind_socket_->get_tid ());
@@ -609,21 +600,27 @@ void zmq::ctx_t::connect_inproc_sockets (zmq::socket_base_t *bind_socket_,
errno_assert (rc == 0); errno_assert (rc == 0);
} }
bool conflate = pending_connection_.endpoint.options.conflate && bool conflate =
(pending_connection_.endpoint.options.type == ZMQ_DEALER || pending_connection_.endpoint.options.conflate
pending_connection_.endpoint.options.type == ZMQ_PULL || && (pending_connection_.endpoint.options.type == ZMQ_DEALER
pending_connection_.endpoint.options.type == ZMQ_PUSH || || pending_connection_.endpoint.options.type == ZMQ_PULL
pending_connection_.endpoint.options.type == ZMQ_PUB || || pending_connection_.endpoint.options.type == ZMQ_PUSH
pending_connection_.endpoint.options.type == ZMQ_SUB); || pending_connection_.endpoint.options.type == ZMQ_PUB
|| pending_connection_.endpoint.options.type == ZMQ_SUB);
if (!conflate) { if (!conflate) {
pending_connection_.connect_pipe->set_hwms_boost(bind_options.sndhwm, bind_options.rcvhwm); pending_connection_.connect_pipe->set_hwms_boost (bind_options.sndhwm,
pending_connection_.bind_pipe->set_hwms_boost(pending_connection_.endpoint.options.sndhwm, pending_connection_.endpoint.options.rcvhwm); 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_.connect_pipe->set_hwms (
pending_connection_.bind_pipe->set_hwms(bind_options.rcvhwm, bind_options.sndhwm); pending_connection_.endpoint.options.rcvhwm,
} pending_connection_.endpoint.options.sndhwm);
else { pending_connection_.bind_pipe->set_hwms (bind_options.rcvhwm,
bind_options.sndhwm);
} else {
pending_connection_.connect_pipe->set_hwms (-1, -1); pending_connection_.connect_pipe->set_hwms (-1, -1);
pending_connection_.bind_pipe->set_hwms (-1, -1); pending_connection_.bind_pipe->set_hwms (-1, -1);
} }
@@ -633,22 +630,24 @@ void zmq::ctx_t::connect_inproc_sockets (zmq::socket_base_t *bind_socket_,
cmd.type = command_t::bind; cmd.type = command_t::bind;
cmd.args.bind.pipe = pending_connection_.bind_pipe; cmd.args.bind.pipe = pending_connection_.bind_pipe;
bind_socket_->process_command (cmd); bind_socket_->process_command (cmd);
bind_socket_->send_inproc_connected (pending_connection_.endpoint.socket); bind_socket_->send_inproc_connected (
} pending_connection_.endpoint.socket);
else } else
pending_connection_.connect_pipe->send_bind (bind_socket_, pending_connection_.bind_pipe, false); pending_connection_.connect_pipe->send_bind (
bind_socket_, pending_connection_.bind_pipe, false);
// When a ctx is terminated all pending inproc connection will be // When a ctx is terminated all pending inproc connection will be
// connected, but the socket will already be closed and the pipe 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 // 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 // and the routing id write fails and causes an assert. Check if the socket
// is open before sending. // is open before sending.
if (pending_connection_.endpoint.options.recv_routing_id && if (pending_connection_.endpoint.options.recv_routing_id
pending_connection_.endpoint.socket->check_tag ()) { && pending_connection_.endpoint.socket->check_tag ()) {
msg_t routing_id; msg_t routing_id;
const int rc = routing_id.init_size (bind_options.routing_id_size); const int rc = routing_id.init_size (bind_options.routing_id_size);
errno_assert (rc == 0); 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); routing_id.set_flags (msg_t::routing_id);
const bool written = pending_connection_.bind_pipe->write (&routing_id); const bool written = pending_connection_.bind_pipe->write (&routing_id);
zmq_assert (written); zmq_assert (written);

View File

@@ -46,7 +46,6 @@
namespace zmq namespace zmq
{ {
class object_t; class object_t;
class io_thread_t; class io_thread_t;
class socket_base_t; class socket_base_t;
@@ -68,7 +67,6 @@ namespace zmq
class ctx_t class ctx_t
{ {
public: public:
// Create the context object. // Create the context object.
ctx_t (); ctx_t ();
@@ -118,7 +116,8 @@ namespace zmq
void unregister_endpoints (zmq::socket_base_t *socket_); void unregister_endpoints (zmq::socket_base_t *socket_);
endpoint_t find_endpoint (const char *addr_); endpoint_t find_endpoint (const char *addr_);
void pend_connection (const std::string &addr_, void pend_connection (const std::string &addr_,
const endpoint_t &endpoint_, pipe_t **pipes_); const endpoint_t &endpoint_,
pipe_t **pipes_);
void connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_); void connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_);
#ifdef ZMQ_HAVE_VMCI #ifdef ZMQ_HAVE_VMCI
@@ -126,7 +125,8 @@ namespace zmq
int get_vmci_socket_family (); int get_vmci_socket_family ();
#endif #endif
enum { enum
{
term_tid = 0, term_tid = 0,
reaper_tid = 1 reaper_tid = 1
}; };
@@ -190,7 +190,8 @@ namespace zmq
endpoints_t endpoints; endpoints_t endpoints;
// List of inproc connection endpoints pending a bind // List of inproc connection endpoints pending a bind
typedef std::multimap <std::string, pending_connection_t> pending_connections_t; typedef std::multimap<std::string, pending_connection_t>
pending_connections_t;
pending_connections_t pending_connections; pending_connections_t pending_connections;
// Synchronisation of access to the list of inproc endpoints. // Synchronisation of access to the list of inproc endpoints.
@@ -230,8 +231,16 @@ namespace zmq
// the process that created this context. Used to detect forking. // the process that created this context. Used to detect forking.
pid_t pid; pid_t pid;
#endif #endif
enum side { connect_side, bind_side }; enum side
void connect_inproc_sockets(zmq::socket_base_t *bind_socket_, options_t& bind_options, const pending_connection_t &pending_connection_, side 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 #ifdef ZMQ_HAVE_VMCI
int vmci_fd; int vmci_fd;
@@ -239,7 +248,6 @@ namespace zmq
mutex_t vmci_sync; mutex_t vmci_sync;
#endif #endif
}; };
} }
#endif #endif

View File

@@ -94,8 +94,7 @@ int zmq::curve_client_t::process_handshake_command (msg_t *msg_)
rc = process_error (msg_data, msg_size); rc = process_error (msg_data, msg_size);
else { else {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
errno = EPROTO; errno = EPROTO;
rc = -1; rc = -1;
} }
@@ -126,8 +125,7 @@ zmq::mechanism_t::status_t zmq::curve_client_t::status () const
{ {
if (state == connected) if (state == connected)
return mechanism_t::ready; return mechanism_t::ready;
else else if (state == error_received)
if (state == error_received)
return mechanism_t::error; return mechanism_t::error;
else else
return mechanism_t::handshaking; return mechanism_t::handshaking;
@@ -141,8 +139,7 @@ int zmq::curve_client_t::produce_hello (msg_t *msg_)
rc = tools.produce_hello (msg_->data (), cn_nonce); rc = tools.produce_hello (msg_->data (), cn_nonce);
if (rc == -1) { if (rc == -1) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
// TODO this is somewhat inconsistent: we call init_size, but we may // 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 // not close msg_; i.e. we assume that msg_ is initialized but empty
@@ -164,8 +161,7 @@ int zmq::curve_client_t::process_welcome (const uint8_t *msg_data,
if (rc == -1) { if (rc == -1) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
errno = EPROTO; errno = EPROTO;
return -1; return -1;
@@ -196,8 +192,7 @@ int zmq::curve_client_t::produce_initiate (msg_t *msg_)
if (-1 == rc) { if (-1 == rc) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
// TODO see comment in produce_hello // TODO see comment in produce_hello
return -1; return -1;
@@ -208,8 +203,8 @@ int zmq::curve_client_t::produce_initiate (msg_t *msg_)
return 0; return 0;
} }
int zmq::curve_client_t::process_ready ( int zmq::curve_client_t::process_ready (const uint8_t *msg_data,
const uint8_t *msg_data, size_t msg_size) size_t msg_size)
{ {
if (msg_size < 30) { if (msg_size < 30) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
@@ -229,21 +224,20 @@ int zmq::curve_client_t::process_ready (
alloc_assert (ready_box); alloc_assert (ready_box);
memset (ready_box, 0, crypto_box_BOXZEROBYTES); memset (ready_box, 0, crypto_box_BOXZEROBYTES);
memcpy (ready_box + crypto_box_BOXZEROBYTES, memcpy (ready_box + crypto_box_BOXZEROBYTES, msg_data + 14,
msg_data + 14, clen - crypto_box_BOXZEROBYTES); clen - crypto_box_BOXZEROBYTES);
memcpy (ready_nonce, "CurveZMQREADY---", 16); memcpy (ready_nonce, "CurveZMQREADY---", 16);
memcpy (ready_nonce + 16, msg_data + 6, 8); 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, int rc = crypto_box_open_afternm (ready_plaintext, ready_box, clen,
clen, ready_nonce, cn_precom); ready_nonce, cn_precom);
free (ready_box); free (ready_box);
if (rc != 0) { if (rc != 0) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
errno = EPROTO; errno = EPROTO;
return -1; return -1;
} }
@@ -254,8 +248,7 @@ int zmq::curve_client_t::process_ready (
if (rc == 0) if (rc == 0)
state = connected; state = connected;
else else {
{
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_METADATA); session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_METADATA);
errno = EPROTO; errno = EPROTO;
@@ -264,8 +257,8 @@ int zmq::curve_client_t::process_ready (
return rc; return rc;
} }
int zmq::curve_client_t::process_error ( int zmq::curve_client_t::process_error (const uint8_t *msg_data,
const uint8_t *msg_data, size_t msg_size) size_t msg_size)
{ {
if (state != expect_welcome && state != expect_ready) { if (state != expect_welcome && state != expect_ready) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (

View File

@@ -38,14 +38,12 @@
namespace zmq namespace zmq
{ {
class msg_t; class msg_t;
class session_base_t; class session_base_t;
class curve_client_t : public curve_mechanism_base_t class curve_client_t : public curve_mechanism_base_t
{ {
public: public:
curve_client_t (session_base_t *session_, const options_t &options_); curve_client_t (session_base_t *session_, const options_t &options_);
virtual ~curve_client_t (); virtual ~curve_client_t ();
@@ -57,8 +55,8 @@ namespace zmq
virtual status_t status () const; virtual status_t status () const;
private: private:
enum state_t
enum state_t { {
send_hello, send_hello,
expect_welcome, expect_welcome,
send_initiate, send_initiate,
@@ -79,7 +77,6 @@ namespace zmq
int process_ready (const uint8_t *cmd_data, size_t data_size); int process_ready (const uint8_t *cmd_data, size_t data_size);
int process_error (const uint8_t *cmd_data, size_t data_size); int process_error (const uint8_t *cmd_data, size_t data_size);
}; };
} }
#endif #endif

View File

@@ -153,8 +153,7 @@ struct curve_client_tools_t
// Create vouch = Box [C',S](C->S') // Create vouch = Box [C',S](C->S')
memset (vouch_plaintext, 0, crypto_box_ZEROBYTES); memset (vouch_plaintext, 0, crypto_box_ZEROBYTES);
memcpy (vouch_plaintext + crypto_box_ZEROBYTES, cn_public, 32); memcpy (vouch_plaintext + crypto_box_ZEROBYTES, cn_public, 32);
memcpy (vouch_plaintext + crypto_box_ZEROBYTES + 32, server_key, memcpy (vouch_plaintext + crypto_box_ZEROBYTES + 32, server_key, 32);
32);
memcpy (vouch_nonce, "VOUCH---", 8); memcpy (vouch_nonce, "VOUCH---", 8);
randombytes (vouch_nonce + 8, 16); randombytes (vouch_nonce + 8, 16);
@@ -165,8 +164,8 @@ struct curve_client_tools_t
return -1; return -1;
uint8_t initiate_nonce[crypto_box_NONCEBYTES]; uint8_t initiate_nonce[crypto_box_NONCEBYTES];
uint8_t *initiate_box = (uint8_t *) malloc ( uint8_t *initiate_box =
crypto_box_BOXZEROBYTES + 144 + metadata_length); (uint8_t *) malloc (crypto_box_BOXZEROBYTES + 144 + metadata_length);
alloc_assert (initiate_box); alloc_assert (initiate_box);
uint8_t *initiate_plaintext = uint8_t *initiate_plaintext =
(uint8_t *) malloc (crypto_box_ZEROBYTES + 128 + metadata_length); (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') // Create Box [C + vouch + metadata](C'->S')
memset (initiate_plaintext, 0, crypto_box_ZEROBYTES); memset (initiate_plaintext, 0, crypto_box_ZEROBYTES);
memcpy (initiate_plaintext + crypto_box_ZEROBYTES, public_key, memcpy (initiate_plaintext + crypto_box_ZEROBYTES, public_key, 32);
32);
memcpy (initiate_plaintext + crypto_box_ZEROBYTES + 32, vouch_nonce + 8, memcpy (initiate_plaintext + crypto_box_ZEROBYTES + 32, vouch_nonce + 8,
16); 16);
memcpy (initiate_plaintext + crypto_box_ZEROBYTES + 48, memcpy (initiate_plaintext + crypto_box_ZEROBYTES + 48,

View File

@@ -68,14 +68,14 @@ int zmq::curve_mechanism_base_t::encode (msg_t *msg_)
memset (message_plaintext, 0, crypto_box_ZEROBYTES); memset (message_plaintext, 0, crypto_box_ZEROBYTES);
message_plaintext[crypto_box_ZEROBYTES] = flags; message_plaintext[crypto_box_ZEROBYTES] = flags;
memcpy (message_plaintext + crypto_box_ZEROBYTES + 1, memcpy (message_plaintext + crypto_box_ZEROBYTES + 1, msg_->data (),
msg_->data (), msg_->size ()); msg_->size ());
uint8_t *message_box = static_cast<uint8_t *> (malloc (mlen)); uint8_t *message_box = static_cast<uint8_t *> (malloc (mlen));
alloc_assert (message_box); alloc_assert (message_box);
int rc = crypto_box_afternm (message_box, message_plaintext, int rc = crypto_box_afternm (message_box, message_plaintext, mlen,
mlen, message_nonce, cn_precom); message_nonce, cn_precom);
zmq_assert (rc == 0); zmq_assert (rc == 0);
rc = msg_->close (); rc = msg_->close ();
@@ -144,8 +144,8 @@ int zmq::curve_mechanism_base_t::decode (msg_t *msg_)
alloc_assert (message_box); alloc_assert (message_box);
memset (message_box, 0, crypto_box_BOXZEROBYTES); memset (message_box, 0, crypto_box_BOXZEROBYTES);
memcpy (message_box + crypto_box_BOXZEROBYTES, memcpy (message_box + crypto_box_BOXZEROBYTES, message + 16,
message + 16, msg_->size () - 16); msg_->size () - 16);
rc = crypto_box_open_afternm (message_plaintext, message_box, clen, rc = crypto_box_open_afternm (message_plaintext, message_box, clen,
message_nonce, cn_precom); message_nonce, cn_precom);
@@ -162,11 +162,9 @@ int zmq::curve_mechanism_base_t::decode (msg_t *msg_)
if (flags & 0x02) if (flags & 0x02)
msg_->set_flags (msg_t::command); msg_->set_flags (msg_t::command);
memcpy (msg_->data (), memcpy (msg_->data (), message_plaintext + crypto_box_ZEROBYTES + 1,
message_plaintext + crypto_box_ZEROBYTES + 1,
msg_->size ()); msg_->size ());
} } else {
else {
// CURVE I : connection key used for MESSAGE is wrong // CURVE I : connection key used for MESSAGE is wrong
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC); session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);

View File

@@ -152,7 +152,8 @@ int zmq::curve_server_t::process_hello (msg_t *msg_)
if (size != 200) { if (size != 200) {
session->get_socket ()->event_handshake_failed_protocol ( 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; errno = EPROTO;
return -1; return -1;
} }
@@ -163,7 +164,8 @@ int zmq::curve_server_t::process_hello (msg_t *msg_)
if (major != 1 || minor != 0) { if (major != 1 || minor != 0) {
// CURVE I: client HELLO has unknown version number // CURVE I: client HELLO has unknown version number
session->get_socket ()->event_handshake_failed_protocol ( 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; errno = EPROTO;
return -1; return -1;
} }
@@ -210,18 +212,16 @@ int zmq::curve_server_t::produce_welcome (msg_t *msg_)
// Generate cookie = Box [C' + s'](t) // Generate cookie = Box [C' + s'](t)
memset (cookie_plaintext, 0, crypto_secretbox_ZEROBYTES); memset (cookie_plaintext, 0, crypto_secretbox_ZEROBYTES);
memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES, memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES, cn_client, 32);
cn_client, 32); memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES + 32, cn_secret, 32);
memcpy (cookie_plaintext + crypto_secretbox_ZEROBYTES + 32,
cn_secret, 32);
// Generate fresh cookie key // Generate fresh cookie key
randombytes (cookie_key, crypto_secretbox_KEYBYTES); randombytes (cookie_key, crypto_secretbox_KEYBYTES);
// Encrypt using symmetric cookie key // Encrypt using symmetric cookie key
int rc = crypto_secretbox (cookie_ciphertext, cookie_plaintext, int rc =
sizeof cookie_plaintext, crypto_secretbox (cookie_ciphertext, cookie_plaintext,
cookie_nonce, cookie_key); sizeof cookie_plaintext, cookie_nonce, cookie_key);
zmq_assert (rc == 0); zmq_assert (rc == 0);
uint8_t welcome_nonce[crypto_box_NONCEBYTES]; uint8_t welcome_nonce[crypto_box_NONCEBYTES];
@@ -236,8 +236,8 @@ int zmq::curve_server_t::produce_welcome (msg_t *msg_)
// Create 144-byte Box [S' + cookie](S->C') // Create 144-byte Box [S' + cookie](S->C')
memset (welcome_plaintext, 0, crypto_box_ZEROBYTES); memset (welcome_plaintext, 0, crypto_box_ZEROBYTES);
memcpy (welcome_plaintext + crypto_box_ZEROBYTES, cn_public, 32); memcpy (welcome_plaintext + crypto_box_ZEROBYTES, cn_public, 32);
memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 32, memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 32, cookie_nonce + 8,
cookie_nonce + 8, 16); 16);
memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 48, memcpy (welcome_plaintext + crypto_box_ZEROBYTES + 48,
cookie_ciphertext + crypto_secretbox_BOXZEROBYTES, 80); cookie_ciphertext + crypto_secretbox_BOXZEROBYTES, 80);
@@ -312,7 +312,8 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_)
// Check cookie plain text is as expected [C' + s'] // Check cookie plain text is as expected [C' + s']
if (memcmp (cookie_plaintext + crypto_secretbox_ZEROBYTES, cn_client, 32) 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 // TODO this case is very hard to test, as it would require a modified
// client that knows the server's secret temporary cookie key // client that knows the server's secret temporary cookie key
@@ -331,15 +332,15 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_)
// Open Box [C + vouch + metadata](C'->S') // Open Box [C + vouch + metadata](C'->S')
memset (initiate_box, 0, crypto_box_BOXZEROBYTES); memset (initiate_box, 0, crypto_box_BOXZEROBYTES);
memcpy (initiate_box + crypto_box_BOXZEROBYTES, memcpy (initiate_box + crypto_box_BOXZEROBYTES, initiate + 113,
initiate + 113, clen - crypto_box_BOXZEROBYTES); clen - crypto_box_BOXZEROBYTES);
memcpy (initiate_nonce, "CurveZMQINITIATE", 16); memcpy (initiate_nonce, "CurveZMQINITIATE", 16);
memcpy (initiate_nonce + 16, initiate + 105, 8); 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, rc = crypto_box_open (initiate_plaintext, initiate_box, clen,
clen, initiate_nonce, cn_client, cn_secret); initiate_nonce, cn_client, cn_secret);
if (rc != 0) { if (rc != 0) {
// CURVE I: cannot open client INITIATE // CURVE I: cannot open client INITIATE
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
@@ -360,11 +361,10 @@ int zmq::curve_server_t::process_initiate (msg_t *msg_)
initiate_plaintext + crypto_box_ZEROBYTES + 48, 80); initiate_plaintext + crypto_box_ZEROBYTES + 48, 80);
memcpy (vouch_nonce, "VOUCH---", 8); memcpy (vouch_nonce, "VOUCH---", 8);
memcpy (vouch_nonce + 8, memcpy (vouch_nonce + 8, initiate_plaintext + crypto_box_ZEROBYTES + 32,
initiate_plaintext + crypto_box_ZEROBYTES + 32, 16); 16);
rc = crypto_box_open (vouch_plaintext, vouch_box, rc = crypto_box_open (vouch_plaintext, vouch_box, sizeof vouch_box,
sizeof vouch_box,
vouch_nonce, client_key, cn_secret); vouch_nonce, client_key, cn_secret);
if (rc != 0) { if (rc != 0) {
// CURVE I: cannot open client INITIATE vouch // CURVE I: cannot open client INITIATE vouch

View File

@@ -46,7 +46,6 @@ namespace zmq
public curve_mechanism_base_t public curve_mechanism_base_t
{ {
public: public:
curve_server_t (session_base_t *session_, curve_server_t (session_base_t *session_,
const std::string &peer_address_, const std::string &peer_address_,
const options_t &options_); const options_t &options_);
@@ -59,7 +58,6 @@ namespace zmq
virtual int decode (msg_t *msg_); virtual int decode (msg_t *msg_);
private: private:
// Our secret key (s) // Our secret key (s)
uint8_t secret_key[crypto_box_SECRETKEYBYTES]; uint8_t secret_key[crypto_box_SECRETKEYBYTES];
@@ -86,7 +84,6 @@ namespace zmq
#ifdef _MSC_VER #ifdef _MSC_VER
#pragma warning(pop) #pragma warning(pop)
#endif #endif
} }
#endif #endif

View File

@@ -39,7 +39,6 @@
namespace zmq namespace zmq
{ {
// dbuffer is a single-producer single-consumer double-buffer // dbuffer is a single-producer single-consumer double-buffer
// implementation. // implementation.
// //
@@ -59,11 +58,10 @@ namespace zmq
template <> class dbuffer_t<msg_t> template <> class dbuffer_t<msg_t>
{ {
public: public:
inline dbuffer_t () :
inline dbuffer_t () back (&storage[0]),
: back (&storage[0]) front (&storage[1]),
, front (&storage[1]) has_msg (false)
, has_msg (false)
{ {
back->init (); back->init ();
front->init (); front->init ();
@@ -84,8 +82,7 @@ namespace zmq
zmq_assert (back->check ()); zmq_assert (back->check ());
if (sync.try_lock ()) if (sync.try_lock ()) {
{
std::swap (back, front); std::swap (back, front);
has_msg = true; has_msg = true;

View File

@@ -67,12 +67,14 @@ void zmq::dealer_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_)
lb.attach (pipe_); lb.attach (pipe_);
} }
int zmq::dealer_t::xsetsockopt (int option_, const void *optval_, int zmq::dealer_t::xsetsockopt (int option_,
const void *optval_,
size_t optvallen_) size_t optvallen_)
{ {
bool is_int = (optvallen_ == sizeof (int)); bool is_int = (optvallen_ == sizeof (int));
int value = 0; int value = 0;
if (is_int) memcpy(&value, optval_, sizeof (int)); if (is_int)
memcpy (&value, optval_, sizeof (int));
switch (option_) { switch (option_) {
case ZMQ_PROBE_ROUTER: case ZMQ_PROBE_ROUTER:

View File

@@ -37,23 +37,19 @@
namespace zmq namespace zmq
{ {
class ctx_t; class ctx_t;
class msg_t; class msg_t;
class pipe_t; class pipe_t;
class io_thread_t; class io_thread_t;
class socket_base_t; class socket_base_t;
class dealer_t : class dealer_t : public socket_base_t
public socket_base_t
{ {
public: public:
dealer_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); dealer_t (zmq::ctx_t *parent_, uint32_t tid_, int sid);
~dealer_t (); ~dealer_t ();
protected: protected:
// Overrides of functions from socket_base_t. // Overrides of functions from socket_base_t.
void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_);
int xsetsockopt (int option_, const void *optval_, size_t optvallen_); int xsetsockopt (int option_, const void *optval_, size_t optvallen_);
@@ -71,7 +67,6 @@ namespace zmq
int recvpipe (zmq::msg_t *msg_, zmq::pipe_t **pipe_); int recvpipe (zmq::msg_t *msg_, zmq::pipe_t **pipe_);
private: private:
// Messages are fair-queued from inbound pipes. And load-balanced to // Messages are fair-queued from inbound pipes. And load-balanced to
// the outbound pipes. // the outbound pipes.
fq_t fq; fq_t fq;
@@ -83,7 +78,6 @@ namespace zmq
dealer_t (const dealer_t &); dealer_t (const dealer_t &);
const dealer_t &operator= (const dealer_t &); const dealer_t &operator= (const dealer_t &);
}; };
} }
#endif #endif

View File

@@ -58,7 +58,6 @@ namespace zmq
class decoder_base_t : public i_decoder class decoder_base_t : public i_decoder
{ {
public: public:
explicit decoder_base_t (A *allocator_) : explicit decoder_base_t (A *allocator_) :
next (NULL), next (NULL),
read_pos (NULL), read_pos (NULL),
@@ -70,10 +69,7 @@ namespace zmq
// The destructor doesn't have to be virtual. It is made virtual // The destructor doesn't have to be virtual. It is made virtual
// just to keep ICC and code checking tools from complaining. // just to keep ICC and code checking tools from complaining.
virtual ~decoder_base_t () virtual ~decoder_base_t () { allocator->deallocate (); }
{
allocator->deallocate ();
}
// Returns a buffer to be filled with binary data. // Returns a buffer to be filled with binary data.
void get_buffer (unsigned char **data_, std::size_t *size_) void get_buffer (unsigned char **data_, std::size_t *size_)
@@ -104,7 +100,8 @@ namespace zmq
// whole message was decoded or 0 when more data is required. // whole message was decoded or 0 when more data is required.
// On error, -1 is returned and errno set accordingly. // On error, -1 is returned and errno set accordingly.
// Number of bytes processed is returned in bytes_used_. // Number of bytes processed is returned in bytes_used_.
int decode (const unsigned char *data_, std::size_t size_, int decode (const unsigned char *data_,
std::size_t size_,
std::size_t &bytes_used_) std::size_t &bytes_used_)
{ {
bytes_used_ = 0; bytes_used_ = 0;
@@ -159,7 +156,6 @@ namespace zmq
} }
protected: protected:
// Prototype of state machine action. Action should return false if // Prototype of state machine action. Action should return false if
// it is unable to push the data to the system. // it is unable to push the data to the system.
typedef int (T::*step_t) (unsigned char const *); typedef int (T::*step_t) (unsigned char const *);
@@ -174,7 +170,6 @@ namespace zmq
} }
private: private:
// Next step. If set to NULL, it means that associated data stream // 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 // is dead. Note that there can be still data in the process in such
// case. // case.

View File

@@ -34,16 +34,20 @@
#include "msg.hpp" #include "msg.hpp"
zmq::shared_message_memory_allocator::shared_message_memory_allocator (std::size_t bufsize_) : zmq::shared_message_memory_allocator::shared_message_memory_allocator (
std::size_t bufsize_) :
buf (NULL), buf (NULL),
bufsize (0), bufsize (0),
max_size (bufsize_), max_size (bufsize_),
msg_content (NULL), msg_content (NULL),
maxCounters (static_cast <size_t> (std::ceil (static_cast <double> (max_size) / static_cast <double> (msg_t::max_vsm_size)))) maxCounters (static_cast<size_t> (
std::ceil (static_cast<double> (max_size)
/ static_cast<double> (msg_t::max_vsm_size))))
{ {
} }
zmq::shared_message_memory_allocator::shared_message_memory_allocator (std::size_t bufsize_, std::size_t maxMessages) : zmq::shared_message_memory_allocator::shared_message_memory_allocator (
std::size_t bufsize_, std::size_t maxMessages) :
buf (NULL), buf (NULL),
bufsize (0), bufsize (0),
max_size (bufsize_), max_size (bufsize_),
@@ -61,7 +65,8 @@ unsigned char* zmq::shared_message_memory_allocator::allocate ()
{ {
if (buf) { if (buf) {
// release reference count to couple lifetime to messages // release reference count to couple lifetime to messages
zmq::atomic_counter_t* c = reinterpret_cast<zmq::atomic_counter_t* >(buf); zmq::atomic_counter_t *c =
reinterpret_cast<zmq::atomic_counter_t *> (buf);
// if refcnt drops to 0, there are no message using the buffer // if refcnt drops to 0, there are no message using the buffer
// because either all messages have been closed or only vsm-messages // because either all messages have been closed or only vsm-messages
@@ -77,8 +82,8 @@ unsigned char* zmq::shared_message_memory_allocator::allocate ()
if (!buf) { if (!buf) {
// allocate memory for reference counters together with reception buffer // allocate memory for reference counters together with reception buffer
std::size_t const allocationsize = std::size_t const allocationsize =
max_size + sizeof (zmq::atomic_counter_t) + max_size + sizeof (zmq::atomic_counter_t)
maxCounters * sizeof (zmq::msg_t::content_t); + maxCounters * sizeof (zmq::msg_t::content_t);
buf = static_cast<unsigned char *> (std::malloc (allocationsize)); buf = static_cast<unsigned char *> (std::malloc (allocationsize));
alloc_assert (buf); alloc_assert (buf);
@@ -86,12 +91,14 @@ unsigned char* zmq::shared_message_memory_allocator::allocate ()
new (buf) atomic_counter_t (1); new (buf) atomic_counter_t (1);
} else { } else {
// release reference count to couple lifetime to messages // release reference count to couple lifetime to messages
zmq::atomic_counter_t *c = reinterpret_cast <zmq::atomic_counter_t *> (buf); zmq::atomic_counter_t *c =
reinterpret_cast<zmq::atomic_counter_t *> (buf);
c->set (1); c->set (1);
} }
bufsize = max_size; bufsize = max_size;
msg_content = reinterpret_cast <zmq::msg_t::content_t*> (buf + sizeof (atomic_counter_t) + max_size); msg_content = reinterpret_cast<zmq::msg_t::content_t *> (
buf + sizeof (atomic_counter_t) + max_size);
return buf + sizeof (zmq::atomic_counter_t); return buf + sizeof (zmq::atomic_counter_t);
} }

View File

@@ -50,29 +50,16 @@ namespace zmq
alloc_assert (buf); alloc_assert (buf);
} }
~c_single_allocator () ~c_single_allocator () { std::free (buf); }
{
std::free (buf);
}
unsigned char* allocate () unsigned char *allocate () { return buf; }
{
return buf;
}
void deallocate () void deallocate () {}
{
}
std::size_t size () const std::size_t size () const { return bufsize; }
{
return bufsize; void resize (std::size_t new_size) { bufsize = new_size; }
}
void resize (std::size_t new_size)
{
bufsize = new_size;
}
private: private:
std::size_t bufsize; std::size_t bufsize;
unsigned char *buf; unsigned char *buf;
@@ -96,7 +83,8 @@ namespace zmq
explicit shared_message_memory_allocator (std::size_t bufsize_); explicit shared_message_memory_allocator (std::size_t bufsize_);
// Create an allocator for a maximum number of messages // 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 (std::size_t bufsize_,
std::size_t maxMessages);
~shared_message_memory_allocator (); ~shared_message_memory_allocator ();
@@ -123,25 +111,13 @@ namespace zmq
unsigned char *data (); unsigned char *data ();
// Return pointer to the first byte of the buffer. // Return pointer to the first byte of the buffer.
unsigned char* buffer () unsigned char *buffer () { return buf; }
{
return buf;
}
void resize (std::size_t new_size) void resize (std::size_t new_size) { bufsize = new_size; }
{
bufsize = new_size;
}
zmq::msg_t::content_t* provide_content () zmq::msg_t::content_t *provide_content () { return msg_content; }
{
return msg_content;
}
void advance_content () void advance_content () { msg_content++; }
{
msg_content++;
}
private: private:
unsigned char *buf; unsigned char *buf;

View File

@@ -153,7 +153,6 @@ int zmq::devpoll_t::max_fds ()
void zmq::devpoll_t::loop () void zmq::devpoll_t::loop ()
{ {
while (!stopping) { while (!stopping) {
struct pollfd ev_buf[max_io_events]; struct pollfd ev_buf[max_io_events];
struct dvpoll poll_req; struct dvpoll poll_req;
@@ -179,7 +178,6 @@ void zmq::devpoll_t::loop ()
errno_assert (n != -1); errno_assert (n != -1);
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
fd_entry_t *fd_ptr = &fd_table[ev_buf[i].fd]; fd_entry_t *fd_ptr = &fd_table[ev_buf[i].fd];
if (!fd_ptr->valid || !fd_ptr->accepted) if (!fd_ptr->valid || !fd_ptr->accepted)
continue; continue;

View File

@@ -43,7 +43,6 @@
namespace zmq 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.
@@ -51,7 +50,6 @@ namespace zmq
class devpoll_t : public poller_base_t class devpoll_t : public poller_base_t
{ {
public: public:
typedef fd_t handle_t; typedef fd_t handle_t;
devpoll_t (const ctx_t &ctx_); devpoll_t (const ctx_t &ctx_);
@@ -70,7 +68,6 @@ namespace zmq
static int max_fds (); static int max_fds ();
private: private:
// Main worker thread routine. // Main worker thread routine.
static void worker_routine (void *arg_); static void worker_routine (void *arg_);
@@ -111,7 +108,6 @@ namespace zmq
}; };
typedef devpoll_t poller_t; typedef devpoll_t poller_t;
} }
#endif #endif

View File

@@ -107,9 +107,7 @@ int zmq::dgram_t::xsend (msg_t *msg_)
// Expect one more message frame. // Expect one more message frame.
more_out = true; more_out = true;
} } else {
else {
// dgram messages are two part only, reject part if more is set // dgram messages are two part only, reject part if more is set
if (msg_->flags () & msg_t::more) { if (msg_->flags () & msg_t::more) {
errno = EINVAL; errno = EINVAL;

View File

@@ -36,17 +36,14 @@
namespace zmq namespace zmq
{ {
class ctx_t; class ctx_t;
class msg_t; class msg_t;
class pipe_t; class pipe_t;
class io_thread_t; class io_thread_t;
class dgram_t : class dgram_t : public socket_base_t
public socket_base_t
{ {
public: public:
dgram_t (zmq::ctx_t *parent_, uint32_t tid_, int sid); dgram_t (zmq::ctx_t *parent_, uint32_t tid_, int sid);
~dgram_t (); ~dgram_t ();
@@ -62,7 +59,6 @@ namespace zmq
void xpipe_terminated (zmq::pipe_t *pipe_); void xpipe_terminated (zmq::pipe_t *pipe_);
private: private:
zmq::pipe_t *pipe; zmq::pipe_t *pipe;
zmq::pipe_t *last_in; zmq::pipe_t *last_in;
@@ -75,7 +71,6 @@ namespace zmq
dgram_t (const dgram_t &); dgram_t (const dgram_t &);
const dgram_t &operator= (const dgram_t &); const dgram_t &operator= (const dgram_t &);
}; };
} }
#endif #endif

View File

@@ -134,7 +134,8 @@ int zmq::dish_t::xleave (const char* group_)
return -1; 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 ()) { if (it == subscriptions.end ()) {
errno = EINVAL; errno = EINVAL;
@@ -186,7 +187,6 @@ int zmq::dish_t::xrecv (msg_t *msg_)
} }
while (true) { while (true) {
// Get a message using fair queueing algorithm. // Get a message using fair queueing algorithm.
int rc = fq.recv (msg_); int rc = fq.recv (msg_);
@@ -196,7 +196,8 @@ int zmq::dish_t::xrecv (msg_t *msg_)
return -1; return -1;
// Filtering non matching messages // 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 ()) if (it != subscriptions.end ())
return 0; return 0;
} }
@@ -221,7 +222,8 @@ bool zmq::dish_t::xhas_in ()
} }
// Filtering non matching messages // 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 ()) { if (it != subscriptions.end ()) {
has_message = true; has_message = true;
return true; return true;
@@ -236,7 +238,8 @@ const zmq::blob_t &zmq::dish_t::get_credential () const
void zmq::dish_t::send_subscriptions (pipe_t *pipe_) 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; msg_t msg;
int rc = msg.init_join (); int rc = msg.init_join ();
errno_assert (rc == 0); errno_assert (rc == 0);
@@ -252,8 +255,10 @@ void zmq::dish_t::send_subscriptions (pipe_t *pipe_)
pipe_->flush (); pipe_->flush ();
} }
zmq::dish_session_t::dish_session_t (io_thread_t *io_thread_, bool connect_, zmq::dish_session_t::dish_session_t (io_thread_t *io_thread_,
socket_base_t *socket_, const options_t &options_, bool connect_,
socket_base_t *socket_,
const options_t &options_,
address_t *addr_) : address_t *addr_) :
session_base_t (io_thread_, connect_, socket_, options_, addr_), session_base_t (io_thread_, connect_, socket_, options_, addr_),
state (group) state (group)
@@ -283,8 +288,7 @@ int zmq::dish_session_t::push_msg (msg_t *msg_)
int rc = msg_->init (); int rc = msg_->init ();
errno_assert (rc == 0); errno_assert (rc == 0);
return 0; return 0;
} } else {
else {
const char *group_setting = msg_->group (); const char *group_setting = msg_->group ();
int rc; int rc;
if (group_setting[0] != 0) if (group_setting[0] != 0)
@@ -334,8 +338,7 @@ int zmq::dish_session_t::pull_msg (msg_t *msg_)
errno_assert (rc == 0); errno_assert (rc == 0);
offset = 5; offset = 5;
memcpy (command.data (), "\4JOIN", 5); memcpy (command.data (), "\4JOIN", 5);
} } else {
else {
rc = command.init_size (group_length + 6); rc = command.init_size (group_length + 6);
errno_assert (rc == 0); errno_assert (rc == 0);
offset = 6; offset = 6;

View File

@@ -41,21 +41,17 @@
namespace zmq namespace zmq
{ {
class ctx_t; class ctx_t;
class pipe_t; class pipe_t;
class io_thread_t; class io_thread_t;
class dish_t : class dish_t : public socket_base_t
public socket_base_t
{ {
public: public:
dish_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); dish_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_);
~dish_t (); ~dish_t ();
protected: protected:
// Overrides of functions from socket_base_t. // Overrides of functions from socket_base_t.
void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_);
int xsend (zmq::msg_t *msg_); int xsend (zmq::msg_t *msg_);
@@ -69,8 +65,8 @@ namespace zmq
void xpipe_terminated (zmq::pipe_t *pipe_); void xpipe_terminated (zmq::pipe_t *pipe_);
int xjoin (const char *group_); int xjoin (const char *group_);
int xleave (const char *group_); int xleave (const char *group_);
private:
private:
// Send subscriptions to a pipe // Send subscriptions to a pipe
void send_subscriptions (pipe_t *pipe_); void send_subscriptions (pipe_t *pipe_);
@@ -96,9 +92,10 @@ namespace zmq
class dish_session_t : public session_base_t class dish_session_t : public session_base_t
{ {
public: public:
dish_session_t (zmq::io_thread_t *io_thread_,
dish_session_t (zmq::io_thread_t *io_thread_, bool connect_, bool connect_,
zmq::socket_base_t *socket_, const options_t &options_, zmq::socket_base_t *socket_,
const options_t &options_,
address_t *addr_); address_t *addr_);
~dish_session_t (); ~dish_session_t ();
@@ -108,8 +105,8 @@ namespace zmq
void reset (); void reset ();
private: private:
enum
enum { {
group, group,
body body
} state; } state;
@@ -119,7 +116,6 @@ namespace zmq
dish_session_t (const dish_session_t &); dish_session_t (const dish_session_t &);
const dish_session_t &operator= (const dish_session_t &); const dish_session_t &operator= (const dish_session_t &);
}; };
} }
#endif #endif

View File

@@ -34,11 +34,7 @@
#include "msg.hpp" #include "msg.hpp"
#include "likely.hpp" #include "likely.hpp"
zmq::dist_t::dist_t () : zmq::dist_t::dist_t () : matching (0), active (0), eligible (0), more (false)
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.push_back (pipe_);
pipes.swap (eligible, pipes.size () - 1); pipes.swap (eligible, pipes.size () - 1);
eligible++; eligible++;
} } else {
else {
pipes.push_back (pipe_); pipes.push_back (pipe_);
pipes.swap (active, pipes.size () - 1); pipes.swap (active, pipes.size () - 1);
active++; active++;
@@ -231,5 +226,3 @@ bool zmq::dist_t::check_hwm ()
return true; return true;
} }

View File

@@ -37,7 +37,6 @@
namespace zmq namespace zmq
{ {
class pipe_t; class pipe_t;
class msg_t; class msg_t;
@@ -46,7 +45,6 @@ namespace zmq
class dist_t class dist_t
{ {
public: public:
dist_t (); dist_t ();
~dist_t (); ~dist_t ();
@@ -81,7 +79,6 @@ namespace zmq
bool check_hwm (); bool check_hwm ();
private: private:
// Write the message to the pipe. Make the pipe inactive if writing // Write the message to the pipe. Make the pipe inactive if writing
// fails. In such a case false is returned. // fails. In such a case false is returned.
bool write (zmq::pipe_t *pipe_, zmq::msg_t *msg_); bool write (zmq::pipe_t *pipe_, zmq::msg_t *msg_);
@@ -114,7 +111,6 @@ namespace zmq
dist_t (const dist_t &); dist_t (const dist_t &);
const dist_t &operator= (const dist_t &); const dist_t &operator= (const dist_t &);
}; };
} }
#endif #endif

View File

@@ -47,7 +47,6 @@
namespace zmq namespace zmq
{ {
// Helper base class for encoders. It implements the state machine that // Helper base class for encoders. It implements the state machine that
// fills the outgoing buffer. Derived classes should implement individual // fills the outgoing buffer. Derived classes should implement individual
// state machine actions. // state machine actions.
@@ -55,7 +54,6 @@ namespace zmq
template <typename T> class encoder_base_t : public i_encoder template <typename T> class encoder_base_t : public i_encoder
{ {
public: public:
inline encoder_base_t (size_t bufsize_) : inline encoder_base_t (size_t bufsize_) :
write_pos (0), write_pos (0),
to_write (0), to_write (0),
@@ -70,10 +68,7 @@ namespace zmq
// The destructor doesn't have to be virtual. It is made virtual // The destructor doesn't have to be virtual. It is made virtual
// just to keep ICC and code checking tools from complaining. // just to keep ICC and code checking tools from complaining.
inline virtual ~encoder_base_t () inline virtual ~encoder_base_t () { free (buf); }
{
free (buf);
}
// The function returns a batch of binary data. The data // The function returns a batch of binary data. The data
// are filled to a supplied buffer. If no buffer is supplied (data_ // are filled to a supplied buffer. If no buffer is supplied (data_
@@ -88,7 +83,6 @@ namespace zmq
size_t pos = 0; size_t pos = 0;
while (pos < buffersize) { while (pos < buffersize) {
// If there are no more data to return, run the state machine. // If there are no more data to return, run the state machine.
// If there are still no data, return what we already have // If there are still no data, return what we already have
// in the buffer. // in the buffer.
@@ -142,14 +136,15 @@ namespace zmq
} }
protected: protected:
// Prototype of state machine action. // Prototype of state machine action.
typedef void (T::*step_t) (); typedef void (T::*step_t) ();
// This function should be called from derived class to write the data // This function should be called from derived class to write the data
// to the buffer and schedule next state machine action. // to the buffer and schedule next state machine action.
inline void next_step (void *write_pos_, size_t to_write_, inline void next_step (void *write_pos_,
step_t next_, bool new_msg_flag_) size_t to_write_,
step_t next_,
bool new_msg_flag_)
{ {
write_pos = (unsigned char *) write_pos_; write_pos = (unsigned char *) write_pos_;
to_write = to_write_; to_write = to_write_;
@@ -158,7 +153,6 @@ namespace zmq
} }
private: private:
// Where to get the data to write from. // Where to get the data to write from.
unsigned char *write_pos; unsigned char *write_pos;
@@ -179,11 +173,8 @@ namespace zmq
void operator= (const encoder_base_t &); void operator= (const encoder_base_t &);
protected: protected:
msg_t *in_progress; msg_t *in_progress;
}; };
} }
#endif #endif

View File

@@ -44,9 +44,7 @@
#include "config.hpp" #include "config.hpp"
#include "i_poll_events.hpp" #include "i_poll_events.hpp"
zmq::epoll_t::epoll_t (const zmq::ctx_t &ctx_) : zmq::epoll_t::epoll_t (const zmq::ctx_t &ctx_) : ctx (ctx_), stopping (false)
ctx(ctx_),
stopping (false)
{ {
#ifdef ZMQ_USE_EPOLL_CLOEXEC #ifdef ZMQ_USE_EPOLL_CLOEXEC
// Setting this option result in sane behaviour when exec() functions // Setting this option result in sane behaviour when exec() functions
@@ -65,7 +63,8 @@ zmq::epoll_t::~epoll_t ()
worker.stop (); worker.stop ();
close (epoll_fd); close (epoll_fd);
for (retired_t::iterator it = retired.begin (); it != retired.end (); ++it) { for (retired_t::iterator it = retired.begin (); it != retired.end ();
++it) {
LIBZMQ_DELETE (*it); LIBZMQ_DELETE (*it);
} }
} }
@@ -159,7 +158,6 @@ void zmq::epoll_t::loop ()
epoll_event ev_buf[max_io_events]; epoll_event ev_buf[max_io_events];
while (!stopping) { while (!stopping) {
// Execute any due timers. // Execute any due timers.
int timeout = (int) execute_timers (); int timeout = (int) execute_timers ();
@@ -190,7 +188,8 @@ void zmq::epoll_t::loop ()
// Destroy retired event sources. // Destroy retired event sources.
retired_sync.lock (); retired_sync.lock ();
for (retired_t::iterator it = retired.begin (); it != retired.end (); ++it) { for (retired_t::iterator it = retired.begin (); it != retired.end ();
++it) {
LIBZMQ_DELETE (*it); LIBZMQ_DELETE (*it);
} }
retired.clear (); retired.clear ();

View File

@@ -45,7 +45,6 @@
namespace zmq namespace zmq
{ {
struct i_poll_events; struct i_poll_events;
// This class implements socket polling mechanism using the Linux-specific // This class implements socket polling mechanism using the Linux-specific
@@ -54,7 +53,6 @@ namespace zmq
class epoll_t : public poller_base_t class epoll_t : public poller_base_t
{ {
public: public:
typedef void *handle_t; typedef void *handle_t;
epoll_t (const ctx_t &ctx_); epoll_t (const ctx_t &ctx_);
@@ -73,7 +71,6 @@ namespace zmq
static int max_fds (); static int max_fds ();
private: private:
// Main worker thread routine. // Main worker thread routine.
static void worker_routine (void *arg_); static void worker_routine (void *arg_);
@@ -111,7 +108,6 @@ namespace zmq
}; };
typedef epoll_t poller_t; typedef epoll_t poller_t;
} }
#endif #endif

View File

@@ -100,123 +100,143 @@ 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. // 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 // Investigate whether there's a way to convert it into the string
// automatically (wsaError->HRESULT->string?). // automatically (wsaError->HRESULT->string?).
return return (no_ == WSABASEERR)
(no_ == WSABASEERR) ? ? "No Error"
"No Error" : : (no_ == WSAEINTR)
(no_ == WSAEINTR) ? ? "Interrupted system call"
"Interrupted system call" : : (no_ == WSAEBADF)
(no_ == WSAEBADF) ? ? "Bad file number"
"Bad file number" : : (no_ == WSAEACCES)
(no_ == WSAEACCES) ? ? "Permission denied"
"Permission denied" : : (no_ == WSAEFAULT)
(no_ == WSAEFAULT) ? ? "Bad address"
"Bad address" : : (no_ == WSAEINVAL)
(no_ == WSAEINVAL) ? ? "Invalid argument"
"Invalid argument" : : (no_ == WSAEMFILE)
(no_ == WSAEMFILE) ? ? "Too many open files"
"Too many open files" : : (no_ == WSAEWOULDBLOCK)
(no_ == WSAEWOULDBLOCK) ? ? wsae_wouldblock_string
wsae_wouldblock_string : : (no_ == WSAEINPROGRESS)
(no_ == WSAEINPROGRESS) ? ? "Operation now in progress"
"Operation now in progress" : : (no_ == WSAEALREADY)
(no_ == WSAEALREADY) ? ? "Operation already in "
"Operation already in progress" : "progress"
(no_ == WSAENOTSOCK) ? : (no_ == WSAENOTSOCK)
"Socket operation on non-socket" : ? "Socket operation on "
(no_ == WSAEDESTADDRREQ) ? "non-socket"
"Destination address required" : : (no_ == WSAEDESTADDRREQ)
(no_ == WSAEMSGSIZE) ? ? "Destination "
"Message too long" : "address required"
(no_ == WSAEPROTOTYPE) ? : (no_ == WSAEMSGSIZE)
"Protocol wrong type for socket" : ? "Message too "
(no_ == WSAENOPROTOOPT) ? "long"
"Bad protocol option" : : (no_
(no_ == WSAEPROTONOSUPPORT) ? == WSAEPROTOTYPE)
"Protocol not supported" : ? "Protocol "
(no_ == WSAESOCKTNOSUPPORT) ? "wrong type "
"Socket type not supported" : "for socket"
(no_ == WSAEOPNOTSUPP) ? : (no_
"Operation not supported on socket" : == WSAENOPROTOOPT)
(no_ == WSAEPFNOSUPPORT) ? ? "Bad "
"Protocol family not supported" : "protoco"
(no_ == WSAEAFNOSUPPORT) ? "l "
"Address family not supported by protocol family" : "option"
(no_ == WSAEADDRINUSE) ? : (no_
"Address already in use" : == WSAEPROTONOSUPPORT)
(no_ == WSAEADDRNOTAVAIL) ? ? "Pro"
"Can't assign requested address" : "toc"
(no_ == WSAENETDOWN) ? "ol "
"Network is down" : "not"
(no_ == WSAENETUNREACH) ? " su"
"Network is unreachable" : "ppo"
(no_ == WSAENETRESET) ? "rte"
"Net dropped connection or reset" : "d"
(no_ == WSAECONNABORTED) ? : (no_
"Software caused connection abort" : == WSAESOCKTNOSUPPORT)
(no_ == WSAECONNRESET) ? ? "Socket type not supported"
"Connection reset by peer" : : (no_
(no_ == WSAENOBUFS) ? == WSAEOPNOTSUPP)
"No buffer space available" : ? "Operation not supported on socket"
(no_ == WSAEISCONN) ? : (no_
"Socket is already connected" : == WSAEPFNOSUPPORT)
(no_ == WSAENOTCONN) ? ? "Protocol family not supported"
"Socket is not connected" : : (no_
(no_ == WSAESHUTDOWN) ? == WSAEAFNOSUPPORT)
"Can't send after socket shutdown" : ? "Address family not supported by protocol family"
(no_ == WSAETOOMANYREFS) ? : (no_ == WSAEADDRINUSE) ? "Address already in use"
"Too many references can't splice" : : (no_ == WSAEADDRNOTAVAIL) ? "Can't assign requested address"
(no_ == WSAETIMEDOUT) ? : (no_ == WSAENETDOWN) ? "Network is down"
"Connection timed out" : : (no_ == WSAENETUNREACH) ? "Network is unreachable"
(no_ == WSAECONNREFUSED) ? : (no_ == WSAENETRESET) ? "Net dropped connection or reset"
"Connection refused" : : (no_ == WSAECONNABORTED) ? "Software caused connection abort"
(no_ == WSAELOOP) ? : (no_ == WSAECONNRESET) ? "Connection reset by peer"
"Too many levels of symbolic links" : : (no_
(no_ == WSAENAMETOOLONG) ? == WSAENOBUFS)
"File name too long" : ? "No buffer space available"
(no_ == WSAEHOSTDOWN) ? : (no_ == WSAEISCONN) ? "Socket is already connected"
"Host is down" : : (no_
(no_ == WSAEHOSTUNREACH) ? == WSAENOTCONN)
"No Route to Host" : ? "Socket is not connected"
(no_ == WSAENOTEMPTY) ? : (no_ == WSAESHUTDOWN) ? "Can't send after socket shutdown"
"Directory not empty" : : (no_ == WSAETOOMANYREFS) ? "Too many references can't splice"
(no_ == WSAEPROCLIM) ? : (no_ == WSAETIMEDOUT) ? "Connection timed out"
"Too many processes" : : (no_
(no_ == WSAEUSERS) ? == WSAECONNREFUSED)
"Too many users" : ? "Connection refused"
(no_ == WSAEDQUOT) ? : (no_
"Disc Quota Exceeded" : == WSAELOOP)
(no_ == WSAESTALE) ? ? "Too many levels of symbolic links"
"Stale NFS file handle" : : (no_
(no_ == WSAEREMOTE) ? == WSAENAMETOOLONG)
"Too many levels of remote in path" : ? "File name too long"
(no_ == WSASYSNOTREADY) ? : (no_ == WSAEHOSTDOWN) ? "Host is down"
"Network SubSystem is unavailable" : : (no_
(no_ == WSAVERNOTSUPPORTED) ? == WSAEHOSTUNREACH)
"WINSOCK DLL Version out of range" : ? "No Route to Host"
(no_ == WSANOTINITIALISED) ? : (no_ == WSAENOTEMPTY) ? "Directory not empty"
"Successful WSASTARTUP not yet performed" : : (no_ == WSAEPROCLIM) ? "Too many processes"
(no_ == WSAHOST_NOT_FOUND) ? : (
"Host not found" : no_
(no_ == WSATRY_AGAIN) ? == WSAEUSERS)
"Non-Authoritative Host not found" : ? "Too many users"
(no_ == WSANO_RECOVERY) ? : (no_
"Non-Recoverable errors: FORMERR REFUSED NOTIMP" : == WSAEDQUOT)
(no_ == WSANO_DATA) ? ? "Disc Quota Exceeded"
"Valid name no data record of requested" : : (no_
"error not defined"; == 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_) void zmq::win_error (char *buffer_, size_t buffer_size_)
{ {
DWORD errcode = GetLastError (); DWORD errcode = GetLastError ();
#if defined _WIN32_WCE #if defined _WIN32_WCE
DWORD rc = FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM | DWORD rc = FormatMessageW (
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, MAKELANGID(LANG_NEUTRAL, FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode,
SUBLANG_DEFAULT), (LPWSTR)buffer_, buffer_size_ / sizeof(wchar_t), NULL); MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR) buffer_,
buffer_size_ / sizeof (wchar_t), NULL);
#else #else
DWORD rc = FormatMessageA (FORMAT_MESSAGE_FROM_SYSTEM | DWORD rc = FormatMessageA (
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, MAKELANGID(LANG_NEUTRAL, FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode,
SUBLANG_DEFAULT), buffer_, (DWORD) buffer_size_, NULL); MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), buffer_, (DWORD) buffer_size_,
NULL);
#endif #endif
zmq_assert (rc); zmq_assert (rc);
} }

View File

@@ -65,7 +65,9 @@ namespace zmq
namespace zmq namespace zmq
{ {
const char *wsa_error (); const char *wsa_error ();
const char *wsa_error_no (int no_, const char * wsae_wouldblock_string = "Operation would block"); const char *
wsa_error_no (int no_,
const char *wsae_wouldblock_string = "Operation would block");
void win_error (char *buffer_, size_t buffer_size_); void win_error (char *buffer_, size_t buffer_size_);
int wsa_error_to_errno (int errcode); int wsa_error_to_errno (int errcode);
} }
@@ -117,8 +119,8 @@ namespace zmq
#define zmq_assert(x) \ #define zmq_assert(x) \
do { \ do { \
if (unlikely (!(x))) { \ if (unlikely (!(x))) { \
fprintf (stderr, "Assertion failed: %s (%s:%d)\n", #x, \ fprintf (stderr, "Assertion failed: %s (%s:%d)\n", #x, __FILE__, \
__FILE__, __LINE__);\ __LINE__); \
fflush (stderr); \ fflush (stderr); \
zmq::zmq_abort (#x); \ zmq::zmq_abort (#x); \
} \ } \
@@ -161,13 +163,11 @@ namespace zmq
#define alloc_assert(x) \ #define alloc_assert(x) \
do { \ do { \
if (unlikely (!x)) { \ if (unlikely (!x)) { \
fprintf (stderr, "FATAL ERROR: OUT OF MEMORY (%s:%d)\n",\ fprintf (stderr, "FATAL ERROR: OUT OF MEMORY (%s:%d)\n", __FILE__, \
__FILE__, __LINE__);\ __LINE__); \
fflush (stderr); \ fflush (stderr); \
zmq::zmq_abort ("FATAL ERROR: OUT OF MEMORY"); \ zmq::zmq_abort ("FATAL ERROR: OUT OF MEMORY"); \
} \ } \
} while (false) } while (false)
#endif #endif

View File

@@ -39,14 +39,23 @@ namespace zmq
#ifdef ZMQ_HAVE_WINDOWS #ifdef ZMQ_HAVE_WINDOWS
#if defined _MSC_VER && _MSC_VER <= 1400 #if defined _MSC_VER && _MSC_VER <= 1400
typedef UINT_PTR fd_t; typedef UINT_PTR fd_t;
enum {retired_fd = (fd_t)(~0)}; enum
{
retired_fd = (fd_t) (~0)
};
#else #else
typedef SOCKET fd_t; typedef SOCKET fd_t;
enum {retired_fd = (fd_t)INVALID_SOCKET}; enum
{
retired_fd = (fd_t) INVALID_SOCKET
};
#endif #endif
#else #else
typedef int fd_t; typedef int fd_t;
enum {retired_fd = -1}; enum
{
retired_fd = -1
};
#endif #endif
} }
#endif #endif

View File

@@ -33,11 +33,7 @@
#include "err.hpp" #include "err.hpp"
#include "msg.hpp" #include "msg.hpp"
zmq::fq_t::fq_t () : zmq::fq_t::fq_t () : active (0), last_in (NULL), current (0), more (false)
active (0),
last_in (NULL),
current (0),
more (false)
{ {
} }
@@ -93,7 +89,6 @@ int zmq::fq_t::recvpipe (msg_t *msg_, pipe_t **pipe_)
// Round-robin over the pipes to get the next message. // Round-robin over the pipes to get the next message.
while (active > 0) { while (active > 0) {
// Try to fetch new message. If we've already read part of the message // Try to fetch new message. If we've already read part of the message
// subsequent part should be immediately available. // subsequent part should be immediately available.
bool fetched = pipes[current]->read (msg_); bool fetched = pipes[current]->read (msg_);
@@ -157,7 +152,5 @@ bool zmq::fq_t::has_in ()
const zmq::blob_t &zmq::fq_t::get_credential () const const zmq::blob_t &zmq::fq_t::get_credential () const
{ {
return last_in? return last_in ? last_in->get_credential () : saved_credential;
last_in->get_credential (): saved_credential;
} }

View File

@@ -37,7 +37,6 @@
namespace zmq namespace zmq
{ {
// Class manages a set of inbound pipes. On receive it performs fair // Class manages a set of inbound pipes. On receive it performs fair
// queueing so that senders gone berserk won't cause denial of // queueing so that senders gone berserk won't cause denial of
// service for decent senders. // service for decent senders.
@@ -45,7 +44,6 @@ namespace zmq
class fq_t class fq_t
{ {
public: public:
fq_t (); fq_t ();
~fq_t (); ~fq_t ();
@@ -59,7 +57,6 @@ namespace zmq
const blob_t &get_credential () const; const blob_t &get_credential () const;
private: private:
// Inbound pipes. // Inbound pipes.
typedef array_t<pipe_t, 1> pipes_t; typedef array_t<pipe_t, 1> pipes_t;
pipes_t pipes; pipes_t pipes;
@@ -86,7 +83,6 @@ namespace zmq
fq_t (const fq_t &); fq_t (const fq_t &);
const fq_t &operator= (const fq_t &); const fq_t &operator= (const fq_t &);
}; };
} }
#endif #endif

View File

@@ -68,7 +68,6 @@ int zmq::gather_t::xrecv (msg_t *msg_)
// Drop any messages with more flag // Drop any messages with more flag
while (rc == 0 && msg_->flags () & msg_t::more) { while (rc == 0 && msg_->flags () & msg_t::more) {
// drop all frames of the current multi-frame message // drop all frames of the current multi-frame message
rc = fq.recvpipe (msg_, NULL); rc = fq.recvpipe (msg_, NULL);

View File

@@ -36,22 +36,18 @@
namespace zmq namespace zmq
{ {
class ctx_t; class ctx_t;
class pipe_t; class pipe_t;
class msg_t; class msg_t;
class io_thread_t; class io_thread_t;
class gather_t : class gather_t : public socket_base_t
public socket_base_t
{ {
public: public:
gather_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_); gather_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_);
~gather_t (); ~gather_t ();
protected: protected:
// Overrides of functions from socket_base_t. // Overrides of functions from socket_base_t.
void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_); void xattach_pipe (zmq::pipe_t *pipe_, bool subscribe_to_all_);
int xrecv (zmq::msg_t *msg_); int xrecv (zmq::msg_t *msg_);
@@ -61,15 +57,12 @@ namespace zmq
void xpipe_terminated (zmq::pipe_t *pipe_); void xpipe_terminated (zmq::pipe_t *pipe_);
private: private:
// Fair queueing object for inbound pipes. // Fair queueing object for inbound pipes.
fq_t fq; fq_t fq;
gather_t (const gather_t &); gather_t (const gather_t &);
const gather_t &operator= (const gather_t &); const gather_t &operator= (const gather_t &);
}; };
} }
#endif #endif

View File

@@ -49,19 +49,22 @@ zmq::gssapi_client_t::gssapi_client_t (session_base_t *session_,
mechs (), mechs (),
security_context_established (false) security_context_established (false)
{ {
const std::string::size_type service_size = options_.gss_service_principal.size(); const std::string::size_type service_size =
options_.gss_service_principal.size ();
service_name = static_cast<char *> (malloc (service_size + 1)); service_name = static_cast<char *> (malloc (service_size + 1));
assert (service_name); assert (service_name);
memcpy(service_name, options_.gss_service_principal.c_str(), service_size+1 ); memcpy (service_name, options_.gss_service_principal.c_str (),
service_size + 1);
service_name_type = convert_nametype (options_.gss_service_principal_nt); service_name_type = convert_nametype (options_.gss_service_principal_nt);
maj_stat = GSS_S_COMPLETE; maj_stat = GSS_S_COMPLETE;
if(!options_.gss_principal.empty()) if (!options_.gss_principal.empty ()) {
{ const std::string::size_type principal_size =
const std::string::size_type principal_size = options_.gss_principal.size(); options_.gss_principal.size ();
principal_name = static_cast<char *> (malloc (principal_size + 1)); principal_name = static_cast<char *> (malloc (principal_size + 1));
assert (principal_name); assert (principal_name);
memcpy(principal_name, options_.gss_principal.c_str(), principal_size+1 ); memcpy (principal_name, options_.gss_principal.c_str (),
principal_size + 1);
gss_OID name_type = convert_nametype (options_.gss_principal_nt); gss_OID name_type = convert_nametype (options_.gss_principal_nt);
if (acquire_credentials (principal_name, &cred, name_type) != 0) if (acquire_credentials (principal_name, &cred, name_type) != 0)
@@ -107,8 +110,7 @@ int zmq::gssapi_client_t::next_handshake_command (msg_t *msg_)
if (maj_stat == GSS_S_COMPLETE) { if (maj_stat == GSS_S_COMPLETE) {
security_context_established = true; security_context_established = true;
state = recv_ready; state = recv_ready;
} } else
else
state = recv_next_token; state = recv_next_token;
return 0; return 0;
@@ -126,8 +128,7 @@ int zmq::gssapi_client_t::process_handshake_command (msg_t *msg_)
if (state != recv_next_token) { if (state != recv_next_token) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
errno = EPROTO; errno = EPROTO;
return -1; return -1;
} }
@@ -182,17 +183,15 @@ int zmq::gssapi_client_t::initialize_context ()
send_tok.value = service_name; send_tok.value = service_name;
send_tok.length = strlen (service_name) + 1; send_tok.length = strlen (service_name) + 1;
OM_uint32 maj = gss_import_name (&min_stat, &send_tok, OM_uint32 maj = gss_import_name (&min_stat, &send_tok,
service_name_type, service_name_type, &target_name);
&target_name);
if (maj != GSS_S_COMPLETE) if (maj != GSS_S_COMPLETE)
return -1; return -1;
} }
maj_stat = gss_init_sec_context(&init_sec_min_stat, cred, &context, maj_stat = gss_init_sec_context (
target_name, mechs.elements, &init_sec_min_stat, cred, &context, target_name, mechs.elements,
gss_flags, 0, NULL, token_ptr, NULL, gss_flags, 0, NULL, token_ptr, NULL, &send_tok, &ret_flags, NULL);
&send_tok, &ret_flags, NULL);
if (token_ptr != GSS_C_NO_BUFFER) if (token_ptr != GSS_C_NO_BUFFER)
free (recv_tok.value); free (recv_tok.value);

View File

@@ -36,7 +36,6 @@
namespace zmq namespace zmq
{ {
class msg_t; class msg_t;
class session_base_t; class session_base_t;
@@ -54,8 +53,8 @@ namespace zmq
virtual status_t status () const; virtual status_t status () const;
private: private:
enum state_t
enum state_t { {
call_next_init, call_next_init,
send_next_token, send_next_token,
recv_next_token, recv_next_token,
@@ -86,7 +85,6 @@ namespace zmq
int produce_next_token (msg_t *msg_); int produce_next_token (msg_t *msg_);
int process_next_token (msg_t *msg_); int process_next_token (msg_t *msg_);
}; };
} }
#endif #endif

View File

@@ -41,8 +41,7 @@
#include "wire.hpp" #include "wire.hpp"
zmq::gssapi_mechanism_base_t::gssapi_mechanism_base_t ( zmq::gssapi_mechanism_base_t::gssapi_mechanism_base_t (
session_base_t *session_, session_base_t *session_, const options_t &options_) :
const options_t &options_) :
mechanism_base_t (session_, options_), mechanism_base_t (session_, options_),
send_tok (), send_tok (),
recv_tok (), recv_tok (),
@@ -81,7 +80,8 @@ int zmq::gssapi_mechanism_base_t::encode_message (msg_t *msg_)
if (msg_->flags () & msg_t::command) if (msg_->flags () & msg_t::command)
flags |= 0x02; flags |= 0x02;
uint8_t *plaintext_buffer = static_cast <uint8_t *>(malloc(msg_->size ()+1)); uint8_t *plaintext_buffer =
static_cast<uint8_t *> (malloc (msg_->size () + 1));
alloc_assert (plaintext_buffer); alloc_assert (plaintext_buffer);
plaintext_buffer[0] = flags; plaintext_buffer[0] = flags;
@@ -90,8 +90,8 @@ int zmq::gssapi_mechanism_base_t::encode_message (msg_t *msg_)
plaintext.value = plaintext_buffer; 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, maj_stat = gss_wrap (&min_stat, context, 1, GSS_C_QOP_DEFAULT, &plaintext,
&plaintext, &state, &wrapped); &state, &wrapped);
zmq_assert (maj_stat == GSS_S_COMPLETE); zmq_assert (maj_stat == GSS_S_COMPLETE);
zmq_assert (state); zmq_assert (state);
@@ -134,8 +134,7 @@ int zmq::gssapi_mechanism_base_t::decode_message (msg_t *msg_)
// Get command string // Get command string
if (bytes_left < 8 || memcmp (ptr, "\x07MESSAGE", 8)) { if (bytes_left < 8 || memcmp (ptr, "\x07MESSAGE", 8)) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
errno = EPROTO; errno = EPROTO;
return -1; return -1;
} }
@@ -177,16 +176,14 @@ int zmq::gssapi_mechanism_base_t::decode_message (msg_t *msg_)
// Unwrap the token value // Unwrap the token value
int state; int state;
gss_buffer_desc plaintext; gss_buffer_desc plaintext;
maj_stat = gss_unwrap(&min_stat, context, &wrapped, &plaintext, maj_stat = gss_unwrap (&min_stat, context, &wrapped, &plaintext, &state,
&state, (gss_qop_t *) NULL); (gss_qop_t *) NULL);
if (maj_stat != GSS_S_COMPLETE) if (maj_stat != GSS_S_COMPLETE) {
{
gss_release_buffer (&min_stat, &plaintext); gss_release_buffer (&min_stat, &plaintext);
free (wrapped.value); free (wrapped.value);
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
ZMQ_PROTOCOL_ERROR_ZMTP_CRYPTOGRAPHIC);
errno = EPROTO; errno = EPROTO;
return -1; return -1;
} }
@@ -205,7 +202,8 @@ int zmq::gssapi_mechanism_base_t::decode_message (msg_t *msg_)
if (flags & 0x02) if (flags & 0x02)
msg_->set_flags (msg_t::command); msg_->set_flags (msg_t::command);
memcpy (msg_->data (), static_cast <char *> (plaintext.value)+1, plaintext.length-1); memcpy (msg_->data (), static_cast<char *> (plaintext.value) + 1,
plaintext.length - 1);
gss_release_buffer (&min_stat, &plaintext); gss_release_buffer (&min_stat, &plaintext);
free (wrapped.value); free (wrapped.value);
@@ -221,7 +219,9 @@ int zmq::gssapi_mechanism_base_t::decode_message (msg_t *msg_)
return 0; 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_value_);
zmq_assert (token_length_ <= 0xFFFFFFFFUL); zmq_assert (token_length_ <= 0xFFFFFFFFUL);
@@ -248,7 +248,9 @@ int zmq::gssapi_mechanism_base_t::produce_initiate (msg_t *msg_, void *token_val
return 0; 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_); zmq_assert (token_value_);
@@ -262,8 +264,7 @@ int zmq::gssapi_mechanism_base_t::process_initiate (msg_t *msg_, void **token_va
// Get command string // Get command string
if (bytes_left < 9 || memcmp (ptr, "\x08INITIATE", 9)) { if (bytes_left < 9 || memcmp (ptr, "\x08INITIATE", 9)) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
errno = EPROTO; errno = EPROTO;
return -1; return -1;
} }
@@ -291,7 +292,8 @@ int zmq::gssapi_mechanism_base_t::process_initiate (msg_t *msg_, void **token_va
return -1; return -1;
} }
*token_value_ = static_cast <char *> (malloc (token_length_ ? token_length_ : 1)); *token_value_ =
static_cast<char *> (malloc (token_length_ ? token_length_ : 1));
alloc_assert (*token_value_); alloc_assert (*token_value_);
if (token_length_) { if (token_length_) {
@@ -338,8 +340,7 @@ int zmq::gssapi_mechanism_base_t::process_ready (msg_t *msg_)
if (bytes_left < 6 || memcmp (ptr, "\x05READY", 6)) { if (bytes_left < 6 || memcmp (ptr, "\x05READY", 6)) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
errno = EPROTO; errno = EPROTO;
return -1; return -1;
} }
@@ -348,8 +349,7 @@ int zmq::gssapi_mechanism_base_t::process_ready (msg_t *msg_)
rc = parse_metadata (ptr, bytes_left); rc = parse_metadata (ptr, bytes_left);
if (rc == -1) if (rc == -1)
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_METADATA);
ZMQ_PROTOCOL_ERROR_ZMTP_INVALID_METADATA);
return rc; return rc;
} }
@@ -371,7 +371,9 @@ const gss_OID zmq::gssapi_mechanism_base_t::convert_nametype (int zmq_nametype)
return NULL; 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 maj_stat;
OM_uint32 min_stat; OM_uint32 min_stat;
@@ -381,15 +383,13 @@ int zmq::gssapi_mechanism_base_t::acquire_credentials (char * service_name_, gss
name_buf.value = service_name_; name_buf.value = service_name_;
name_buf.length = strlen ((char *) name_buf.value) + 1; name_buf.length = strlen ((char *) name_buf.value) + 1;
maj_stat = gss_import_name (&min_stat, &name_buf, maj_stat = gss_import_name (&min_stat, &name_buf, name_type_, &server_name);
name_type_, &server_name);
if (maj_stat != GSS_S_COMPLETE) if (maj_stat != GSS_S_COMPLETE)
return -1; return -1;
maj_stat = gss_acquire_cred (&min_stat, server_name, 0, maj_stat = gss_acquire_cred (&min_stat, server_name, 0, GSS_C_NO_OID_SET,
GSS_C_NO_OID_SET, GSS_C_BOTH, GSS_C_BOTH, cred_, NULL, NULL);
cred_, NULL, NULL);
if (maj_stat != GSS_S_COMPLETE) if (maj_stat != GSS_S_COMPLETE)
return -1; return -1;

View File

@@ -42,7 +42,6 @@
namespace zmq namespace zmq
{ {
class msg_t; class msg_t;
/// Commonalities between clients and servers are captured here. /// Commonalities between clients and servers are captured here.
@@ -126,7 +125,6 @@ namespace zmq
// If true, use gss to encrypt messages. If false, only utilize gss for auth. // If true, use gss to encrypt messages. If false, only utilize gss for auth.
bool do_encryption; bool do_encryption;
}; };
} }
#endif #endif

View File

@@ -54,12 +54,13 @@ zmq::gssapi_server_t::gssapi_server_t (session_base_t *session_,
security_context_established (false) security_context_established (false)
{ {
maj_stat = GSS_S_CONTINUE_NEEDED; maj_stat = GSS_S_CONTINUE_NEEDED;
if(!options_.gss_principal.empty()) if (!options_.gss_principal.empty ()) {
{ const std::string::size_type principal_size =
const std::string::size_type principal_size = options_.gss_principal.size(); options_.gss_principal.size ();
principal_name = static_cast<char *> (malloc (principal_size + 1)); principal_name = static_cast<char *> (malloc (principal_size + 1));
assert (principal_name); assert (principal_name);
memcpy(principal_name, options_.gss_principal.c_str(), principal_size+1 ); memcpy (principal_name, options_.gss_principal.c_str (),
principal_size + 1);
gss_OID name_type = convert_nametype (options_.gss_principal_nt); gss_OID name_type = convert_nametype (options_.gss_principal_nt);
if (acquire_credentials (principal_name, &cred, name_type) != 0) if (acquire_credentials (principal_name, &cred, name_type) != 0)
maj_stat = GSS_S_FAILURE; maj_stat = GSS_S_FAILURE;
@@ -117,8 +118,7 @@ int zmq::gssapi_server_t::process_handshake_command (msg_t *msg_)
if (state != recv_next_token) { if (state != recv_next_token) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
errno = EPROTO; errno = EPROTO;
return -1; return -1;
} }
@@ -158,8 +158,8 @@ void zmq::gssapi_server_t::send_zap_request ()
{ {
gss_buffer_desc principal; gss_buffer_desc principal;
gss_display_name (&min_stat, target_name, &principal, NULL); gss_display_name (&min_stat, target_name, &principal, NULL);
zap_client_t::send_zap_request ("GSSAPI", 6, zap_client_t::send_zap_request (
reinterpret_cast<const uint8_t *> (principal.value), "GSSAPI", 6, reinterpret_cast<const uint8_t *> (principal.value),
principal.length); principal.length);
gss_release_buffer (&min_stat, &principal); gss_release_buffer (&min_stat, &principal);
@@ -235,10 +235,9 @@ int zmq::gssapi_server_t::process_next_token (msg_t *msg_)
void zmq::gssapi_server_t::accept_context () void zmq::gssapi_server_t::accept_context ()
{ {
maj_stat = gss_accept_sec_context(&init_sec_min_stat, &context, cred, maj_stat = gss_accept_sec_context (
&recv_tok, GSS_C_NO_CHANNEL_BINDINGS, &init_sec_min_stat, &context, cred, &recv_tok, GSS_C_NO_CHANNEL_BINDINGS,
&target_name, &doid, &send_tok, &target_name, &doid, &send_tok, &ret_flags, NULL, NULL);
&ret_flags, NULL, NULL);
if (recv_tok.value) { if (recv_tok.value) {
free (recv_tok.value); free (recv_tok.value);

View File

@@ -37,12 +37,10 @@
namespace zmq namespace zmq
{ {
class msg_t; class msg_t;
class session_base_t; class session_base_t;
class gssapi_server_t class gssapi_server_t : public gssapi_mechanism_base_t, public zap_client_t
: public gssapi_mechanism_base_t, public zap_client_t
{ {
public: public:
gssapi_server_t (session_base_t *session_, gssapi_server_t (session_base_t *session_,
@@ -59,8 +57,8 @@ namespace zmq
virtual status_t status () const; virtual status_t status () const;
private: private:
enum state_t
enum state_t { {
send_next_token, send_next_token,
recv_next_token, recv_next_token,
expect_zap_reply, expect_zap_reply,
@@ -87,7 +85,6 @@ namespace zmq
int process_next_token (msg_t *msg_); int process_next_token (msg_t *msg_);
void send_zap_request (); void send_zap_request ();
}; };
} }
#endif #endif

View File

@@ -34,7 +34,6 @@
namespace zmq namespace zmq
{ {
class msg_t; class msg_t;
// Interface to be implemented by message decoder. // Interface to be implemented by message decoder.
@@ -51,14 +50,11 @@ namespace zmq
// When a message is decoded, 1 is returned. // When a message is decoded, 1 is returned.
// When the decoder needs more data, 0 is returned. // When the decoder needs more data, 0 is returned.
// On error, -1 is returned and errno is set accordingly. // On error, -1 is returned and errno is set accordingly.
virtual int decode (const unsigned char *data_, size_t size_, virtual int
size_t &processed) = 0; decode (const unsigned char *data_, size_t size_, size_t &processed) = 0;
virtual msg_t *msg () = 0; virtual msg_t *msg () = 0;
}; };
} }
#endif #endif

View File

@@ -34,7 +34,6 @@
namespace zmq namespace zmq
{ {
// Forward declaration // Forward declaration
class msg_t; class msg_t;
@@ -52,9 +51,7 @@ namespace zmq
// Load a new message into encoder. // Load a new message into encoder.
virtual void load_msg (msg_t *msg_) = 0; virtual void load_msg (msg_t *msg_) = 0;
}; };
} }
#endif #endif

View File

@@ -32,7 +32,6 @@
namespace zmq 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.
@@ -60,9 +59,7 @@ namespace zmq
virtual void zap_msg_available () = 0; virtual void zap_msg_available () = 0;
virtual const char *get_endpoint () const = 0; virtual const char *get_endpoint () const = 0;
}; };
} }
#endif #endif

View File

@@ -51,10 +51,7 @@ namespace zmq
// with the context in the parent process. // with the context in the parent process.
virtual void forked () = 0; virtual void forked () = 0;
#endif #endif
}; };
} }
#endif #endif

View File

@@ -32,7 +32,6 @@
namespace zmq namespace zmq
{ {
// Virtual interface to be exposed by object that want to be notified // Virtual interface to be exposed by object that want to be notified
// about events on file descriptors. // about events on file descriptors.
@@ -49,7 +48,6 @@ namespace zmq
// Called when timer expires. // Called when timer expires.
virtual void timer_event (int id_) = 0; virtual void timer_event (int id_) = 0;
}; };
} }
#endif #endif

View File

@@ -32,8 +32,7 @@
#include "io_thread.hpp" #include "io_thread.hpp"
#include "err.hpp" #include "err.hpp"
zmq::io_object_t::io_object_t (io_thread_t *io_thread_) : zmq::io_object_t::io_object_t (io_thread_t *io_thread_) : poller (NULL)
poller (NULL)
{ {
if (io_thread_) if (io_thread_)
plug (io_thread_); plug (io_thread_);

View File

@@ -38,7 +38,6 @@
namespace zmq namespace zmq
{ {
class io_thread_t; class io_thread_t;
// Simple base class for objects that live in I/O threads. // Simple base class for objects that live in I/O threads.
@@ -48,7 +47,6 @@ namespace zmq
class io_object_t : public i_poll_events class io_object_t : public i_poll_events
{ {
public: public:
io_object_t (zmq::io_thread_t *io_thread_ = NULL); io_object_t (zmq::io_thread_t *io_thread_ = NULL);
~io_object_t (); ~io_object_t ();
@@ -58,7 +56,6 @@ namespace zmq
void unplug (); void unplug ();
protected: protected:
typedef poller_t::handle_t handle_t; typedef poller_t::handle_t handle_t;
// Methods to access underlying poller object. // Methods to access underlying poller object.
@@ -77,13 +74,11 @@ namespace zmq
void timer_event (int id_); void timer_event (int id_);
private: private:
poller_t *poller; poller_t *poller;
io_object_t (const io_object_t &); io_object_t (const io_object_t &);
const io_object_t &operator= (const io_object_t &); const io_object_t &operator= (const io_object_t &);
}; };
} }
#endif #endif

View File

@@ -40,7 +40,6 @@
namespace zmq namespace zmq
{ {
class ctx_t; class ctx_t;
// Generic part of the I/O thread. Polling-mechanism-specific features // Generic part of the I/O thread. Polling-mechanism-specific features
@@ -49,7 +48,6 @@ namespace zmq
class io_thread_t : public object_t, public i_poll_events class io_thread_t : public object_t, public i_poll_events
{ {
public: public:
io_thread_t (zmq::ctx_t *ctx_, uint32_t tid_); io_thread_t (zmq::ctx_t *ctx_, uint32_t tid_);
// Clean-up. If the thread was started, it's necessary to call 'stop' // Clean-up. If the thread was started, it's necessary to call 'stop'
@@ -80,7 +78,6 @@ namespace zmq
int get_load (); int get_load ();
private: private:
// I/O thread accesses incoming commands via this mailbox. // I/O thread accesses incoming commands via this mailbox.
mailbox_t mailbox; mailbox_t mailbox;
@@ -93,7 +90,6 @@ namespace zmq
io_thread_t (const io_thread_t &); io_thread_t (const io_thread_t &);
const io_thread_t &operator= (const io_thread_t &); const io_thread_t &operator= (const io_thread_t &);
}; };
} }
#endif #endif

View File

@@ -138,30 +138,28 @@ int zmq::get_peer_ip_address (fd_t sockfd_, std::string &ip_addr_)
#ifdef ZMQ_HAVE_WINDOWS #ifdef ZMQ_HAVE_WINDOWS
if (rc == SOCKET_ERROR) { if (rc == SOCKET_ERROR) {
const int last_error = WSAGetLastError (); const int last_error = WSAGetLastError ();
wsa_assert (last_error != WSANOTINITIALISED && wsa_assert (last_error != WSANOTINITIALISED && last_error != WSAEFAULT
last_error != WSAEFAULT && && last_error != WSAEINPROGRESS
last_error != WSAEINPROGRESS && && last_error != WSAENOTSOCK);
last_error != WSAENOTSOCK);
return 0; return 0;
} }
#else #else
if (rc == -1) { if (rc == -1) {
errno_assert (errno != EBADF && errno_assert (errno != EBADF && errno != EFAULT && errno != ENOTSOCK);
errno != EFAULT &&
errno != ENOTSOCK);
return 0; return 0;
} }
#endif #endif
char host[NI_MAXHOST]; char host[NI_MAXHOST];
rc = getnameinfo ((struct sockaddr*) &ss, addrlen, host, sizeof host, rc = getnameinfo ((struct sockaddr *) &ss, addrlen, host, sizeof host, NULL,
NULL, 0, NI_NUMERICHOST); 0, NI_NUMERICHOST);
if (rc != 0) if (rc != 0)
return 0; return 0;
ip_addr_ = host; ip_addr_ = host;
union { union
{
struct sockaddr sa; struct sockaddr sa;
struct sockaddr_storage sa_stor; struct sockaddr_storage sa_stor;
} u; } 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) void zmq::set_ip_type_of_service (fd_t s_, int iptos)
{ {
int rc = setsockopt(s_, IPPROTO_IP, IP_TOS, reinterpret_cast<const char*>(&iptos), sizeof(iptos)); int rc =
setsockopt (s_, IPPROTO_IP, IP_TOS,
reinterpret_cast<const char *> (&iptos), sizeof (iptos));
#ifdef ZMQ_HAVE_WINDOWS #ifdef ZMQ_HAVE_WINDOWS
wsa_assert (rc != SOCKET_ERROR); wsa_assert (rc != SOCKET_ERROR);
@@ -182,18 +182,13 @@ void zmq::set_ip_type_of_service (fd_t s_, int iptos)
// Windows and Hurd do not support IPV6_TCLASS // Windows and Hurd do not support IPV6_TCLASS
#if !defined(ZMQ_HAVE_WINDOWS) && defined(IPV6_TCLASS) #if !defined(ZMQ_HAVE_WINDOWS) && defined(IPV6_TCLASS)
rc = setsockopt( rc = setsockopt (s_, IPPROTO_IPV6, IPV6_TCLASS,
s_, reinterpret_cast<const char *> (&iptos), sizeof (iptos));
IPPROTO_IPV6,
IPV6_TCLASS,
reinterpret_cast<const char*>(&iptos),
sizeof(iptos));
// If IPv6 is not enabled ENOPROTOOPT will be returned on Linux and // If IPv6 is not enabled ENOPROTOOPT will be returned on Linux and
// EINVAL on OSX // EINVAL on OSX
if (rc == -1) { if (rc == -1) {
errno_assert (errno == ENOPROTOOPT || errno_assert (errno == ENOPROTOOPT || errno == EINVAL);
errno == EINVAL);
} }
#endif #endif
} }
@@ -221,7 +216,8 @@ int zmq::set_nosigpipe (fd_t s_)
void zmq::bind_to_device (fd_t s_, std::string &bound_device_) void zmq::bind_to_device (fd_t s_, std::string &bound_device_)
{ {
#ifdef ZMQ_HAVE_SO_BINDTODEVICE #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 #ifdef ZMQ_HAVE_WINDOWS
wsa_assert (rc != SOCKET_ERROR); wsa_assert (rc != SOCKET_ERROR);

View File

@@ -35,7 +35,6 @@
namespace zmq namespace zmq
{ {
// Same as socket(2), but allows for transparent tweaking the options. // Same as socket(2), but allows for transparent tweaking the options.
fd_t open_socket (int domain_, int type_, int protocol_); fd_t open_socket (int domain_, int type_, int protocol_);
@@ -58,7 +57,6 @@ namespace zmq
// Binds the underlying socket to the given device, eg. VRF or interface // Binds the underlying socket to the given device, eg. VRF or interface
void bind_to_device (fd_t s_, std::string &bound_device_); void bind_to_device (fd_t s_, std::string &bound_device_);
} }
#endif #endif

View File

@@ -99,7 +99,8 @@ const sockaddr *zmq::ipc_address_t::addr () const
socklen_t zmq::ipc_address_t::addrlen () const socklen_t zmq::ipc_address_t::addrlen () const
{ {
if (!address.sun_path[0] && address.sun_path[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) strlen (address.sun_path + 1) + sizeof (sa_family_t)
+ 1;
return (socklen_t) sizeof address; return (socklen_t) sizeof address;
} }

View File

@@ -39,11 +39,9 @@
namespace zmq namespace zmq
{ {
class ipc_address_t class ipc_address_t
{ {
public: public:
ipc_address_t (); ipc_address_t ();
ipc_address_t (const sockaddr *sa, socklen_t sa_len); ipc_address_t (const sockaddr *sa, socklen_t sa_len);
~ipc_address_t (); ~ipc_address_t ();
@@ -58,17 +56,13 @@ namespace zmq
socklen_t addrlen () const; socklen_t addrlen () const;
private: private:
struct sockaddr_un address; struct sockaddr_un address;
ipc_address_t (const ipc_address_t &); ipc_address_t (const ipc_address_t &);
const ipc_address_t &operator= (const ipc_address_t &); const ipc_address_t &operator= (const ipc_address_t &);
}; };
} }
#endif #endif
#endif #endif

View File

@@ -50,8 +50,10 @@
#include <sys/un.h> #include <sys/un.h>
zmq::ipc_connecter_t::ipc_connecter_t (class io_thread_t *io_thread_, zmq::ipc_connecter_t::ipc_connecter_t (class io_thread_t *io_thread_,
class session_base_t *session_, const options_t &options_, class session_base_t *session_,
const address_t *addr_, bool delayed_start_) : const options_t &options_,
const address_t *addr_,
bool delayed_start_) :
own_t (io_thread_, options_), own_t (io_thread_, options_),
io_object_t (io_thread_), io_object_t (io_thread_),
addr (addr_), addr (addr_),
@@ -122,8 +124,8 @@ void zmq::ipc_connecter_t::out_event ()
return; return;
} }
// Create the engine object for this connection. // Create the engine object for this connection.
stream_engine_t *engine = new (std::nothrow) stream_engine_t *engine =
stream_engine_t (fd, options, endpoint); new (std::nothrow) stream_engine_t (fd, options, endpoint);
alloc_assert (engine); alloc_assert (engine);
// Attach the engine to the corresponding session object. // Attach the engine to the corresponding session object.
@@ -155,8 +157,7 @@ void zmq::ipc_connecter_t::start_connecting ()
} }
// Connection establishment may be delayed. Poll for its completion. // Connection establishment may be delayed. Poll for its completion.
else else if (rc == -1 && errno == EINPROGRESS) {
if (rc == -1 && errno == EINPROGRESS) {
handle = add_fd (s); handle = add_fd (s);
handle_valid = true; handle_valid = true;
set_pollout (handle); set_pollout (handle);
@@ -182,14 +183,13 @@ void zmq::ipc_connecter_t::add_reconnect_timer()
int zmq::ipc_connecter_t::get_new_reconnect_ivl () int zmq::ipc_connecter_t::get_new_reconnect_ivl ()
{ {
// The new interval is the current interval + random value. // The new interval is the current interval + random value.
int this_interval = current_reconnect_ivl + int this_interval =
(generate_random () % options.reconnect_ivl); current_reconnect_ivl + (generate_random () % options.reconnect_ivl);
// Only change the current reconnect interval if the maximum reconnect // Only change the current reconnect interval if the maximum reconnect
// interval was set and if it's larger than the reconnect interval. // interval was set and if it's larger than the reconnect interval.
if (options.reconnect_ivl_max > 0 && if (options.reconnect_ivl_max > 0
options.reconnect_ivl_max > options.reconnect_ivl) { && options.reconnect_ivl_max > options.reconnect_ivl) {
// Calculate the next interval // Calculate the next interval
current_reconnect_ivl = current_reconnect_ivl * 2; current_reconnect_ivl = current_reconnect_ivl * 2;
if (current_reconnect_ivl >= options.reconnect_ivl_max) { if (current_reconnect_ivl >= options.reconnect_ivl_max) {
@@ -212,8 +212,7 @@ int zmq::ipc_connecter_t::open ()
unblock_socket (s); unblock_socket (s);
// Connect to the remote peer. // Connect to the remote peer.
int rc = ::connect ( int rc = ::connect (s, addr->resolved.ipc_addr->addr (),
s, addr->resolved.ipc_addr->addr (),
addr->resolved.ipc_addr->addrlen ()); addr->resolved.ipc_addr->addrlen ());
// Connect was successful immediately. // Connect was successful immediately.
@@ -258,13 +257,12 @@ zmq::fd_t zmq::ipc_connecter_t::connect ()
err = errno; err = errno;
} }
if (err != 0) { if (err != 0) {
// Assert if the error was caused by 0MQ bug. // Assert if the error was caused by 0MQ bug.
// Networking problems are OK. No need to assert. // Networking problems are OK. No need to assert.
errno = err; errno = err;
errno_assert (errno == ECONNREFUSED || errno == ECONNRESET || errno_assert (errno == ECONNREFUSED || errno == ECONNRESET
errno == ETIMEDOUT || errno == EHOSTUNREACH || || errno == ETIMEDOUT || errno == EHOSTUNREACH
errno == ENETUNREACH || errno == ENETDOWN); || errno == ENETUNREACH || errno == ENETDOWN);
return retired_fd; return retired_fd;
} }
@@ -275,4 +273,3 @@ zmq::fd_t zmq::ipc_connecter_t::connect ()
} }
#endif #endif

View File

@@ -39,7 +39,6 @@
namespace zmq namespace zmq
{ {
class io_thread_t; class io_thread_t;
class session_base_t; class session_base_t;
struct address_t; struct address_t;
@@ -47,18 +46,21 @@ namespace zmq
class ipc_connecter_t : public own_t, public io_object_t class ipc_connecter_t : public own_t, public io_object_t
{ {
public: public:
// If 'delayed_start' is true connecter first waits for a while, // If 'delayed_start' is true connecter first waits for a while,
// then starts connection process. // then starts connection process.
ipc_connecter_t (zmq::io_thread_t *io_thread_, ipc_connecter_t (zmq::io_thread_t *io_thread_,
zmq::session_base_t *session_, const options_t &options_, zmq::session_base_t *session_,
const address_t *addr_, bool delayed_start_); const options_t &options_,
const address_t *addr_,
bool delayed_start_);
~ipc_connecter_t (); ~ipc_connecter_t ();
private: private:
// ID of the timer used to delay the reconnection. // ID of the timer used to delay the reconnection.
enum {reconnect_timer_id = 1}; enum
{
reconnect_timer_id = 1
};
// Handlers for incoming commands. // Handlers for incoming commands.
void process_plug (); void process_plug ();
@@ -126,10 +128,8 @@ namespace zmq
ipc_connecter_t (const ipc_connecter_t &); ipc_connecter_t (const ipc_connecter_t &);
const ipc_connecter_t &operator= (const ipc_connecter_t &); const ipc_connecter_t &operator= (const ipc_connecter_t &);
}; };
} }
#endif #endif
#endif #endif

View File

@@ -65,9 +65,7 @@
#endif #endif
const char *zmq::ipc_listener_t::tmp_env_vars[] = { const char *zmq::ipc_listener_t::tmp_env_vars[] = {
"TMPDIR", "TMPDIR", "TEMPDIR", "TMP",
"TEMPDIR",
"TMP",
0 // Sentinel 0 // Sentinel
}; };
@@ -84,7 +82,8 @@ int zmq::ipc_listener_t::create_wildcard_address(std::string& path_,
struct stat statbuf; struct stat statbuf;
// Confirm it is actually a directory before trying to use // Confirm it is actually a directory before trying to use
if ( tmpdir != 0 && ::stat(tmpdir, &statbuf) == 0 && S_ISDIR(statbuf.st_mode) ) { if (tmpdir != 0 && ::stat (tmpdir, &statbuf) == 0
&& S_ISDIR (statbuf.st_mode)) {
tmp_path.assign (tmpdir); tmp_path.assign (tmpdir);
if (*(tmp_path.rbegin ()) != '/') { if (*(tmp_path.rbegin ()) != '/') {
tmp_path.push_back ('/'); tmp_path.push_back ('/');
@@ -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_, 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_), own_t (io_thread_, options_),
io_object_t (io_thread_), io_object_t (io_thread_),
has_file (false), has_file (false),
@@ -171,8 +171,8 @@ void zmq::ipc_listener_t::in_event ()
} }
// Create the engine object for this connection. // Create the engine object for this connection.
stream_engine_t *engine = new (std::nothrow) stream_engine_t *engine =
stream_engine_t (fd, options, endpoint); new (std::nothrow) stream_engine_t (fd, options, endpoint);
alloc_assert (engine); alloc_assert (engine);
// Choose I/O thread to run connecter in. Given that we are already // 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); zmq_assert (io_thread);
// Create and launch a session object. // Create and launch a session object.
session_base_t *session = session_base_t::create (io_thread, false, socket, session_base_t *session =
options, NULL); session_base_t::create (io_thread, false, socket, options, NULL);
errno_assert (session); errno_assert (session);
session->inc_seqnum (); session->inc_seqnum ();
launch_child (session); launch_child (session);
@@ -317,9 +317,9 @@ int zmq::ipc_listener_t::close ()
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 () && if (options.ipc_uid_accept_filters.empty ()
options.ipc_pid_accept_filters.empty () && && options.ipc_pid_accept_filters.empty ()
options.ipc_gid_accept_filters.empty ()) && options.ipc_gid_accept_filters.empty ())
return true; return true;
struct ucred cred; 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)) if (getsockopt (sock, SOL_SOCKET, SO_PEERCRED, &cred, &size))
return false; return false;
if (options.ipc_uid_accept_filters.find (cred.uid) != options.ipc_uid_accept_filters.end () || if (options.ipc_uid_accept_filters.find (cred.uid)
options.ipc_gid_accept_filters.find (cred.gid) != options.ipc_gid_accept_filters.end () || != options.ipc_uid_accept_filters.end ()
options.ipc_pid_accept_filters.find (cred.pid) != options.ipc_pid_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; return true;
struct passwd *pw; struct passwd *pw;
@@ -337,7 +340,8 @@ bool zmq::ipc_listener_t::filter (fd_t sock)
if (!(pw = getpwuid (cred.uid))) if (!(pw = getpwuid (cred.uid)))
return false; return false;
for (options_t::ipc_gid_accept_filters_t::const_iterator it = options.ipc_gid_accept_filters.begin (); 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++) { it != options.ipc_gid_accept_filters.end (); it++) {
if (!(gr = getgrgid (*it))) if (!(gr = getgrgid (*it)))
continue; continue;
@@ -353,8 +357,8 @@ bool zmq::ipc_listener_t::filter (fd_t sock)
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 () && if (options.ipc_uid_accept_filters.empty ()
options.ipc_gid_accept_filters.empty ()) && options.ipc_gid_accept_filters.empty ())
return true; return true;
struct xucred cred; struct xucred cred;
@@ -364,10 +368,12 @@ bool zmq::ipc_listener_t::filter (fd_t sock)
return false; return false;
if (cred.cr_version != XUCRED_VERSION) if (cred.cr_version != XUCRED_VERSION)
return false; 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; return true;
for (int i = 0; i < cred.cr_ngroups; i++) { 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; return true;
} }
@@ -388,13 +394,14 @@ zmq::fd_t zmq::ipc_listener_t::accept ()
fd_t sock = ::accept (s, NULL, NULL); fd_t sock = ::accept (s, NULL, NULL);
#endif #endif
if (sock == -1) { if (sock == -1) {
errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR
errno == EINTR || errno == ECONNABORTED || errno == EPROTO || || errno == ECONNABORTED || errno == EPROTO
errno == ENFILE); || errno == ENFILE);
return retired_fd; 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 // Race condition can cause socket not to be closed (if fork happens
// between accept and this point). // between accept and this point).
int rc = fcntl (sock, F_SETFD, FD_CLOEXEC); int rc = fcntl (sock, F_SETFD, FD_CLOEXEC);

View File

@@ -41,16 +41,15 @@
namespace zmq namespace zmq
{ {
class io_thread_t; class io_thread_t;
class socket_base_t; class socket_base_t;
class ipc_listener_t : public own_t, public io_object_t class ipc_listener_t : public own_t, public io_object_t
{ {
public: public:
ipc_listener_t (zmq::io_thread_t *io_thread_, ipc_listener_t (zmq::io_thread_t *io_thread_,
zmq::socket_base_t *socket_, const options_t &options_); zmq::socket_base_t *socket_,
const options_t &options_);
~ipc_listener_t (); ~ipc_listener_t ();
// Set address to listen on. // Set address to listen on.
@@ -60,7 +59,6 @@ namespace zmq
int get_address (std::string &addr_); int get_address (std::string &addr_);
private: private:
// Handlers for incoming commands. // Handlers for incoming commands.
void process_plug (); void process_plug ();
void process_term (int linger_); void process_term (int linger_);
@@ -72,8 +70,7 @@ namespace zmq
int close (); int close ();
// Create wildcard path address // Create wildcard path address
static int create_wildcard_address(std::string& path_, static int create_wildcard_address (std::string &path_, std::string &file_);
std::string& file_);
// Filter new connections if the OS provides a mechanism to get // Filter new connections if the OS provides a mechanism to get
// the credentials of the peer process. Called from accept(). // the credentials of the peer process. Called from accept().
@@ -114,10 +111,8 @@ namespace zmq
ipc_listener_t (const ipc_listener_t &); ipc_listener_t (const ipc_listener_t &);
const ipc_listener_t &operator= (const ipc_listener_t &); const ipc_listener_t &operator= (const ipc_listener_t &);
}; };
} }
#endif #endif
#endif #endif

View File

@@ -54,9 +54,7 @@
#define kevent_udata_t void * #define kevent_udata_t void *
#endif #endif
zmq::kqueue_t::kqueue_t (const zmq::ctx_t &ctx_) : zmq::kqueue_t::kqueue_t (const zmq::ctx_t &ctx_) : ctx (ctx_), stopping (false)
ctx(ctx_),
stopping (false)
{ {
// Create event queue // Create event queue
kqueue_fd = kqueue (); kqueue_fd = kqueue ();
@@ -173,7 +171,6 @@ int zmq::kqueue_t::max_fds ()
void zmq::kqueue_t::loop () void zmq::kqueue_t::loop ()
{ {
while (!stopping) { while (!stopping) {
// Execute any due timers. // Execute any due timers.
int timeout = (int) execute_timers (); int timeout = (int) execute_timers ();
@@ -212,7 +209,8 @@ void zmq::kqueue_t::loop ()
} }
// Destroy retired event sources. // Destroy retired event sources.
for (retired_t::iterator it = retired.begin (); it != retired.end (); ++it) { for (retired_t::iterator it = retired.begin (); it != retired.end ();
++it) {
LIBZMQ_DELETE (*it); LIBZMQ_DELETE (*it);
} }
retired.clear (); retired.clear ();

View File

@@ -44,7 +44,6 @@
namespace zmq namespace zmq
{ {
struct i_poll_events; struct i_poll_events;
// Implements socket polling mechanism using the BSD-specific // Implements socket polling mechanism using the BSD-specific
@@ -53,7 +52,6 @@ namespace zmq
class kqueue_t : public poller_base_t class kqueue_t : public poller_base_t
{ {
public: public:
typedef void *handle_t; typedef void *handle_t;
kqueue_t (const ctx_t &ctx_); kqueue_t (const ctx_t &ctx_);
@@ -72,7 +70,6 @@ namespace zmq
static int max_fds (); static int max_fds ();
private: private:
// Main worker thread routine. // Main worker thread routine.
static void worker_routine (void *arg_); static void worker_routine (void *arg_);
@@ -119,7 +116,6 @@ namespace zmq
}; };
typedef kqueue_t poller_t; typedef kqueue_t poller_t;
} }
#endif #endif

View File

@@ -33,11 +33,7 @@
#include "err.hpp" #include "err.hpp"
#include "msg.hpp" #include "msg.hpp"
zmq::lb_t::lb_t () : zmq::lb_t::lb_t () : active (0), current (0), more (false), dropping (false)
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 // Drop the message if required. If we are at the end of the message
// switch back to non-dropping mode. // switch back to non-dropping mode.
if (dropping) { if (dropping) {
more = msg_->flags () & msg_t::more ? true : false; more = msg_->flags () & msg_t::more ? true : false;
dropping = more; dropping = more;
@@ -101,8 +96,7 @@ int zmq::lb_t::sendpipe (msg_t *msg_, pipe_t **pipe_)
} }
while (active > 0) { while (active > 0) {
if (pipes [current]->write (msg_)) if (pipes[current]->write (msg_)) {
{
if (pipe_) if (pipe_)
*pipe_ = pipes[current]; *pipe_ = pipes[current];
break; break;
@@ -111,8 +105,7 @@ int zmq::lb_t::sendpipe (msg_t *msg_, pipe_t **pipe_)
// If send fails for multi-part msg rollback other // If send fails for multi-part msg rollback other
// parts sent earlier and return EAGAIN. // parts sent earlier and return EAGAIN.
// Application should handle this as suitable // Application should handle this as suitable
if (more) if (more) {
{
pipes[current]->rollback (); pipes[current]->rollback ();
more = 0; more = 0;
errno = EAGAIN; errno = EAGAIN;
@@ -157,7 +150,6 @@ bool zmq::lb_t::has_out ()
return true; return true;
while (active > 0) { while (active > 0) {
// Check whether a pipe has room for another message. // Check whether a pipe has room for another message.
if (pipes[current]->check_write ()) if (pipes[current]->check_write ())
return true; return true;

View File

@@ -35,14 +35,12 @@
namespace zmq namespace zmq
{ {
// This class manages a set of outbound pipes. On send it load balances // This class manages a set of outbound pipes. On send it load balances
// messages fairly among the pipes. // messages fairly among the pipes.
class lb_t class lb_t
{ {
public: public:
lb_t (); lb_t ();
~lb_t (); ~lb_t ();
@@ -61,7 +59,6 @@ namespace zmq
bool has_out (); bool has_out ();
private: private:
// List of outbound pipes. // List of outbound pipes.
typedef array_t<pipe_t, 2> pipes_t; typedef array_t<pipe_t, 2> pipes_t;
pipes_t pipes; pipes_t pipes;
@@ -82,7 +79,6 @@ namespace zmq
lb_t (const lb_t &); lb_t (const lb_t &);
const lb_t &operator= (const lb_t &); const lb_t &operator= (const lb_t &);
}; };
} }
#endif #endif

View File

@@ -4,7 +4,8 @@
/******************************************************************************/ /******************************************************************************/
#define LIBZMQ_UNUSED(object) (void) object #define LIBZMQ_UNUSED(object) (void) object
#define LIBZMQ_DELETE(p_object) {\ #define LIBZMQ_DELETE(p_object) \
{ \
delete p_object; \ delete p_object; \
p_object = 0; \ p_object = 0; \
} }

View File

@@ -42,11 +42,9 @@
namespace zmq namespace zmq
{ {
class mailbox_t : public i_mailbox class mailbox_t : public i_mailbox
{ {
public: public:
mailbox_t (); mailbox_t ();
~mailbox_t (); ~mailbox_t ();
@@ -64,7 +62,6 @@ namespace zmq
#endif #endif
private: private:
// The pipe to store actual commands. // The pipe to store actual commands.
typedef ypipe_t<command_t, command_pipe_granularity> cpipe_t; typedef ypipe_t<command_t, command_pipe_granularity> cpipe_t;
cpipe_t cpipe; cpipe_t cpipe;
@@ -86,7 +83,6 @@ namespace zmq
mailbox_t (const mailbox_t &); mailbox_t (const mailbox_t &);
const mailbox_t &operator= (const mailbox_t &); const mailbox_t &operator= (const mailbox_t &);
}; };
} }
#endif #endif

View File

@@ -32,8 +32,7 @@
#include "clock.hpp" #include "clock.hpp"
#include "err.hpp" #include "err.hpp"
zmq::mailbox_safe_t::mailbox_safe_t (mutex_t* sync_) : zmq::mailbox_safe_t::mailbox_safe_t (mutex_t *sync_) : sync (sync_)
sync (sync_)
{ {
// Get the pipe into passive state. That way, if the users starts by // 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 // polling on the associated file descriptor it will get woken up when
@@ -84,7 +83,8 @@ void zmq::mailbox_safe_t::send (const command_t &cmd_)
if (!ok) { if (!ok) {
cond_var.broadcast (); cond_var.broadcast ();
for (std::vector<signaler_t*>::iterator it = signalers.begin(); it != signalers.end(); ++it){ for (std::vector<signaler_t *>::iterator it = signalers.begin ();
it != signalers.end (); ++it) {
(*it)->send (); (*it)->send ();
} }
} }

View File

@@ -44,11 +44,9 @@
namespace zmq namespace zmq
{ {
class mailbox_safe_t : public i_mailbox class mailbox_safe_t : public i_mailbox
{ {
public: public:
mailbox_safe_t (mutex_t *sync_); mailbox_safe_t (mutex_t *sync_);
~mailbox_safe_t (); ~mailbox_safe_t ();
@@ -71,7 +69,6 @@ namespace zmq
#endif #endif
private: private:
// The pipe to store actual commands. // The pipe to store actual commands.
typedef ypipe_t<command_t, command_pipe_granularity> cpipe_t; typedef ypipe_t<command_t, command_pipe_granularity> cpipe_t;
cpipe_t cpipe; cpipe_t cpipe;
@@ -88,7 +85,6 @@ namespace zmq
mailbox_safe_t (const mailbox_safe_t &); mailbox_safe_t (const mailbox_safe_t &);
const mailbox_safe_t &operator= (const mailbox_safe_t &); const mailbox_safe_t &operator= (const mailbox_safe_t &);
}; };
} }
#endif #endif

View File

@@ -37,8 +37,7 @@
#include "wire.hpp" #include "wire.hpp"
#include "session_base.hpp" #include "session_base.hpp"
zmq::mechanism_t::mechanism_t (const options_t &options_) : zmq::mechanism_t::mechanism_t (const options_t &options_) : options (options_)
options (options_)
{ {
} }
@@ -73,12 +72,10 @@ const zmq::blob_t &zmq::mechanism_t::get_user_id () const
const char *zmq::mechanism_t::socket_type_string (int socket_type) const const char *zmq::mechanism_t::socket_type_string (int socket_type) const
{ {
static const char *names [] = {"PAIR", "PUB", "SUB", "REQ", "REP", static const char *names[] = {
"DEALER", "ROUTER", "PULL", "PUSH", "PAIR", "PUB", "SUB", "REQ", "REP", "DEALER", "ROUTER",
"XPUB", "XSUB", "STREAM", "PULL", "PUSH", "XPUB", "XSUB", "STREAM", "SERVER", "CLIENT",
"SERVER", "CLIENT", "RADIO", "DISH", "GATHER", "SCATTER", "DGRAM"};
"RADIO", "DISH",
"GATHER", "SCATTER", "DGRAM"};
zmq_assert (socket_type >= 0 && socket_type <= 18); zmq_assert (socket_type >= 0 && socket_type <= 18);
return names[socket_type]; return names[socket_type];
} }
@@ -131,16 +128,15 @@ size_t zmq::mechanism_t::add_basic_properties (unsigned char *buf,
// Add socket type property // Add socket type property
const char *socket_type = socket_type_string (options.type); const char *socket_type = socket_type_string (options.type);
ptr += add_property (ptr, buf_capacity, ptr += add_property (ptr, buf_capacity, ZMTP_PROPERTY_SOCKET_TYPE,
ZMTP_PROPERTY_SOCKET_TYPE, socket_type, socket_type, strlen (socket_type));
strlen (socket_type));
// Add identity (aka routing id) property // Add identity (aka routing id) property
if (options.type == ZMQ_REQ || options.type == ZMQ_DEALER if (options.type == ZMQ_REQ || options.type == ZMQ_DEALER
|| options.type == ZMQ_ROUTER) || options.type == ZMQ_ROUTER)
ptr += add_property (ptr, buf_capacity - (ptr - buf), ptr +=
ZMTP_PROPERTY_IDENTITY, options.routing_id, add_property (ptr, buf_capacity - (ptr - buf), ZMTP_PROPERTY_IDENTITY,
options.routing_id_size); options.routing_id, options.routing_id_size);
return ptr - buf; return ptr - buf;
} }
@@ -151,8 +147,7 @@ size_t zmq::mechanism_t::basic_properties_len() const
return property_len (ZMTP_PROPERTY_SOCKET_TYPE, strlen (socket_type)) return property_len (ZMTP_PROPERTY_SOCKET_TYPE, strlen (socket_type))
+ ((options.type == ZMQ_REQ || options.type == ZMQ_DEALER + ((options.type == ZMQ_REQ || options.type == ZMQ_DEALER
|| options.type == ZMQ_ROUTER) || options.type == ZMQ_ROUTER)
? property_len (ZMTP_PROPERTY_IDENTITY, ? property_len (ZMTP_PROPERTY_IDENTITY, options.routing_id_size)
options.routing_id_size)
: 0); : 0);
} }
@@ -169,8 +164,8 @@ void zmq::mechanism_t::make_command_with_basic_properties (
memcpy (ptr, prefix, prefix_len); memcpy (ptr, prefix, prefix_len);
ptr += prefix_len; ptr += prefix_len;
add_basic_properties ( add_basic_properties (ptr, command_size
ptr, command_size - (ptr - (unsigned char *) msg_->data ())); - (ptr - (unsigned char *) msg_->data ()));
} }
int zmq::mechanism_t::parse_metadata (const unsigned char *ptr_, int zmq::mechanism_t::parse_metadata (const unsigned char *ptr_,
@@ -204,15 +199,13 @@ int zmq::mechanism_t::parse_metadata (const unsigned char *ptr_,
if (name == ZMTP_PROPERTY_IDENTITY && options.recv_routing_id) if (name == ZMTP_PROPERTY_IDENTITY && options.recv_routing_id)
set_peer_routing_id (value, value_length); set_peer_routing_id (value, value_length);
else else if (name == ZMTP_PROPERTY_SOCKET_TYPE) {
if (name == ZMTP_PROPERTY_SOCKET_TYPE) {
const std::string socket_type ((char *) value, value_length); const std::string socket_type ((char *) value, value_length);
if (!check_socket_type (socket_type)) { if (!check_socket_type (socket_type)) {
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
} } else {
else {
const int rc = property (name, value, value_length); const int rc = property (name, value, value_length);
if (rc == -1) if (rc == -1)
return -1; return -1;
@@ -232,7 +225,8 @@ int zmq::mechanism_t::parse_metadata (const unsigned char *ptr_,
} }
int zmq::mechanism_t::property (const std::string & /* name_ */, int zmq::mechanism_t::property (const std::string & /* name_ */,
const void * /* value_ */, size_t /* length_ */) const void * /* value_ */,
size_t /* length_ */)
{ {
// Default implementation does not check // Default implementation does not check
// property values and returns 0 to signal success. // property values and returns 0 to signal success.

View File

@@ -37,7 +37,6 @@
namespace zmq namespace zmq
{ {
class msg_t; class msg_t;
class session_base_t; class session_base_t;
@@ -47,8 +46,8 @@ namespace zmq
class mechanism_t class mechanism_t
{ {
public: public:
enum status_t
enum status_t { {
handshaking, handshaking,
ready, ready,
error error
@@ -82,16 +81,11 @@ namespace zmq
const blob_t &get_user_id () const; const blob_t &get_user_id () const;
const metadata_t::dict_t& get_zmtp_properties () { const metadata_t::dict_t &get_zmtp_properties () { return zmtp_properties; }
return zmtp_properties;
}
const metadata_t::dict_t& get_zap_properties () { const metadata_t::dict_t &get_zap_properties () { return zap_properties; }
return zap_properties;
}
protected: protected:
// Only used to identify the socket for the Socket-Type // Only used to identify the socket for the Socket-Type
// property in the wire protocol. // property in the wire protocol.
const char *socket_type_string (int socket_type) const; const char *socket_type_string (int socket_type) const;
@@ -101,8 +95,7 @@ namespace zmq
const char *name, const char *name,
const void *value, const void *value,
size_t value_len); size_t value_len);
static size_t property_len (const char *name, static size_t property_len (const char *name, size_t value_len);
size_t value_len);
size_t add_basic_properties (unsigned char *ptr, size_t ptr_capacity) const; size_t add_basic_properties (unsigned char *ptr, size_t ptr_capacity) const;
size_t basic_properties_len () const; size_t basic_properties_len () const;
@@ -115,8 +108,9 @@ namespace zmq
// Metadata consists of a list of properties consisting of // Metadata consists of a list of properties consisting of
// name and value as size-specified strings. // name and value as size-specified strings.
// Returns 0 on success and -1 on error, in which case errno is set. // Returns 0 on success and -1 on error, in which case errno is set.
int parse_metadata ( int parse_metadata (const unsigned char *ptr_,
const unsigned char *ptr_, size_t length, bool zap_flag = false); size_t length,
bool zap_flag = false);
// This is called by parse_property method whenever it // This is called by parse_property method whenever it
// parses a new property. The function should return 0 // parses a new property. The function should return 0
@@ -125,8 +119,8 @@ namespace zmq
// parsing remaining data. // parsing remaining data.
// Derived classes are supposed to override this // Derived classes are supposed to override this
// method to handle custom processing. // method to handle custom processing.
virtual int property (const std::string& name_, virtual int
const void *value_, size_t length_); property (const std::string &name_, const void *value_, size_t length_);
// Properties received from ZMTP peer. // Properties received from ZMTP peer.
metadata_t::dict_t zmtp_properties; metadata_t::dict_t zmtp_properties;
@@ -137,7 +131,6 @@ namespace zmq
options_t options; options_t options;
private: private:
blob_t routing_id; blob_t routing_id;
blob_t user_id; blob_t user_id;
@@ -146,7 +139,6 @@ namespace zmq
// is compatible with a given socket type 'type_'. // is compatible with a given socket type 'type_'.
bool check_socket_type (const std::string &type_) const; bool check_socket_type (const std::string &type_) const;
}; };
} }
#endif #endif

View File

@@ -37,7 +37,6 @@ zmq::mechanism_base_t::mechanism_base_t (session_base_t *const session_,
mechanism_t (options_), mechanism_t (options_),
session (session_) session (session_)
{ {
} }
int zmq::mechanism_base_t::check_basic_command_structure (msg_t *msg_) int zmq::mechanism_base_t::check_basic_command_structure (msg_t *msg_)

View File

@@ -44,7 +44,8 @@ class mechanism_base_t : public mechanism_t
int check_basic_command_structure (msg_t *msg_); 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;
}; };

View File

@@ -30,24 +30,20 @@
#include "precompiled.hpp" #include "precompiled.hpp"
#include "metadata.hpp" #include "metadata.hpp"
zmq::metadata_t::metadata_t (const dict_t &dict) : zmq::metadata_t::metadata_t (const dict_t &dict) : ref_cnt (1), dict (dict)
ref_cnt (1),
dict (dict)
{ {
} }
const char *zmq::metadata_t::get (const std::string &property) const const char *zmq::metadata_t::get (const std::string &property) const
{ {
dict_t::const_iterator it = dict.find (property); 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 */ /** \todo remove this when support for the deprecated name "Identity" is dropped */
if (property == "Identity") if (property == "Identity")
return get (ZMQ_MSG_PROPERTY_ROUTING_ID); return get (ZMQ_MSG_PROPERTY_ROUTING_ID);
return NULL; return NULL;
} } else
else
return it->second.c_str (); return it->second.c_str ();
} }

View File

@@ -64,7 +64,6 @@ namespace zmq
// Dictionary holding metadata. // Dictionary holding metadata.
dict_t dict; dict_t dict;
}; };
} }
#endif #endif

View File

@@ -43,37 +43,30 @@
// Check whether the sizes of public representation of the message (zmq_msg_t) // Check whether the sizes of public representation of the message (zmq_msg_t)
// and private representation of the message (zmq::msg_t) match. // and private representation of the message (zmq::msg_t) match.
typedef char zmq_msg_size_check typedef char
[2 * ((sizeof (zmq::msg_t) == sizeof (zmq_msg_t)) != 0) - 1]; zmq_msg_size_check[2 * ((sizeof (zmq::msg_t) == sizeof (zmq_msg_t)) != 0)
- 1];
bool zmq::msg_t::check () const 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_, int zmq::msg_t::init (
msg_free_fn* ffn_, void* hint, void *data_, size_t size_, msg_free_fn *ffn_, void *hint, content_t *content_)
content_t* content_)
{ {
if (size_ < max_vsm_size) { if (size_ < max_vsm_size) {
int const rc = init_size (size_); int const rc = init_size (size_);
if (rc != -1) if (rc != -1) {
{
memcpy (data (), data_, size_); memcpy (data (), data_, size_);
return 0; return 0;
} } else {
else
{
return -1; return -1;
} }
} } else if (content_) {
else if(content_)
{
return init_external_storage (content_, data_, size_, ffn_, hint); return init_external_storage (content_, data_, size_, ffn_, hint);
} } else {
else
{
return init_data (data_, size_, ffn_, hint); 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.size = (unsigned char) size_;
u.vsm.group[0] = '\0'; u.vsm.group[0] = '\0';
u.vsm.routing_id = 0; u.vsm.routing_id = 0;
} } else {
else {
u.lmsg.metadata = NULL; u.lmsg.metadata = NULL;
u.lmsg.type = type_lmsg; u.lmsg.type = type_lmsg;
u.lmsg.flags = 0; u.lmsg.flags = 0;
@@ -122,8 +114,11 @@ int zmq::msg_t::init_size (size_t size_)
return 0; return 0;
} }
int zmq::msg_t::init_external_storage(content_t* content_, void* data_, size_t size_, int zmq::msg_t::init_external_storage (content_t *content_,
msg_free_fn *ffn_, void* hint_) void *data_,
size_t size_,
msg_free_fn *ffn_,
void *hint_)
{ {
zmq_assert (NULL != data_); zmq_assert (NULL != data_);
zmq_assert (NULL != content_); zmq_assert (NULL != content_);
@@ -144,8 +139,10 @@ int zmq::msg_t::init_external_storage(content_t* content_, void* data_, size_t s
return 0; return 0;
} }
int zmq::msg_t::init_data (void *data_, size_t size_, int zmq::msg_t::init_data (void *data_,
msg_free_fn *ffn_, void *hint_) size_t size_,
msg_free_fn *ffn_,
void *hint_)
{ {
// If data is NULL and size is not 0, a segfault // If data is NULL and size is not 0, a segfault
// would occur once the data is accessed // would occur once the data is accessed
@@ -160,8 +157,7 @@ int zmq::msg_t::init_data (void *data_, size_t size_,
u.cmsg.size = size_; u.cmsg.size = size_;
u.cmsg.group[0] = '\0'; u.cmsg.group[0] = '\0';
u.cmsg.routing_id = 0; u.cmsg.routing_id = 0;
} } else {
else {
u.lmsg.metadata = NULL; u.lmsg.metadata = NULL;
u.lmsg.type = type_lmsg; u.lmsg.type = type_lmsg;
u.lmsg.flags = 0; u.lmsg.flags = 0;
@@ -180,7 +176,6 @@ int zmq::msg_t::init_data (void *data_, size_t size_,
new (&u.lmsg.content->refcnt) zmq::atomic_counter_t (); new (&u.lmsg.content->refcnt) zmq::atomic_counter_t ();
} }
return 0; return 0;
} }
int zmq::msg_t::init_delimiter () int zmq::msg_t::init_delimiter ()
@@ -222,12 +217,10 @@ int zmq::msg_t::close ()
} }
if (u.base.type == type_lmsg) { if (u.base.type == type_lmsg) {
// If the content is not shared, or if it is shared and the reference // If the content is not shared, or if it is shared and the reference
// count has dropped to zero, deallocate it. // count has dropped to zero, deallocate it.
if (!(u.lmsg.flags & msg_t::shared) || if (!(u.lmsg.flags & msg_t::shared)
!u.lmsg.content->refcnt.sub (1)) { || !u.lmsg.content->refcnt.sub (1)) {
// We used "placement new" operator to initialize the reference // We used "placement new" operator to initialize the reference
// counter so we call the destructor explicitly now. // counter so we call the destructor explicitly now.
u.lmsg.content->refcnt.~atomic_counter_t (); u.lmsg.content->refcnt.~atomic_counter_t ();
@@ -239,15 +232,13 @@ int zmq::msg_t::close ()
} }
} }
if (is_zcmsg()) if (is_zcmsg ()) {
{
zmq_assert (u.zclmsg.content->ffn); zmq_assert (u.zclmsg.content->ffn);
// If the content is not shared, or if it is shared and the reference // If the content is not shared, or if it is shared and the reference
// count has dropped to zero, deallocate it. // count has dropped to zero, deallocate it.
if (!(u.zclmsg.flags & msg_t::shared) || if (!(u.zclmsg.flags & msg_t::shared)
!u.zclmsg.content->refcnt.sub (1)) { || !u.zclmsg.content->refcnt.sub (1)) {
// We used "placement new" operator to initialize the reference // We used "placement new" operator to initialize the reference
// counter so we call the destructor explicitly now. // counter so we call the destructor explicitly now.
u.zclmsg.content->refcnt.~atomic_counter_t (); u.zclmsg.content->refcnt.~atomic_counter_t ();
@@ -304,7 +295,6 @@ int zmq::msg_t::copy (msg_t &src_)
return rc; 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 // One reference is added to shared messages. Non-shared messages
// are turned into shared messages and reference count is set to 2. // are turned into shared messages and reference count is set to 2.
if (src_.u.lmsg.flags & msg_t::shared) if (src_.u.lmsg.flags & msg_t::shared)
@@ -316,7 +306,6 @@ 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 // One reference is added to shared messages. Non-shared messages
// are turned into shared messages and reference count is set to 2. // are turned into shared messages and reference count is set to 2.
if (src_.u.zclmsg.flags & msg_t::shared) if (src_.u.zclmsg.flags & msg_t::shared)
@@ -332,7 +321,6 @@ int zmq::msg_t::copy (msg_t &src_)
*this = src_; *this = src_;
return 0; return 0;
} }
void *zmq::msg_t::data () void *zmq::msg_t::data ()
@@ -488,7 +476,8 @@ bool zmq::msg_t::rm_refs (int refs_)
return true; return true;
// If there's only one reference close the message. // 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 (); close ();
return false; return false;
} }
@@ -509,7 +498,8 @@ bool zmq::msg_t::rm_refs (int refs_)
if (is_zcmsg () && !u.zclmsg.content->refcnt.sub (refs_)) { if (is_zcmsg () && !u.zclmsg.content->refcnt.sub (refs_)) {
// storage for rfcnt is provided externally // storage for rfcnt is provided externally
if (u.zclmsg.content->ffn) { 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; return false;
@@ -551,8 +541,7 @@ int zmq::msg_t::set_group (const char * 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; errno = EINVAL;
return -1; return -1;
} }
@@ -565,8 +554,7 @@ int zmq::msg_t::set_group (const char * group_, size_t length_)
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: case type_lmsg:
return &u.lmsg.content->refcnt; return &u.lmsg.content->refcnt;
case type_zclmsg: case type_zclmsg:

View File

@@ -42,21 +42,18 @@
// Signature for free function to deallocate the message content. // 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 // Note that it has to be declared as "C" so that it is the same as
// zmq_free_fn defined in zmq.h. // zmq_free_fn defined in zmq.h.
extern "C" extern "C" {
{
typedef void(msg_free_fn) (void *data, void *hint); typedef void(msg_free_fn) (void *data, void *hint);
} }
namespace zmq namespace zmq
{ {
// Note that this structure needs to be explicitly constructed // Note that this structure needs to be explicitly constructed
// (init functions) and destructed (close function). // (init functions) and destructed (close function).
class msg_t class msg_t
{ {
public: public:
// Shared message buffer. Message data are either allocated in one // Shared message buffer. Message data are either allocated in one
// continuous block along with this structure - thus avoiding one // continuous block along with this structure - thus avoiding one
// malloc/free pair or they are stored in user-supplied memory. // malloc/free pair or they are stored in user-supplied memory.
@@ -86,15 +83,19 @@ namespace zmq
bool check () const; bool check () const;
int init (); int init ();
int init (void* data, size_t size_, int init (void *data,
msg_free_fn* ffn_, void* hint, size_t size_,
msg_free_fn *ffn_,
void *hint,
content_t *content_ = NULL); content_t *content_ = NULL);
int init_size (size_t size_); int init_size (size_t size_);
int init_data (void *data_, size_t size_, msg_free_fn *ffn_, 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_); 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_delimiter ();
int init_join (); int init_join ();
int init_leave (); int init_leave ();
@@ -134,11 +135,16 @@ namespace zmq
// Size in bytes of the largest message that is still copied around // Size in bytes of the largest message that is still copied around
// rather than being reference-counted. // rather than being reference-counted.
enum { msg_t_size = 64 }; enum
enum { max_vsm_size = msg_t_size - (sizeof (metadata_t *) + {
3 + msg_t_size = 64
16 + };
sizeof (uint32_t))}; enum
{
max_vsm_size =
msg_t_size - (sizeof (metadata_t *) + 3 + 16 + sizeof (uint32_t))
};
private: private:
zmq::atomic_counter_t *refcnt (); zmq::atomic_counter_t *refcnt ();
@@ -171,19 +177,21 @@ namespace zmq
// moved to the parent class (msg_t). This way we get tighter packing // 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 // of the data. Shared fields can be accessed via 'base' member of
// the union. // the union.
union { union
struct { {
struct
{
metadata_t *metadata; metadata_t *metadata;
unsigned char unused [msg_t_size - (sizeof (metadata_t *) + unsigned char
2 + unused[msg_t_size
16 + - (sizeof (metadata_t *) + 2 + 16 + sizeof (uint32_t))];
sizeof (uint32_t))];
unsigned char type; unsigned char type;
unsigned char flags; unsigned char flags;
char group[16]; char group[16];
uint32_t routing_id; uint32_t routing_id;
} base; } base;
struct { struct
{
metadata_t *metadata; metadata_t *metadata;
unsigned char data[max_vsm_size]; unsigned char data[max_vsm_size];
unsigned char size; unsigned char size;
@@ -192,53 +200,50 @@ namespace zmq
char group[16]; char group[16];
uint32_t routing_id; uint32_t routing_id;
} vsm; } vsm;
struct { struct
{
metadata_t *metadata; metadata_t *metadata;
content_t *content; content_t *content;
unsigned char unused [msg_t_size - (sizeof (metadata_t *) + unsigned char unused[msg_t_size
sizeof (content_t*) + - (sizeof (metadata_t *) + sizeof (content_t *)
2 + + 2 + 16 + sizeof (uint32_t))];
16 +
sizeof (uint32_t))];
unsigned char type; unsigned char type;
unsigned char flags; unsigned char flags;
char group[16]; char group[16];
uint32_t routing_id; uint32_t routing_id;
} lmsg; } lmsg;
struct { struct
{
metadata_t *metadata; metadata_t *metadata;
content_t *content; content_t *content;
unsigned char unused [msg_t_size - (sizeof (metadata_t *) + unsigned char unused[msg_t_size
sizeof (content_t*) + - (sizeof (metadata_t *) + sizeof (content_t *)
2 + + 2 + 16 + sizeof (uint32_t))];
16 +
sizeof (uint32_t))];
unsigned char type; unsigned char type;
unsigned char flags; unsigned char flags;
char group[16]; char group[16];
uint32_t routing_id; uint32_t routing_id;
} zclmsg; } zclmsg;
struct { struct
{
metadata_t *metadata; metadata_t *metadata;
void *data; void *data;
size_t size; size_t size;
unsigned char unused [msg_t_size - (sizeof (metadata_t *) + unsigned char
sizeof (void*) + unused[msg_t_size
sizeof (size_t) + - (sizeof (metadata_t *) + sizeof (void *)
2 + + sizeof (size_t) + 2 + 16 + sizeof (uint32_t))];
16 +
sizeof (uint32_t))];
unsigned char type; unsigned char type;
unsigned char flags; unsigned char flags;
char group[16]; char group[16];
uint32_t routing_id; uint32_t routing_id;
} cmsg; } cmsg;
struct { struct
{
metadata_t *metadata; metadata_t *metadata;
unsigned char unused [msg_t_size - (sizeof (metadata_t *) + unsigned char
2 + unused[msg_t_size
16 + - (sizeof (metadata_t *) + 2 + 16 + sizeof (uint32_t))];
sizeof (uint32_t))];
unsigned char type; unsigned char type;
unsigned char flags; unsigned char flags;
char group[16]; char group[16];

View File

@@ -38,11 +38,7 @@
#include "macros.hpp" #include "macros.hpp"
#include "mtrie.hpp" #include "mtrie.hpp"
zmq::mtrie_t::mtrie_t () : zmq::mtrie_t::mtrie_t () : pipes (0), min (0), count (0), live_nodes (0)
pipes (0),
min (0),
count (0),
live_nodes (0)
{ {
} }
@@ -53,8 +49,7 @@ zmq::mtrie_t::~mtrie_t ()
if (count == 1) { if (count == 1) {
zmq_assert (next.node); zmq_assert (next.node);
LIBZMQ_DELETE (next.node); LIBZMQ_DELETE (next.node);
} } else if (count > 1) {
else if (count > 1) {
for (unsigned short i = 0; i != count; ++i) { for (unsigned short i = 0; i != count; ++i) {
LIBZMQ_DELETE (next.table[i]); LIBZMQ_DELETE (next.table[i]);
} }
@@ -67,7 +62,8 @@ bool zmq::mtrie_t::add (unsigned char *prefix_, size_t size_, pipe_t *pipe_)
return add_helper (prefix_, size_, pipe_); return add_helper (prefix_, size_, pipe_);
} }
bool zmq::mtrie_t::add_helper (unsigned char *prefix_, size_t size_, bool zmq::mtrie_t::add_helper (unsigned char *prefix_,
size_t size_,
pipe_t *pipe_) pipe_t *pipe_)
{ {
// We are at the node corresponding to the prefix. We are done. // We are at the node corresponding to the prefix. We are done.
@@ -83,44 +79,37 @@ bool zmq::mtrie_t::add_helper (unsigned char *prefix_, size_t size_,
unsigned char c = *prefix_; unsigned char c = *prefix_;
if (c < min || c >= min + count) { if (c < min || c >= min + count) {
// The character is out of range of currently handled // The character is out of range of currently handled
// characters. We have to extend the table. // characters. We have to extend the table.
if (!count) { if (!count) {
min = c; min = c;
count = 1; count = 1;
next.node = NULL; next.node = NULL;
} } else if (count == 1) {
else
if (count == 1) {
unsigned char oldc = min; unsigned char oldc = min;
mtrie_t *oldp = next.node; mtrie_t *oldp = next.node;
count = (min < c ? c - min : min - c) + 1; count = (min < c ? c - min : min - c) + 1;
next.table = (mtrie_t**) next.table = (mtrie_t **) malloc (sizeof (mtrie_t *) * count);
malloc (sizeof (mtrie_t*) * count);
alloc_assert (next.table); alloc_assert (next.table);
for (unsigned short i = 0; i != count; ++i) for (unsigned short i = 0; i != count; ++i)
next.table[i] = 0; next.table[i] = 0;
min = std::min (min, c); min = std::min (min, c);
next.table[oldc - min] = oldp; next.table[oldc - min] = oldp;
} } else if (min < c) {
else
if (min < c) {
// The new character is above the current character range. // The new character is above the current character range.
unsigned short old_count = count; unsigned short old_count = count;
count = c - min + 1; count = c - min + 1;
next.table = (mtrie_t**) realloc (next.table, next.table =
sizeof (mtrie_t*) * count); (mtrie_t **) realloc (next.table, sizeof (mtrie_t *) * count);
alloc_assert (next.table); alloc_assert (next.table);
for (unsigned short i = old_count; i != count; i++) for (unsigned short i = old_count; i != count; i++)
next.table[i] = NULL; next.table[i] = NULL;
} } else {
else {
// The new character is below the current character range. // The new character is below the current character range.
unsigned short old_count = count; unsigned short old_count = count;
count = (min + old_count) - c; count = (min + old_count) - c;
next.table = (mtrie_t**) realloc (next.table, next.table =
sizeof (mtrie_t*) * count); (mtrie_t **) realloc (next.table, sizeof (mtrie_t *) * count);
alloc_assert (next.table); alloc_assert (next.table);
memmove (next.table + min - c, next.table, memmove (next.table + min - c, next.table,
old_count * sizeof (mtrie_t *)); old_count * sizeof (mtrie_t *));
@@ -138,8 +127,7 @@ bool zmq::mtrie_t::add_helper (unsigned char *prefix_, size_t size_,
++live_nodes; ++live_nodes;
} }
return next.node->add_helper (prefix_ + 1, size_ - 1, pipe_); return next.node->add_helper (prefix_ + 1, size_ - 1, pipe_);
} } else {
else {
if (!next.table[c - min]) { if (!next.table[c - min]) {
next.table[c - min] = new (std::nothrow) mtrie_t; next.table[c - min] = new (std::nothrow) mtrie_t;
alloc_assert (next.table[c - min]); alloc_assert (next.table[c - min]);
@@ -151,18 +139,26 @@ bool zmq::mtrie_t::add_helper (unsigned char *prefix_, size_t size_,
void zmq::mtrie_t::rm (pipe_t *pipe_, void zmq::mtrie_t::rm (pipe_t *pipe_,
void (*func_) (unsigned char *data_, size_t size_, void *arg_), void (*func_) (unsigned char *data_,
void *arg_, bool call_on_uniq_) size_t size_,
void *arg_),
void *arg_,
bool call_on_uniq_)
{ {
unsigned char *buff = NULL; unsigned char *buff = NULL;
rm_helper (pipe_, &buff, 0, 0, func_, arg_, call_on_uniq_); rm_helper (pipe_, &buff, 0, 0, func_, arg_, call_on_uniq_);
free (buff); free (buff);
} }
void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_, void zmq::mtrie_t::rm_helper (pipe_t *pipe_,
size_t buffsize_, size_t maxbuffsize_, unsigned char **buff_,
void (*func_) (unsigned char *data_, size_t size_, void *arg_), size_t buffsize_,
void *arg_, bool call_on_uniq_) 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. // Remove the subscription from this node.
if (pipes && pipes->erase (pipe_)) { if (pipes && pipes->erase (pipe_)) {
@@ -190,8 +186,8 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_,
if (count == 1) { if (count == 1) {
(*buff_)[buffsize_] = min; (*buff_)[buffsize_] = min;
buffsize_++; buffsize_++;
next.node->rm_helper (pipe_, buff_, buffsize_, maxbuffsize_, next.node->rm_helper (pipe_, buff_, buffsize_, maxbuffsize_, func_,
func_, arg_, call_on_uniq_); arg_, call_on_uniq_);
// Prune the node if it was made redundant by the removal // Prune the node if it was made redundant by the removal
if (next.node->is_redundant ()) { if (next.node->is_redundant ()) {
@@ -212,8 +208,8 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_,
for (unsigned short c = 0; c != count; c++) { for (unsigned short c = 0; c != count; c++) {
(*buff_)[buffsize_] = min + c; (*buff_)[buffsize_] = min + c;
if (next.table[c]) { if (next.table[c]) {
next.table [c]->rm_helper (pipe_, buff_, buffsize_ + 1, next.table[c]->rm_helper (pipe_, buff_, buffsize_ + 1, maxbuffsize_,
maxbuffsize_, func_, arg_, call_on_uniq_); func_, arg_, call_on_uniq_);
// Prune redundant nodes from the mtrie // Prune redundant nodes from the mtrie
if (next.table[c]->is_redundant ()) { if (next.table[c]->is_redundant ()) {
@@ -221,8 +217,7 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_,
zmq_assert (live_nodes > 0); zmq_assert (live_nodes > 0);
--live_nodes; --live_nodes;
} } else {
else {
// The node is not redundant, so it's a candidate for being // The node is not redundant, so it's a candidate for being
// the new min/max node. // the new min/max node.
// //
@@ -247,8 +242,7 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_,
count = 0; count = 0;
} }
// Compact the node table if possible // Compact the node table if possible
else else if (live_nodes == 1) {
if (live_nodes == 1) {
// If there's only one live node in the table we can // If there's only one live node in the table we can
// switch to using the more compact single-node // switch to using the more compact single-node
// representation // representation
@@ -260,9 +254,7 @@ void zmq::mtrie_t::rm_helper (pipe_t *pipe_, unsigned char **buff_,
next.node = node; next.node = node;
count = 1; count = 1;
min = new_min; 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); zmq_assert (new_max - new_min + 1 > 1);
mtrie_t **old_table = next.table; mtrie_t **old_table = next.table;
@@ -288,7 +280,8 @@ bool zmq::mtrie_t::rm (unsigned char *prefix_, size_t size_, pipe_t *pipe_)
return rm_helper (prefix_, size_, pipe_); return rm_helper (prefix_, size_, pipe_);
} }
bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_, bool zmq::mtrie_t::rm_helper (unsigned char *prefix_,
size_t size_,
pipe_t *pipe_) pipe_t *pipe_)
{ {
if (!size_) { if (!size_) {
@@ -306,8 +299,7 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_,
if (!count || c < min || c >= min + count) if (!count || c < min || c >= min + count)
return false; return false;
mtrie_t *next_node = mtrie_t *next_node = count == 1 ? next.node : next.table[c - min];
count == 1 ? next.node : next.table [c - min];
if (!next_node) if (!next_node)
return false; return false;
@@ -323,8 +315,7 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_,
count = 0; count = 0;
--live_nodes; --live_nodes;
zmq_assert (live_nodes == 0); zmq_assert (live_nodes == 0);
} } else {
else {
next.table[c - min] = 0; next.table[c - min] = 0;
zmq_assert (live_nodes > 1); zmq_assert (live_nodes > 1);
--live_nodes; --live_nodes;
@@ -345,9 +336,7 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_,
mtrie_t *oldp = next.table[i]; mtrie_t *oldp = next.table[i];
free (next.table); free (next.table);
next.node = oldp; next.node = oldp;
} } else if (c == min) {
else
if (c == min) {
// We can compact the table "from the left" // We can compact the table "from the left"
unsigned short i; unsigned short i;
for (i = 1; i < count; ++i) for (i = 1; i < count; ++i)
@@ -362,9 +351,7 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_,
alloc_assert (next.table); 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); free (old_table);
} } else if (c == min + count - 1) {
else
if (c == min + count - 1) {
// We can compact the table "from the right" // We can compact the table "from the right"
unsigned short i; unsigned short i;
for (i = 1; i < count; ++i) for (i = 1; i < count; ++i)
@@ -385,12 +372,13 @@ bool zmq::mtrie_t::rm_helper (unsigned char *prefix_, size_t size_,
return ret; return ret;
} }
void zmq::mtrie_t::match (unsigned char *data_, size_t size_, void zmq::mtrie_t::match (unsigned char *data_,
void (*func_) (pipe_t *pipe_, void *arg_), void *arg_) size_t size_,
void (*func_) (pipe_t *pipe_, void *arg_),
void *arg_)
{ {
mtrie_t *current = this; mtrie_t *current = this;
while (true) { while (true) {
// Signal the pipes attached to this node. // Signal the pipes attached to this node.
if (current->pipes) { if (current->pipes) {
for (pipes_t::iterator it = current->pipes->begin (); for (pipes_t::iterator it = current->pipes->begin ();
@@ -417,8 +405,8 @@ void zmq::mtrie_t::match (unsigned char *data_, size_t size_,
} }
// If there are multiple subnodes. // If there are multiple subnodes.
if (data_ [0] < current->min || data_ [0] >= if (data_[0] < current->min
current->min + current->count) || data_[0] >= current->min + current->count)
break; break;
if (!current->next.table[data_[0] - current->min]) if (!current->next.table[data_[0] - current->min])
break; break;

View File

@@ -37,7 +37,6 @@
namespace zmq 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.
@@ -45,7 +44,6 @@ namespace zmq
class mtrie_t class mtrie_t
{ {
public: public:
mtrie_t (); mtrie_t ();
~mtrie_t (); ~mtrie_t ();
@@ -59,26 +57,30 @@ namespace zmq
// every removal. // every removal.
void rm (zmq::pipe_t *pipe_, void rm (zmq::pipe_t *pipe_,
void (*func_) (unsigned char *data_, size_t size_, void *arg_), void (*func_) (unsigned char *data_, size_t size_, void *arg_),
void *arg_, bool call_on_uniq_); void *arg_,
bool call_on_uniq_);
// Remove specific subscription from the trie. Return true is it was // Remove specific subscription from the trie. Return true is it was
// actually removed rather than de-duplicated. // actually removed rather than de-duplicated.
bool rm (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_); bool rm (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_);
// Signal all the matching pipes. // Signal all the matching pipes.
void match (unsigned char *data_, size_t size_, void match (unsigned char *data_,
void (*func_) (zmq::pipe_t *pipe_, void *arg_), void *arg_); size_t size_,
void (*func_) (zmq::pipe_t *pipe_, void *arg_),
void *arg_);
private: private:
bool add_helper (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_);
bool add_helper (unsigned char *prefix_, size_t size_, void
zmq::pipe_t *pipe_); rm_helper (zmq::pipe_t *pipe_,
void rm_helper (zmq::pipe_t *pipe_, unsigned char **buff_, unsigned char **buff_,
size_t buffsize_, size_t maxbuffsize_, size_t buffsize_,
size_t maxbuffsize_,
void (*func_) (unsigned char *data_, size_t size_, void *arg_), void (*func_) (unsigned char *data_, size_t size_, void *arg_),
void *arg_, bool call_on_uniq_); void *arg_,
bool rm_helper (unsigned char *prefix_, size_t size_, bool call_on_uniq_);
zmq::pipe_t *pipe_); bool rm_helper (unsigned char *prefix_, size_t size_, zmq::pipe_t *pipe_);
bool is_redundant () const; bool is_redundant () const;
typedef std::set<zmq::pipe_t *> pipes_t; typedef std::set<zmq::pipe_t *> pipes_t;
@@ -87,7 +89,8 @@ namespace zmq
unsigned char min; unsigned char min;
unsigned short count; unsigned short count;
unsigned short live_nodes; unsigned short live_nodes;
union { union
{
class mtrie_t *node; class mtrie_t *node;
class mtrie_t **table; class mtrie_t **table;
} next; } next;
@@ -95,8 +98,6 @@ namespace zmq
mtrie_t (const mtrie_t &); mtrie_t (const mtrie_t &);
const mtrie_t &operator= (const mtrie_t &); const mtrie_t &operator= (const mtrie_t &);
}; };
} }
#endif #endif

View File

@@ -40,49 +40,31 @@
namespace zmq namespace zmq
{ {
class mutex_t class mutex_t
{ {
public: public:
inline mutex_t () inline mutex_t () { InitializeCriticalSection (&cs); }
{
InitializeCriticalSection (&cs);
}
inline ~mutex_t () inline ~mutex_t () { DeleteCriticalSection (&cs); }
{
DeleteCriticalSection (&cs);
}
inline void lock () inline void lock () { EnterCriticalSection (&cs); }
{
EnterCriticalSection (&cs);
}
inline bool try_lock () inline bool try_lock ()
{ {
return (TryEnterCriticalSection (&cs)) ? true : false; return (TryEnterCriticalSection (&cs)) ? true : false;
} }
inline void unlock () inline void unlock () { LeaveCriticalSection (&cs); }
{
LeaveCriticalSection (&cs);
}
inline CRITICAL_SECTION* get_cs() inline CRITICAL_SECTION *get_cs () { return &cs; }
{
return &cs;
}
private: private:
CRITICAL_SECTION cs; CRITICAL_SECTION cs;
// Disable copy construction and assignment. // Disable copy construction and assignment.
mutex_t (const mutex_t &); mutex_t (const mutex_t &);
void operator= (const mutex_t &); void operator= (const mutex_t &);
}; };
} }
#else #else
@@ -91,7 +73,6 @@ namespace zmq
namespace zmq namespace zmq
{ {
class mutex_t class mutex_t
{ {
public: public:
@@ -138,13 +119,9 @@ namespace zmq
posix_assert (rc); posix_assert (rc);
} }
inline pthread_mutex_t* get_mutex() inline pthread_mutex_t *get_mutex () { return &mutex; }
{
return &mutex;
}
private: private:
pthread_mutex_t mutex; pthread_mutex_t mutex;
pthread_mutexattr_t attr; pthread_mutexattr_t attr;
@@ -152,7 +129,6 @@ namespace zmq
mutex_t (const mutex_t &); mutex_t (const mutex_t &);
const mutex_t &operator= (const mutex_t &); const mutex_t &operator= (const mutex_t &);
}; };
} }
#endif #endif
@@ -162,19 +138,11 @@ namespace zmq
{ {
struct scoped_lock_t struct scoped_lock_t
{ {
scoped_lock_t (mutex_t& mutex_) scoped_lock_t (mutex_t &mutex_) : mutex (mutex_) { mutex.lock (); }
: mutex (mutex_)
{
mutex.lock ();
}
~scoped_lock_t () ~scoped_lock_t () { mutex.unlock (); }
{
mutex.unlock ();
}
private: private:
mutex_t &mutex; mutex_t &mutex;
// Disable copy construction and assignment. // Disable copy construction and assignment.
@@ -185,8 +153,7 @@ namespace zmq
struct scoped_optional_lock_t struct scoped_optional_lock_t
{ {
scoped_optional_lock_t (mutex_t* mutex_) scoped_optional_lock_t (mutex_t *mutex_) : mutex (mutex_)
: mutex (mutex_)
{ {
if (mutex != NULL) if (mutex != NULL)
mutex->lock (); mutex->lock ();
@@ -199,15 +166,12 @@ namespace zmq
} }
private: private:
mutex_t *mutex; mutex_t *mutex;
// Disable copy construction and assignment. // Disable copy construction and assignment.
scoped_optional_lock_t (const scoped_lock_t &); scoped_optional_lock_t (const scoped_lock_t &);
const scoped_optional_lock_t &operator= (const scoped_lock_t &); const scoped_optional_lock_t &operator= (const scoped_lock_t &);
}; };
} }
#endif #endif

View File

@@ -10,14 +10,22 @@
#include "v2_protocol.hpp" #include "v2_protocol.hpp"
zmq::norm_engine_t::norm_engine_t (io_thread_t *parent_, zmq::norm_engine_t::norm_engine_t (io_thread_t *parent_,
const options_t& options_) const options_t &options_) :
: io_object_t(parent_), zmq_session(NULL), options(options_), io_object_t (parent_),
norm_instance(NORM_INSTANCE_INVALID), norm_session(NORM_SESSION_INVALID), zmq_session (NULL),
is_sender(false), is_receiver(false), options (options_),
zmq_encoder(0), norm_tx_stream(NORM_OBJECT_INVALID), norm_instance (NORM_INSTANCE_INVALID),
tx_first_msg(true), tx_more_bit(false), norm_session (NORM_SESSION_INVALID),
zmq_output_ready(false), norm_tx_ready(false), is_sender (false),
tx_index(0), tx_len(0), 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_input_ready (false)
{ {
int rc = tx_msg.init (); int rc = tx_msg.init ();
@@ -38,59 +46,53 @@ int zmq::norm_engine_t::init(const char* network_, bool send, bool recv)
// (default NORM_NODE_ANY causes NORM to use host IP addr for NormNodeId) // (default NORM_NODE_ANY causes NORM to use host IP addr for NormNodeId)
NormNodeId localId = NORM_NODE_ANY; NormNodeId localId = NORM_NODE_ANY;
const char *ifacePtr = strchr (network_, ','); const char *ifacePtr = strchr (network_, ',');
if (NULL != ifacePtr) if (NULL != ifacePtr) {
{
size_t idLen = ifacePtr - network_; size_t idLen = ifacePtr - network_;
if (idLen > 31) idLen = 31; if (idLen > 31)
idLen = 31;
char idText[32]; char idText[32];
strncpy (idText, network_, idLen); strncpy (idText, network_, idLen);
idText[idLen] = '\0'; idText[idLen] = '\0';
localId = (NormNodeId) atoi (idText); localId = (NormNodeId) atoi (idText);
ifacePtr++; ifacePtr++;
} } else {
else
{
ifacePtr = network_; ifacePtr = network_;
} }
// Second, look for optional multicast ifaceName // Second, look for optional multicast ifaceName
char ifaceName[256]; char ifaceName[256];
const char *addrPtr = strchr (ifacePtr, ';'); const char *addrPtr = strchr (ifacePtr, ';');
if (NULL != addrPtr) if (NULL != addrPtr) {
{
size_t ifaceLen = addrPtr - ifacePtr; size_t ifaceLen = addrPtr - ifacePtr;
if (ifaceLen > 255) ifaceLen = 255; // return error instead? if (ifaceLen > 255)
ifaceLen = 255; // return error instead?
strncpy (ifaceName, ifacePtr, ifaceLen); strncpy (ifaceName, ifacePtr, ifaceLen);
ifaceName[ifaceLen] = '\0'; ifaceName[ifaceLen] = '\0';
ifacePtr = ifaceName; ifacePtr = ifaceName;
addrPtr++; addrPtr++;
} } else {
else
{
addrPtr = ifacePtr; addrPtr = ifacePtr;
ifacePtr = NULL; ifacePtr = NULL;
} }
// Finally, parse IP address and port number // Finally, parse IP address and port number
const char *portPtr = strrchr (addrPtr, ':'); const char *portPtr = strrchr (addrPtr, ':');
if (NULL == portPtr) if (NULL == portPtr) {
{
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
char addr[256]; char addr[256];
size_t addrLen = portPtr - addrPtr; size_t addrLen = portPtr - addrPtr;
if (addrLen > 255) addrLen = 255; if (addrLen > 255)
addrLen = 255;
strncpy (addr, addrPtr, addrLen); strncpy (addr, addrPtr, addrLen);
addr[addrLen] = '\0'; addr[addrLen] = '\0';
portPtr++; portPtr++;
unsigned short portNumber = atoi (portPtr); unsigned short portNumber = atoi (portPtr);
if (NORM_INSTANCE_INVALID == norm_instance) if (NORM_INSTANCE_INVALID == norm_instance) {
{ if (NORM_INSTANCE_INVALID == (norm_instance = NormCreateInstance ())) {
if (NORM_INSTANCE_INVALID == (norm_instance = NormCreateInstance()))
{
// errno set by whatever caused NormCreateInstance() to fail // errno set by whatever caused NormCreateInstance() to fail
return -1; return -1;
} }
@@ -104,8 +106,7 @@ int zmq::norm_engine_t::init(const char* network_, bool send, bool recv)
// conflict detection/resolution protocol // conflict detection/resolution protocol
norm_session = NormCreateSession (norm_instance, addr, portNumber, localId); norm_session = NormCreateSession (norm_instance, addr, portNumber, localId);
if (NORM_SESSION_INVALID == norm_session) if (NORM_SESSION_INVALID == norm_session) {
{
int savedErrno = errno; int savedErrno = errno;
NormDestroyInstance (norm_instance); NormDestroyInstance (norm_instance);
norm_instance = NORM_INSTANCE_INVALID; norm_instance = NORM_INSTANCE_INVALID;
@@ -113,33 +114,32 @@ int zmq::norm_engine_t::init(const char* network_, bool send, bool recv)
return -1; return -1;
} }
// There's many other useful NORM options that could be applied here // There's many other useful NORM options that could be applied here
if (NormIsUnicastAddress(addr)) if (NormIsUnicastAddress (addr)) {
{
NormSetDefaultUnicastNack (norm_session, true); NormSetDefaultUnicastNack (norm_session, true);
} } else {
else
{
// These only apply for multicast sessions // These only apply for multicast sessions
//NormSetTTL(norm_session, options.multicast_hops); // ZMQ default is 1 //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 NormSetTTL (
NormSetRxPortReuse(norm_session, true); // port reuse doesn't work for non-connected unicast norm_session,
NormSetLoopback(norm_session, true); // needed when multicast users on same machine 255); // since the ZMQ_MULTICAST_HOPS socket option isn't well-supported
if (NULL != ifacePtr) 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 // Note a bad interface may not be caught until sender or receiver start
// (Since sender/receiver is not yet started, this always succeeds here) // (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" // The alternative NORM_SYNC_CURRENT here would provide "instant"
// receiver sync to the sender's _current_ message transmission. // receiver sync to the sender's _current_ message transmission.
// NORM_SYNC_STREAM tries to get everything the sender has cached/buffered // NORM_SYNC_STREAM tries to get everything the sender has cached/buffered
NormSetDefaultSyncPolicy (norm_session, NORM_SYNC_STREAM); NormSetDefaultSyncPolicy (norm_session, NORM_SYNC_STREAM);
if (!NormStartReceiver(norm_session, 2*1024*1024)) if (!NormStartReceiver (norm_session, 2 * 1024 * 1024)) {
{
// errno set by whatever failed // errno set by whatever failed
int savedErrno = errno; int savedErrno = errno;
NormDestroyInstance (norm_instance); // session gets closed, too NormDestroyInstance (norm_instance); // session gets closed, too
@@ -151,13 +151,12 @@ int zmq::norm_engine_t::init(const char* network_, bool send, bool recv)
is_receiver = true; is_receiver = true;
} }
if (send) if (send) {
{
// Pick a random sender instance id (aka norm sender session id) // 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 // 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 // errno set by whatever failed
int savedErrno = errno; int savedErrno = errno;
NormDestroyInstance (norm_instance); // session gets closed, too NormDestroyInstance (norm_instance); // session gets closed, too
@@ -169,8 +168,9 @@ int zmq::norm_engine_t::init(const char* network_, bool send, bool recv)
NormSetCongestionControl (norm_session, true); NormSetCongestionControl (norm_session, true);
norm_tx_ready = true; norm_tx_ready = true;
is_sender = 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 // errno set by whatever failed
int savedErrno = errno; int savedErrno = errno;
NormDestroyInstance (norm_instance); // session gets closed, too NormDestroyInstance (norm_instance); // session gets closed, too
@@ -191,8 +191,7 @@ int zmq::norm_engine_t::init(const char* network_, bool send, bool recv)
void zmq::norm_engine_t::shutdown () void zmq::norm_engine_t::shutdown ()
{ {
// TBD - implement a more graceful shutdown option // TBD - implement a more graceful shutdown option
if (is_receiver) if (is_receiver) {
{
NormStopReceiver (norm_session); NormStopReceiver (norm_session);
// delete any active NormRxStreamState // delete any active NormRxStreamState
@@ -202,37 +201,38 @@ void zmq::norm_engine_t::shutdown()
is_receiver = false; is_receiver = false;
} }
if (is_sender) if (is_sender) {
{
NormStopSender (norm_session); NormStopSender (norm_session);
is_sender = false; is_sender = false;
} }
if (NORM_SESSION_INVALID != norm_session) if (NORM_SESSION_INVALID != norm_session) {
{
NormDestroySession (norm_session); NormDestroySession (norm_session);
norm_session = NORM_SESSION_INVALID; norm_session = NORM_SESSION_INVALID;
} }
if (NORM_INSTANCE_INVALID != norm_instance) if (NORM_INSTANCE_INVALID != norm_instance) {
{
NormStopInstance (norm_instance); NormStopInstance (norm_instance);
NormDestroyInstance (norm_instance); NormDestroyInstance (norm_instance);
norm_instance = NORM_INSTANCE_INVALID; 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??? // TBD - we may assign the NORM engine to an io_thread in the future???
zmq_session = session_; zmq_session = session_;
if (is_sender) zmq_output_ready = true; if (is_sender)
if (is_receiver) zmq_input_ready = true; zmq_output_ready = true;
if (is_receiver)
zmq_input_ready = true;
fd_t normDescriptor = NormGetDescriptor (norm_instance); fd_t normDescriptor = NormGetDescriptor (norm_instance);
norm_descriptor_handle = add_fd (normDescriptor); norm_descriptor_handle = add_fd (normDescriptor);
// Set POLLIN for notification of pending NormEvents // 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()
@@ -254,31 +254,26 @@ void zmq::norm_engine_t::restart_output()
{ {
// There's new message data available from the session // There's new message data available from the session
zmq_output_ready = true; 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 // Here we write as much as is available or we can
while (zmq_output_ready && norm_tx_ready) while (zmq_output_ready && norm_tx_ready) {
{ if (0 == tx_len) {
if (0 == tx_len)
{
// Our tx_buffer needs data to send // Our tx_buffer needs data to send
// Get more data from encoder // Get more data from encoder
size_t space = BUFFER_SIZE; size_t space = BUFFER_SIZE;
unsigned char *bufPtr = (unsigned char *) tx_buffer; unsigned char *bufPtr = (unsigned char *) tx_buffer;
tx_len = zmq_encoder.encode (&bufPtr, space); tx_len = zmq_encoder.encode (&bufPtr, space);
if (0 == tx_len) if (0 == tx_len) {
{ if (tx_first_msg) {
if (tx_first_msg)
{
// We don't need to mark eom/flush until a message is sent // We don't need to mark eom/flush until a message is sent
tx_first_msg = false; tx_first_msg = false;
} } else {
else
{
// A prior message was completely written to stream, so // A prior message was completely written to stream, so
// mark end-of-message and possibly flush (to force packet transmission, // mark end-of-message and possibly flush (to force packet transmission,
// even if it's not a full segment so message gets delivered quickly) // even if it's not a full segment so message gets delivered quickly)
@@ -289,8 +284,7 @@ void zmq::norm_engine_t::send_data()
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 // 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 // We need to wait for "restart_output()" to be called by ZMQ
zmq_output_ready = false; zmq_output_ready = false;
break; break;
@@ -304,7 +298,8 @@ void zmq::norm_engine_t::send_data()
// I.e.,If more_flag _was_ false previously, this is the first // I.e.,If more_flag _was_ false previously, this is the first
// frame of a ZMQ message. // frame of a ZMQ message.
if (tx_more_bit) 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 else
tx_buffer[0] = 0x00; // this is first frame of message tx_buffer[0] = 0x00; // this is first frame of message
tx_more_bit = (0 != (tx_msg.flags () & msg_t::more)); tx_more_bit = (0 != (tx_msg.flags () & msg_t::more));
@@ -316,12 +311,11 @@ void zmq::norm_engine_t::send_data()
} }
} }
// Do we have data in our tx_buffer pending // 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 // 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); tx_index += NormStreamWrite (norm_tx_stream, tx_buffer + tx_index,
if (tx_index < tx_len) tx_len - tx_index);
{ if (tx_index < tx_len) {
// NORM stream buffer full, wait for NORM_TX_QUEUE_VACANCY // NORM stream buffer full, wait for NORM_TX_QUEUE_VACANCY
norm_tx_ready = false; norm_tx_ready = false;
break; break;
@@ -335,19 +329,16 @@ void zmq::norm_engine_t::in_event()
{ {
// This means a NormEvent is pending, so call NormGetNextEvent() and handle // This means a NormEvent is pending, so call NormGetNextEvent() and handle
NormEvent event; NormEvent event;
if (!NormGetNextEvent(norm_instance, &event)) if (!NormGetNextEvent (norm_instance, &event)) {
{
// NORM has died before we unplugged?! // NORM has died before we unplugged?!
zmq_assert (false); zmq_assert (false);
return; return;
} }
switch(event.type) switch (event.type) {
{
case NORM_TX_QUEUE_VACANCY: case NORM_TX_QUEUE_VACANCY:
case NORM_TX_QUEUE_EMPTY: case NORM_TX_QUEUE_EMPTY:
if (!norm_tx_ready) if (!norm_tx_ready) {
{
norm_tx_ready = true; norm_tx_ready = true;
send_data (); send_data ();
} }
@@ -359,16 +350,16 @@ void zmq::norm_engine_t::in_event()
recv_data (event.object); recv_data (event.object);
break; break;
case NORM_RX_OBJECT_ABORTED: case NORM_RX_OBJECT_ABORTED: {
{ NormRxStreamState *rxState =
NormRxStreamState* rxState = (NormRxStreamState*)NormObjectGetUserData(event.object); (NormRxStreamState *) NormObjectGetUserData (event.object);
if (NULL != rxState) if (NULL != rxState) {
{
// Remove the state from the list it's in // Remove the state from the list it's in
// This is now unnecessary since deletion takes care of list removal // This is now unnecessary since deletion takes care of list removal
// but in the interest of being clear ... // but in the interest of being clear ...
NormRxStreamState::List *list = rxState->AccessList (); NormRxStreamState::List *list = rxState->AccessList ();
if (NULL != list) list->Remove(*rxState); if (NULL != list)
list->Remove (*rxState);
} }
delete rxState; delete rxState;
break; break;
@@ -403,37 +394,33 @@ void 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 // Call result of NORM_RX_OBJECT_UPDATED notification
// This is a rx_ready indication for a new or existing rx stream // This is a rx_ready indication for a new or existing rx stream
// First, determine if this is a stream we already know // 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 // Since there can be multiple senders (publishers), we keep
// state for each separate rx stream. // state for each separate rx stream.
NormRxStreamState* rxState = (NormRxStreamState*)NormObjectGetUserData(object); NormRxStreamState *rxState =
if (NULL == rxState) (NormRxStreamState *) NormObjectGetUserData (object);
{ if (NULL == rxState) {
// This is a new stream, so create rxState with zmq decoder, etc // This is a new stream, so create rxState with zmq decoder, etc
rxState = new (std::nothrow) NormRxStreamState(object, options.maxmsgsize); rxState =
new (std::nothrow) NormRxStreamState (object, options.maxmsgsize);
errno_assert (rxState); errno_assert (rxState);
if (!rxState->Init()) if (!rxState->Init ()) {
{
errno_assert (false); errno_assert (false);
delete rxState; delete rxState;
return; return;
} }
NormObjectSetUserData (object, rxState); NormObjectSetUserData (object, rxState);
} } else if (!rxState->IsRxReady ()) {
else if (!rxState->IsRxReady())
{
// Existing non-ready stream, so remove from pending // Existing non-ready stream, so remove from pending
// list to be promoted to rx_ready_list ... // 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? // TBD - prepend up front for immediate service?
rxState->SetRxReady (true); rxState->SetRxReady (true);
rx_ready_list.Append (*rxState); rx_ready_list.Append (*rxState);
@@ -441,16 +428,14 @@ void zmq::norm_engine_t::recv_data(NormObjectHandle object)
} }
// This loop repeats until we've read all data available from "rx ready" inbound streams // 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. // 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 // Iterate through our rx_ready streams, reading data into the decoder
// (This services incoming "rx ready" streams in a round-robin fashion) // (This services incoming "rx ready" streams in a round-robin fashion)
NormRxStreamState::List::Iterator iterator (rx_ready_list); NormRxStreamState::List::Iterator iterator (rx_ready_list);
NormRxStreamState *rxState; NormRxStreamState *rxState;
while (NULL != (rxState = iterator.GetNextItem())) while (NULL != (rxState = iterator.GetNextItem ())) {
{ switch (rxState->Decode ()) {
switch(rxState->Decode())
{
case 1: // msg completed case 1: // msg completed
// Complete message decoded, move this stream to msg_ready_list // Complete message decoded, move this stream to msg_ready_list
// to push the message up to the session below. Note the stream // to push the message up to the session below. Note the stream
@@ -470,34 +455,30 @@ void zmq::norm_engine_t::recv_data(NormObjectHandle object)
// Get more data from this stream // Get more data from this stream
NormObjectHandle stream = rxState->GetStreamHandle (); NormObjectHandle stream = rxState->GetStreamHandle ();
// First, make sure we're in sync ... // First, make sure we're in sync ...
while (!rxState->InSync()) while (!rxState->InSync ()) {
{
// seek NORM message start // seek NORM message start
if (!NormStreamSeekMsgStart(stream)) if (!NormStreamSeekMsgStart (stream)) {
{
// Need to wait for more data // Need to wait for more data
break; break;
} }
// read message 'flag' byte to see if this it's a 'final' frame // read message 'flag' byte to see if this it's a 'final' frame
char syncFlag; char syncFlag;
unsigned int numBytes = 1; unsigned int numBytes = 1;
if (!NormStreamRead(stream, &syncFlag, &numBytes)) if (!NormStreamRead (stream, &syncFlag, &numBytes)) {
{
// broken stream (shouldn't happen after seek msg start?) // broken stream (shouldn't happen after seek msg start?)
zmq_assert (false); zmq_assert (false);
continue; continue;
} }
if (0 == numBytes) if (0 == numBytes) {
{
// This probably shouldn't happen either since we found msg start // This probably shouldn't happen either since we found msg start
// Need to wait for more data // Need to wait for more data
break; break;
} }
if (0 == syncFlag) rxState->SetSync(true); if (0 == syncFlag)
rxState->SetSync (true);
// else keep seeking ... // else keep seeking ...
} // end while(!rxState->InSync()) } // end while(!rxState->InSync())
if (!rxState->InSync()) if (!rxState->InSync ()) {
{
// Need more data for this stream, so remove from "rx ready" // Need more data for this stream, so remove from "rx ready"
// list and iterate to next "rx ready" stream // list and iterate to next "rx ready" stream
rxState->SetRxReady (false); rxState->SetRxReady (false);
@@ -509,8 +490,7 @@ void zmq::norm_engine_t::recv_data(NormObjectHandle object)
// Now we're actually ready to read data from the NORM stream to the zmq_decoder // 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. // the underlying zmq_decoder->get_buffer() call sets how much is needed.
unsigned int numBytes = rxState->GetBytesNeeded (); unsigned int numBytes = rxState->GetBytesNeeded ();
if (!NormStreamRead(stream, rxState->AccessBuffer(), &numBytes)) if (!NormStreamRead (stream, rxState->AccessBuffer (), &numBytes)) {
{
// broken NORM stream, so re-sync // 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 // This will retry syncing, and getting data from this stream
@@ -518,8 +498,7 @@ void zmq::norm_engine_t::recv_data(NormObjectHandle object)
continue; continue;
} }
rxState->IncrementBufferCount (numBytes); rxState->IncrementBufferCount (numBytes);
if (0 == numBytes) if (0 == numBytes) {
{
// All the data available has been read // All the data available has been read
// Need to wait for NORM_RX_OBJECT_UPDATED for this stream // Need to wait for NORM_RX_OBJECT_UPDATED for this stream
rxState->SetRxReady (false); rxState->SetRxReady (false);
@@ -529,28 +508,22 @@ void zmq::norm_engine_t::recv_data(NormObjectHandle object)
} }
} // 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 // 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 // Now make a pass through the "msg_pending" list (if the zmq session
// ready for more input). This may possibly return streams back to // ready for more input). This may possibly return streams back to
// the "rx ready" stream list after their pending message is handled // the "rx ready" stream list after their pending message is handled
NormRxStreamState::List::Iterator iterator (msg_ready_list); NormRxStreamState::List::Iterator iterator (msg_ready_list);
NormRxStreamState *rxState; NormRxStreamState *rxState;
while (NULL != (rxState = iterator.GetNextItem())) while (NULL != (rxState = iterator.GetNextItem ())) {
{
msg_t *msg = rxState->AccessMsg (); msg_t *msg = rxState->AccessMsg ();
int rc = zmq_session->push_msg (msg); int rc = zmq_session->push_msg (msg);
if (-1 == rc) if (-1 == rc) {
{ if (EAGAIN == errno) {
if (EAGAIN == errno)
{
// need to wait until session calls "restart_input()" // need to wait until session calls "restart_input()"
zmq_input_ready = false; zmq_input_ready = false;
break; break;
} } else {
else
{
// session rejected message? // session rejected message?
// TBD - handle this better // TBD - handle this better
zmq_assert (false); zmq_assert (false);
@@ -558,7 +531,9 @@ void zmq::norm_engine_t::recv_data(NormObjectHandle object)
} }
// else message was accepted. // else message was accepted.
msg_ready_list.Remove (*rxState); msg_ready_list.Remove (*rxState);
if (rxState->IsRxReady()) // Move back to "rx_ready" list to read more data if (
rxState
->IsRxReady ()) // Move back to "rx_ready" list to read more data
rx_ready_list.Append (*rxState); rx_ready_list.Append (*rxState);
else // Move back to "rx_pending" list until NORM_RX_OBJECT_UPDATED else // Move back to "rx_pending" list until NORM_RX_OBJECT_UPDATED
msg_ready_list.Append (*rxState); msg_ready_list.Append (*rxState);
@@ -571,24 +546,30 @@ void zmq::norm_engine_t::recv_data(NormObjectHandle object)
} // end zmq::norm_engine_t::recv_data() } // end zmq::norm_engine_t::recv_data()
zmq::norm_engine_t::NormRxStreamState::NormRxStreamState(NormObjectHandle normStream, zmq::norm_engine_t::NormRxStreamState::NormRxStreamState (
int64_t maxMsgSize) NormObjectHandle normStream, int64_t maxMsgSize) :
: norm_stream(normStream), max_msg_size(maxMsgSize), norm_stream (normStream),
in_sync(false), rx_ready(false), zmq_decoder(NULL), skip_norm_sync(false), max_msg_size (maxMsgSize),
buffer_ptr(NULL), buffer_size(0), buffer_count(0), in_sync (false),
prev(NULL), next(NULL), list(NULL) 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; delete zmq_decoder;
zmq_decoder = NULL; zmq_decoder = NULL;
} }
if (NULL != list) if (NULL != list) {
{
list->Remove (*this); list->Remove (*this);
list = NULL; list = NULL;
} }
@@ -598,19 +579,17 @@ bool zmq::norm_engine_t::NormRxStreamState::Init()
{ {
in_sync = false; in_sync = false;
skip_norm_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 // Note "in_batch_size" comes from config.h
zmq_decoder = new (std::nothrow) v2_decoder_t (in_batch_size, max_msg_size); zmq_decoder = new (std::nothrow) v2_decoder_t (in_batch_size, max_msg_size);
alloc_assert (zmq_decoder); alloc_assert (zmq_decoder);
if (NULL != zmq_decoder) if (NULL != zmq_decoder) {
{
buffer_count = 0; buffer_count = 0;
buffer_size = 0; buffer_size = 0;
zmq_decoder->get_buffer (&buffer_ptr, &buffer_size); zmq_decoder->get_buffer (&buffer_ptr, &buffer_size);
return true; return true;
} } else {
else
{
return false; return false;
} }
} // end zmq::norm_engine_t::NormRxStreamState::Init() } // end zmq::norm_engine_t::NormRxStreamState::Init()
@@ -620,16 +599,14 @@ bool zmq::norm_engine_t::NormRxStreamState::Init()
int zmq::norm_engine_t::NormRxStreamState::Decode () int zmq::norm_engine_t::NormRxStreamState::Decode ()
{ {
// If we have pending bytes to decode, process those first // 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 // There's pending data for the decoder to decode
size_t processed = 0; size_t processed = 0;
// This a bit of a kludgy approach used to weed // This a bit of a kludgy approach used to weed
// out the NORM ZMQ message transport "syncFlag" byte // out the NORM ZMQ message transport "syncFlag" byte
// from the ZMQ message stream being decoded (but it works!) // from the ZMQ message stream being decoded (but it works!)
if (skip_norm_sync) if (skip_norm_sync) {
{
buffer_ptr++; buffer_ptr++;
buffer_count--; buffer_count--;
skip_norm_sync = false; skip_norm_sync = false;
@@ -638,12 +615,10 @@ int zmq::norm_engine_t::NormRxStreamState::Decode()
int rc = zmq_decoder->decode (buffer_ptr, buffer_count, processed); int rc = zmq_decoder->decode (buffer_ptr, buffer_count, processed);
buffer_ptr += processed; buffer_ptr += processed;
buffer_count -= processed; buffer_count -= processed;
switch (rc) switch (rc) {
{
case 1: case 1:
// msg completed // msg completed
if (0 == buffer_count) if (0 == buffer_count) {
{
buffer_size = 0; buffer_size = 0;
zmq_decoder->get_buffer (&buffer_ptr, &buffer_size); zmq_decoder->get_buffer (&buffer_ptr, &buffer_size);
} }
@@ -669,8 +644,7 @@ int zmq::norm_engine_t::NormRxStreamState::Decode()
} // end zmq::norm_engine_t::NormRxStreamState::Decode() } // end zmq::norm_engine_t::NormRxStreamState::Decode()
zmq::norm_engine_t::NormRxStreamState::List::List() zmq::norm_engine_t::NormRxStreamState::List::List () : head (NULL), tail (NULL)
: head(NULL), tail(NULL)
{ {
} }
@@ -682,15 +656,15 @@ zmq::norm_engine_t::NormRxStreamState::List::~List()
void zmq::norm_engine_t::NormRxStreamState::List::Destroy () void zmq::norm_engine_t::NormRxStreamState::List::Destroy ()
{ {
NormRxStreamState *item = head; NormRxStreamState *item = head;
while (NULL != item) while (NULL != item) {
{
Remove (*item); Remove (*item);
delete item; delete item;
item = head; 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; item.prev = tail;
if (NULL != tail) if (NULL != tail)
@@ -702,7 +676,8 @@ void zmq::norm_engine_t::NormRxStreamState::List::Append(NormRxStreamState& item
item.list = this; 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) if (NULL != item.prev)
item.prev->next = item.next; item.prev->next = item.next;
@@ -716,15 +691,18 @@ void zmq::norm_engine_t::NormRxStreamState::List::Remove(NormRxStreamState& item
item.list = 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) zmq::norm_engine_t::NormRxStreamState::List::Iterator::Iterator (
: next_item(list.head) 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; NormRxStreamState *nextItem = next_item;
if (NULL != nextItem) next_item = nextItem->next; if (NULL != nextItem)
next_item = nextItem->next;
return nextItem; return nextItem;
} // end zmq::norm_engine_t::NormRxStreamState::List::Iterator::GetNextItem() } // end zmq::norm_engine_t::NormRxStreamState::List::Iterator::GetNextItem()

View File

@@ -59,41 +59,34 @@ namespace zmq
void recv_data (NormObjectHandle stream); void recv_data (NormObjectHandle stream);
enum {BUFFER_SIZE = 2048}; enum
{
BUFFER_SIZE = 2048
};
// Used to keep track of streams from multiple senders // Used to keep track of streams from multiple senders
class NormRxStreamState class NormRxStreamState
{ {
public: public:
NormRxStreamState(NormObjectHandle normStream, NormRxStreamState (NormObjectHandle normStream, int64_t maxMsgSize);
int64_t maxMsgSize);
~NormRxStreamState (); ~NormRxStreamState ();
NormObjectHandle GetStreamHandle() const NormObjectHandle GetStreamHandle () const { return norm_stream; }
{return norm_stream;}
bool Init (); bool Init ();
void SetRxReady(bool state) void SetRxReady (bool state) { rx_ready = state; }
{rx_ready = state;} bool IsRxReady () const { return rx_ready; }
bool IsRxReady() const
{return rx_ready;}
void SetSync(bool state) void SetSync (bool state) { in_sync = state; }
{in_sync = state;} bool InSync () const { return in_sync; }
bool InSync() const
{return in_sync;}
// These are used to feed data to decoder // These are used to feed data to decoder
// and its underlying "msg" buffer // and its underlying "msg" buffer
char* AccessBuffer() char *AccessBuffer () { return (char *) (buffer_ptr + buffer_count); }
{return (char*)(buffer_ptr + buffer_count);} size_t GetBytesNeeded () const { return (buffer_size - buffer_count); }
size_t GetBytesNeeded() const void IncrementBufferCount (size_t count) { buffer_count += count; }
{return (buffer_size - buffer_count);} msg_t *AccessMsg () { return zmq_decoder->msg (); }
void IncrementBufferCount(size_t count)
{buffer_count += count;}
msg_t* AccessMsg()
{return zmq_decoder->msg();}
// This invokes the decoder "decode" method // This invokes the decoder "decode" method
// returning 0 if more data is needed, // returning 0 if more data is needed,
// 1 if the message is complete, If an error // 1 if the message is complete, If an error
@@ -110,8 +103,7 @@ namespace zmq
void Append (NormRxStreamState &item); void Append (NormRxStreamState &item);
void Remove (NormRxStreamState &item); void Remove (NormRxStreamState &item);
bool IsEmpty() const bool IsEmpty () const { return (NULL == head); }
{return (NULL == head);}
void Destroy (); void Destroy ();
@@ -120,6 +112,7 @@ namespace zmq
public: public:
Iterator (const List &list); Iterator (const List &list);
NormRxStreamState *GetNextItem (); NormRxStreamState *GetNextItem ();
private: private:
NormRxStreamState *next_item; NormRxStreamState *next_item;
}; };
@@ -133,8 +126,7 @@ namespace zmq
friend class List; friend class List;
List* AccessList() List *AccessList () { return list; }
{return list;}
private: private:
@@ -177,9 +169,12 @@ namespace zmq
// Receiver state // Receiver state
// Lists of norm rx streams from remote senders // Lists of norm rx streams from remote senders
bool zmq_input_ready; // zmq ready to receive msg(s) bool zmq_input_ready; // zmq ready to receive msg(s)
NormRxStreamState::List rx_pending_list; // rx streams waiting for data reception NormRxStreamState::List
NormRxStreamState::List rx_ready_list; // rx streams ready for NormStreamRead() rx_pending_list; // rx streams waiting for data reception
NormRxStreamState::List msg_ready_list; // rx streams w/ msg ready for push to zmq 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 }; // end class norm_engine_t

View File

@@ -70,11 +70,9 @@ int zmq::null_mechanism_t::next_handshake_command (msg_t *msg_)
return -1; return -1;
} }
int rc = session->zap_connect (); int rc = session->zap_connect ();
if (rc == -1) if (rc == -1) {
{
session->get_socket ()->event_handshake_failed_no_detail ( session->get_socket ()->event_handshake_failed_no_detail (
session->get_endpoint(), session->get_endpoint (), EFAULT);
EFAULT);
return -1; return -1;
} }
send_zap_request (); send_zap_request ();
@@ -120,8 +118,7 @@ int zmq::null_mechanism_t::process_handshake_command (msg_t *msg_)
{ {
if (ready_command_received || error_command_received) { if (ready_command_received || error_command_received) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
errno = EPROTO; errno = EPROTO;
return -1; return -1;
} }
@@ -133,13 +130,11 @@ int zmq::null_mechanism_t::process_handshake_command (msg_t *msg_)
int rc = 0; int rc = 0;
if (data_size >= 6 && !memcmp (cmd_data, "\5READY", 6)) if (data_size >= 6 && !memcmp (cmd_data, "\5READY", 6))
rc = process_ready_command (cmd_data, data_size); rc = process_ready_command (cmd_data, data_size);
else else if (data_size >= 6 && !memcmp (cmd_data, "\5ERROR", 6))
if (data_size >= 6 && !memcmp (cmd_data, "\5ERROR", 6))
rc = process_error_command (cmd_data, data_size); rc = process_error_command (cmd_data, data_size);
else { else {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
session->get_endpoint (), session->get_endpoint (), ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND);
errno = EPROTO; errno = EPROTO;
rc = -1; rc = -1;
} }
@@ -153,15 +148,15 @@ int zmq::null_mechanism_t::process_handshake_command (msg_t *msg_)
return rc; return rc;
} }
int zmq::null_mechanism_t::process_ready_command ( int zmq::null_mechanism_t::process_ready_command (const unsigned char *cmd_data,
const unsigned char *cmd_data, size_t data_size) size_t data_size)
{ {
ready_command_received = true; ready_command_received = true;
return parse_metadata (cmd_data + 6, data_size - 6); return parse_metadata (cmd_data + 6, data_size - 6);
} }
int zmq::null_mechanism_t::process_error_command ( int zmq::null_mechanism_t::process_error_command (const unsigned char *cmd_data,
const unsigned char *cmd_data, size_t data_size) size_t data_size)
{ {
if (data_size < 7) { if (data_size < 7) {
session->get_socket ()->event_handshake_failed_protocol ( session->get_socket ()->event_handshake_failed_protocol (
@@ -200,15 +195,13 @@ int zmq::null_mechanism_t::zap_msg_available ()
zmq::mechanism_t::status_t zmq::null_mechanism_t::status () const zmq::mechanism_t::status_t zmq::null_mechanism_t::status () const
{ {
const bool command_sent = const bool command_sent = ready_command_sent || error_command_sent;
ready_command_sent || error_command_sent;
const bool command_received = const bool command_received =
ready_command_received || error_command_received; ready_command_received || error_command_received;
if (ready_command_sent && ready_command_received) if (ready_command_sent && ready_command_received)
return mechanism_t::ready; return mechanism_t::ready;
else else if (command_sent && command_received)
if (command_sent && command_received)
return error; return error;
else else
return handshaking; return handshaking;

View File

@@ -36,14 +36,12 @@
namespace zmq namespace zmq
{ {
class msg_t; class msg_t;
class session_base_t; class session_base_t;
class null_mechanism_t : public zap_client_t class null_mechanism_t : public zap_client_t
{ {
public: public:
null_mechanism_t (session_base_t *session_, null_mechanism_t (session_base_t *session_,
const std::string &peer_address, const std::string &peer_address,
const options_t &options_); const options_t &options_);
@@ -56,7 +54,6 @@ namespace zmq
virtual status_t status () const; virtual status_t status () const;
private: private:
bool ready_command_sent; bool ready_command_sent;
bool error_command_sent; bool error_command_sent;
bool ready_command_received; bool ready_command_received;
@@ -64,14 +61,11 @@ namespace zmq
bool zap_request_sent; bool zap_request_sent;
bool zap_reply_received; bool zap_reply_received;
int process_ready_command ( int process_ready_command (const unsigned char *cmd_data, size_t data_size);
const unsigned char *cmd_data, size_t data_size); int process_error_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 (); void send_zap_request ();
}; };
} }
#endif #endif

View File

@@ -39,9 +39,7 @@
#include "session_base.hpp" #include "session_base.hpp"
#include "socket_base.hpp" #include "socket_base.hpp"
zmq::object_t::object_t (ctx_t *ctx_, uint32_t tid_) : zmq::object_t::object_t (ctx_t *ctx_, uint32_t tid_) : ctx (ctx_), tid (tid_)
ctx (ctx_),
tid (tid_)
{ {
} }
@@ -73,7 +71,6 @@ zmq::ctx_t *zmq::object_t::get_ctx ()
void zmq::object_t::process_command (command_t &cmd_) void zmq::object_t::process_command (command_t &cmd_)
{ {
switch (cmd_.type) { switch (cmd_.type) {
case command_t::activate_read: case command_t::activate_read:
process_activate_read (); process_activate_read ();
break; break;
@@ -119,7 +116,8 @@ void zmq::object_t::process_command (command_t &cmd_)
break; break;
case command_t::pipe_hwm: case command_t::pipe_hwm:
process_pipe_hwm (cmd_.args.pipe_hwm.inhwm, cmd_.args.pipe_hwm.outhwm); process_pipe_hwm (cmd_.args.pipe_hwm.inhwm,
cmd_.args.pipe_hwm.outhwm);
break; break;
case command_t::term_req: case command_t::term_req:
@@ -162,8 +160,8 @@ int zmq::object_t::register_endpoint (const char *addr_,
return ctx->register_endpoint (addr_, endpoint_); return ctx->register_endpoint (addr_, endpoint_);
} }
int zmq::object_t::unregister_endpoint ( int zmq::object_t::unregister_endpoint (const std::string &addr_,
const std::string &addr_, socket_base_t *socket_) socket_base_t *socket_)
{ {
return ctx->unregister_endpoint (addr_, socket_); return ctx->unregister_endpoint (addr_, socket_);
} }
@@ -179,12 +177,14 @@ zmq::endpoint_t zmq::object_t::find_endpoint (const char *addr_)
} }
void zmq::object_t::pend_connection (const std::string &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_); 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_);
} }
@@ -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_, 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_) if (inc_seqnum_)
destination_->inc_seqnum (); destination_->inc_seqnum ();
@@ -243,7 +244,8 @@ void zmq::object_t::send_attach (session_base_t *destination_,
send_command (cmd); send_command (cmd);
} }
void zmq::object_t::send_bind (own_t *destination_, pipe_t *pipe_, void zmq::object_t::send_bind (own_t *destination_,
pipe_t *pipe_,
bool inc_seqnum_) bool inc_seqnum_)
{ {
if (inc_seqnum_) if (inc_seqnum_)
@@ -299,7 +301,9 @@ void zmq::object_t::send_pipe_term_ack (pipe_t *destination_)
send_command (cmd); 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; command_t cmd;
cmd.destination = destination_; cmd.destination = destination_;
@@ -309,8 +313,7 @@ void zmq::object_t::send_pipe_hwm (pipe_t *destination_, int inhwm_, int outhwm_
send_command (cmd); send_command (cmd);
} }
void zmq::object_t::send_term_req (own_t *destination_, void zmq::object_t::send_term_req (own_t *destination_, own_t *object_)
own_t *object_)
{ {
command_t cmd; command_t cmd;
cmd.destination = destination_; cmd.destination = destination_;
@@ -473,4 +476,3 @@ void zmq::object_t::send_command (command_t &cmd_)
{ {
ctx->send_command (cmd_.destination->get_tid (), cmd_); ctx->send_command (cmd_.destination->get_tid (), cmd_);
} }

View File

@@ -35,7 +35,6 @@
namespace zmq namespace zmq
{ {
struct i_engine; struct i_engine;
struct endpoint_t; struct endpoint_t;
struct pending_connection_t; struct pending_connection_t;
@@ -53,7 +52,6 @@ namespace zmq
class object_t class object_t
{ {
public: public:
object_t (zmq::ctx_t *ctx_, uint32_t tid_); object_t (zmq::ctx_t *ctx_, uint32_t tid_);
object_t (object_t *parent_); object_t (object_t *parent_);
virtual ~object_t (); virtual ~object_t ();
@@ -63,20 +61,20 @@ namespace zmq
ctx_t *get_ctx (); ctx_t *get_ctx ();
void process_command (zmq::command_t &cmd_); void process_command (zmq::command_t &cmd_);
void send_inproc_connected (zmq::socket_base_t *socket_); void send_inproc_connected (zmq::socket_base_t *socket_);
void send_bind (zmq::own_t *destination_, zmq::pipe_t *pipe_, bool inc_seqnum_ = true); void send_bind (zmq::own_t *destination_,
zmq::pipe_t *pipe_,
bool inc_seqnum_ = true);
protected: protected:
// Using following function, socket is able to access global // Using following function, socket is able to access global
// repository of inproc endpoints. // repository of inproc endpoints.
int register_endpoint (const char *addr_, int register_endpoint (const char *addr_, const zmq::endpoint_t &endpoint_);
const zmq::endpoint_t &endpoint_); int unregister_endpoint (const std::string &addr_, socket_base_t *socket_);
int unregister_endpoint (
const std::string &addr_, socket_base_t *socket_);
void unregister_endpoints (zmq::socket_base_t *socket_); void unregister_endpoints (zmq::socket_base_t *socket_);
zmq::endpoint_t find_endpoint (const char *addr_); zmq::endpoint_t find_endpoint (const char *addr_);
void pend_connection (const std::string &addr_, void pend_connection (const std::string &addr_,
const endpoint_t &endpoint, pipe_t **pipes_); const endpoint_t &endpoint,
pipe_t **pipes_);
void connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_); void connect_pending (const char *addr_, zmq::socket_base_t *bind_socket_);
void destroy_socket (zmq::socket_base_t *socket_); void destroy_socket (zmq::socket_base_t *socket_);
@@ -90,21 +88,18 @@ namespace zmq
// Derived object can use these functions to send commands // Derived object can use these functions to send commands
// to other objects. // to other objects.
void send_stop (); void send_stop ();
void send_plug (zmq::own_t *destination_, void send_plug (zmq::own_t *destination_, bool inc_seqnum_ = true);
bool inc_seqnum_ = true); void send_own (zmq::own_t *destination_, zmq::own_t *object_);
void send_own (zmq::own_t *destination_,
zmq::own_t *object_);
void send_attach (zmq::session_base_t *destination_, void send_attach (zmq::session_base_t *destination_,
zmq::i_engine *engine_, bool inc_seqnum_ = true); zmq::i_engine *engine_,
bool inc_seqnum_ = true);
void send_activate_read (zmq::pipe_t *destination_); void send_activate_read (zmq::pipe_t *destination_);
void send_activate_write (zmq::pipe_t *destination_, void send_activate_write (zmq::pipe_t *destination_, uint64_t msgs_read_);
uint64_t msgs_read_);
void send_hiccup (zmq::pipe_t *destination_, void *pipe_); void send_hiccup (zmq::pipe_t *destination_, void *pipe_);
void send_pipe_term (zmq::pipe_t *destination_); void send_pipe_term (zmq::pipe_t *destination_);
void send_pipe_term_ack (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_pipe_hwm (zmq::pipe_t *destination_, int inhwm_, int outhwm_);
void send_term_req (zmq::own_t *destination_, void send_term_req (zmq::own_t *destination_, zmq::own_t *object_);
zmq::own_t *object_);
void send_term (zmq::own_t *destination_, int linger_); void send_term (zmq::own_t *destination_, int linger_);
void send_term_ack (zmq::own_t *destination_); void send_term_ack (zmq::own_t *destination_);
void send_term_endpoint (own_t *destination_, std::string *endpoint_); void send_term_endpoint (own_t *destination_, std::string *endpoint_);
@@ -138,7 +133,6 @@ namespace zmq
virtual void process_seqnum (); virtual void process_seqnum ();
private: private:
// Context provides access to the global state. // Context provides access to the global state.
zmq::ctx_t *ctx; zmq::ctx_t *ctx;
@@ -150,7 +144,6 @@ namespace zmq
object_t (const object_t &); object_t (const object_t &);
const object_t &operator= (const object_t &); const object_t &operator= (const object_t &);
}; };
} }
#endif #endif

View File

@@ -103,10 +103,11 @@ zmq::options_t::options_t () :
#endif #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_) { switch (optvallen_) {
case CURVE_KEYSIZE: case CURVE_KEYSIZE:
memcpy (destination, optval_, optvallen_); memcpy (destination, optval_, optvallen_);
mechanism = ZMQ_CURVE; mechanism = ZMQ_CURVE;
@@ -135,12 +136,14 @@ int zmq::options_t::set_curve_key(uint8_t * destination, const void * optval_, s
return -1; return -1;
} }
int zmq::options_t::setsockopt (int option_, const void *optval_, int zmq::options_t::setsockopt (int option_,
const void *optval_,
size_t optvallen_) size_t optvallen_)
{ {
bool is_int = (optvallen_ == sizeof (int)); bool is_int = (optvallen_ == sizeof (int));
int value = 0; int value = 0;
if (is_int) memcpy(&value, optval_, sizeof (int)); if (is_int)
memcpy (&value, optval_, sizeof (int));
#if defined(ZMQ_ACT_MILITANT) #if defined(ZMQ_ACT_MILITANT)
bool malformed = true; // Did caller pass a bad option value? bool malformed = true; // Did caller pass a bad option value?
#endif #endif
@@ -308,9 +311,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
if (optval_ == NULL && optvallen_ == 0) { if (optval_ == NULL && optvallen_ == 0) {
socks_proxy_address.clear (); socks_proxy_address.clear ();
return 0; return 0;
} } else if (optval_ != NULL && optvallen_ > 0) {
else
if (optval_ != NULL && optvallen_ > 0 ) {
socks_proxy_address = socks_proxy_address =
std::string ((const char *) optval_, optvallen_); std::string ((const char *) optval_, optvallen_);
return 0; return 0;
@@ -356,9 +357,8 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
if (optvallen_ == 0 && optval_ == NULL) { if (optvallen_ == 0 && optval_ == NULL) {
tcp_accept_filters.clear (); tcp_accept_filters.clear ();
return 0; return 0;
} } else if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL
else && *((const char *) optval_) != 0) {
if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL && *((const char*) optval_) != 0) {
std::string filter_str ((const char *) optval_, optvallen_); std::string filter_str ((const char *) optval_, optvallen_);
tcp_address_mask_t mask; tcp_address_mask_t mask;
int rc = mask.resolve (filter_str.c_str (), ipv6); 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) { if (optvallen_ == 0 && optval_ == NULL) {
ipc_uid_accept_filters.clear (); ipc_uid_accept_filters.clear ();
return 0; 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_)); ipc_uid_accept_filters.insert (*((uid_t *) optval_));
return 0; return 0;
} }
@@ -386,9 +384,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
if (optvallen_ == 0 && optval_ == NULL) { if (optvallen_ == 0 && optval_ == NULL) {
ipc_gid_accept_filters.clear (); ipc_gid_accept_filters.clear ();
return 0; 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_)); ipc_gid_accept_filters.insert (*((gid_t *) optval_));
return 0; return 0;
} }
@@ -400,9 +396,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
if (optvallen_ == 0 && optval_ == NULL) { if (optvallen_ == 0 && optval_ == NULL) {
ipc_pid_accept_filters.clear (); ipc_pid_accept_filters.clear ();
return 0; 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_)); ipc_pid_accept_filters.insert (*((pid_t *) optval_));
return 0; return 0;
} }
@@ -421,9 +415,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
if (optvallen_ == 0 && optval_ == NULL) { if (optvallen_ == 0 && optval_ == NULL) {
mechanism = ZMQ_NULL; mechanism = ZMQ_NULL;
return 0; 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_); plain_username.assign ((const char *) optval_, optvallen_);
as_server = 0; as_server = 0;
mechanism = ZMQ_PLAIN; mechanism = ZMQ_PLAIN;
@@ -435,9 +427,7 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
if (optvallen_ == 0 && optval_ == NULL) { if (optvallen_ == 0 && optval_ == NULL) {
mechanism = ZMQ_NULL; mechanism = ZMQ_NULL;
return 0; 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_); plain_password.assign ((const char *) optval_, optvallen_);
as_server = 0; as_server = 0;
mechanism = ZMQ_PLAIN; mechanism = ZMQ_PLAIN;
@@ -509,7 +499,8 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
case ZMQ_GSSAPI_SERVICE_PRINCIPAL: case ZMQ_GSSAPI_SERVICE_PRINCIPAL:
if (optvallen_ > 0 && optvallen_ < 256 && optval_ != NULL) { 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; mechanism = ZMQ_GSSAPI;
as_server = 0; as_server = 0;
return 0; return 0;
@@ -524,7 +515,8 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
break; break;
case ZMQ_GSSAPI_PRINCIPAL_NAMETYPE: case ZMQ_GSSAPI_PRINCIPAL_NAMETYPE:
if (is_int && (value == ZMQ_GSSAPI_NT_HOSTBASED if (is_int
&& (value == ZMQ_GSSAPI_NT_HOSTBASED
|| value == ZMQ_GSSAPI_NT_USER_NAME || value == ZMQ_GSSAPI_NT_USER_NAME
|| value == ZMQ_GSSAPI_NT_KRB5_PRINCIPAL)) { || value == ZMQ_GSSAPI_NT_KRB5_PRINCIPAL)) {
gss_principal_nt = value; gss_principal_nt = value;
@@ -533,7 +525,8 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
break; break;
case ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE: case ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE:
if (is_int && (value == ZMQ_GSSAPI_NT_HOSTBASED if (is_int
&& (value == ZMQ_GSSAPI_NT_HOSTBASED
|| value == ZMQ_GSSAPI_NT_USER_NAME || value == ZMQ_GSSAPI_NT_USER_NAME
|| value == ZMQ_GSSAPI_NT_KRB5_PRINCIPAL)) { || value == ZMQ_GSSAPI_NT_KRB5_PRINCIPAL)) {
gss_service_principal_nt = value; gss_service_principal_nt = value;
@@ -620,11 +613,9 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
if (optval_ == NULL && optvallen_ == 0) { if (optval_ == NULL && optvallen_ == 0) {
bound_device.clear (); bound_device.clear ();
return 0; return 0;
} } else if (optval_ != NULL && optvallen_ > 0
else && optvallen_ <= BINDDEVSIZ) {
if (optval_ != NULL && optvallen_ > 0 && optvallen_ <= BINDDEVSIZ) { bound_device = std::string ((const char *) optval_, optvallen_);
bound_device =
std::string ((const char *) optval_, optvallen_);
return 0; return 0;
} }
break; break;
@@ -658,7 +649,9 @@ int zmq::options_t::setsockopt (int option_, const void *optval_,
return -1; 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)); bool is_int = (*optvallen_ == sizeof (int));
int *value = (int *) optval_; int *value = (int *) optval_;
@@ -839,7 +832,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
case ZMQ_SOCKS_PROXY: case ZMQ_SOCKS_PROXY:
if (*optvallen_ >= socks_proxy_address.size () + 1) { 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; *optvallen_ = socks_proxy_address.size () + 1;
return 0; return 0;
} }
@@ -889,7 +883,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
case ZMQ_PLAIN_USERNAME: case ZMQ_PLAIN_USERNAME:
if (*optvallen_ >= plain_username.size () + 1) { 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; *optvallen_ = plain_username.size () + 1;
return 0; return 0;
} }
@@ -897,7 +892,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
case ZMQ_PLAIN_PASSWORD: case ZMQ_PLAIN_PASSWORD:
if (*optvallen_ >= plain_password.size () + 1) { 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; *optvallen_ = plain_password.size () + 1;
return 0; return 0;
} }
@@ -924,10 +920,9 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
if (*optvallen_ == CURVE_KEYSIZE) { if (*optvallen_ == CURVE_KEYSIZE) {
memcpy (optval_, curve_public_key, CURVE_KEYSIZE); memcpy (optval_, curve_public_key, CURVE_KEYSIZE);
return 0; return 0;
} } else if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) {
else zmq_z85_encode ((char *) optval_, curve_public_key,
if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) { CURVE_KEYSIZE);
zmq_z85_encode ((char *) optval_, curve_public_key, CURVE_KEYSIZE);
return 0; return 0;
} }
break; break;
@@ -936,10 +931,9 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
if (*optvallen_ == CURVE_KEYSIZE) { if (*optvallen_ == CURVE_KEYSIZE) {
memcpy (optval_, curve_secret_key, CURVE_KEYSIZE); memcpy (optval_, curve_secret_key, CURVE_KEYSIZE);
return 0; return 0;
} } else if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) {
else zmq_z85_encode ((char *) optval_, curve_secret_key,
if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) { CURVE_KEYSIZE);
zmq_z85_encode ((char *) optval_, curve_secret_key, CURVE_KEYSIZE);
return 0; return 0;
} }
break; break;
@@ -948,10 +942,9 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
if (*optvallen_ == CURVE_KEYSIZE) { if (*optvallen_ == CURVE_KEYSIZE) {
memcpy (optval_, curve_server_key, CURVE_KEYSIZE); memcpy (optval_, curve_server_key, CURVE_KEYSIZE);
return 0; return 0;
} } else if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) {
else zmq_z85_encode ((char *) optval_, curve_server_key,
if (*optvallen_ == CURVE_KEYSIZE_Z85 + 1) { CURVE_KEYSIZE);
zmq_z85_encode ((char *) optval_, curve_server_key, CURVE_KEYSIZE);
return 0; return 0;
} }
break; break;
@@ -975,7 +968,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
case ZMQ_GSSAPI_PRINCIPAL: case ZMQ_GSSAPI_PRINCIPAL:
if (*optvallen_ >= gss_principal.size () + 1) { 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; *optvallen_ = gss_principal.size () + 1;
return 0; return 0;
} }
@@ -983,7 +977,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
case ZMQ_GSSAPI_SERVICE_PRINCIPAL: case ZMQ_GSSAPI_SERVICE_PRINCIPAL:
if (*optvallen_ >= gss_service_principal.size () + 1) { 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; *optvallen_ = gss_service_principal.size () + 1;
return 0; return 0;
} }
@@ -1055,7 +1050,8 @@ int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
case ZMQ_BINDTODEVICE: case ZMQ_BINDTODEVICE:
if (*optvallen_ >= bound_device.size () + 1) { 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; *optvallen_ = bound_device.size () + 1;
return 0; return 0;
} }

View File

@@ -56,7 +56,9 @@ namespace zmq
{ {
options_t (); options_t ();
int set_curve_key(uint8_t * destination, const void * optval_, size_t optvallen_); int set_curve_key (uint8_t *destination,
const void *optval_,
size_t optvallen_);
int setsockopt (int option_, 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; int getsockopt (int option_, void *optval_, size_t *optvallen_) const;

Some files were not shown because too many files have changed in this diff Show More