summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJaromil <jaromil@dyne.org>2012-02-21 16:22:03 (GMT)
committer Jaromil <jaromil@dyne.org>2012-02-21 16:22:03 (GMT)
commit0a6f44a0abeec1a1b813d2bb64e177abceb1bfbd (patch)
treec8220f99e8b31d5b7a4bfa5fd30c53f3cb35db47
parent76c2e865f43348bbae868b795d7a641da5a0b3f6 (diff)
included a fully featured 0mq
compiles as static library with all dependencies tested with mips target, examples work
-rw-r--r--Makefile.am1
-rw-r--r--configure.ac7
-rw-r--r--src/0mq/Makefile.am142
-rw-r--r--src/0mq/array.hpp147
-rw-r--r--src/0mq/atomic_counter.hpp164
-rw-r--r--src/0mq/atomic_ptr.hpp159
-rw-r--r--src/0mq/blob.hpp34
-rw-r--r--src/0mq/clock.cpp130
-rw-r--r--src/0mq/clock.hpp60
-rw-r--r--src/0mq/command.cpp39
-rw-r--r--src/0mq/command.hpp147
-rw-r--r--src/0mq/config.hpp95
-rw-r--r--src/0mq/connect_session.cpp119
-rw-r--r--src/0mq/connect_session.hpp65
-rw-r--r--src/0mq/ctx.cpp324
-rw-r--r--src/0mq/ctx.hpp159
-rw-r--r--src/0mq/decoder.cpp129
-rw-r--r--src/0mq/decoder.hpp207
-rw-r--r--src/0mq/device.cpp134
-rw-r--r--src/0mq/device.hpp32
-rw-r--r--src/0mq/devpoll.cpp190
-rw-r--r--src/0mq/devpoll.hpp100
-rw-r--r--src/0mq/dist.cpp200
-rw-r--r--src/0mq/dist.hpp90
-rw-r--r--src/0mq/encoder.cpp90
-rw-r--r--src/0mq/encoder.hpp184
-rw-r--r--src/0mq/epoll.cpp177
-rw-r--r--src/0mq/epoll.hpp96
-rw-r--r--src/0mq/err.cpp251
-rw-r--r--src/0mq/err.hpp150
-rw-r--r--src/0mq/fd.hpp45
-rw-r--r--src/0mq/fq.cpp164
-rw-r--r--src/0mq/fq.hpp80
-rw-r--r--src/0mq/i_engine.hpp53
-rw-r--r--src/0mq/i_inout.hpp50
-rw-r--r--src/0mq/i_poll_events.hpp46
-rw-r--r--src/0mq/io_object.cpp107
-rw-r--r--src/0mq/io_object.hpp78
-rw-r--r--src/0mq/io_thread.cpp109
-rw-r--r--src/0mq/io_thread.hpp88
-rw-r--r--src/0mq/ip.cpp369
-rw-r--r--src/0mq/ip.hpp70
-rw-r--r--src/0mq/kqueue.cpp203
-rw-r--r--src/0mq/kqueue.hpp103
-rw-r--r--src/0mq/lb.cpp174
-rw-r--r--src/0mq/lb.hpp79
-rw-r--r--src/0mq/libzmq.pc.in10
-rw-r--r--src/0mq/likely.hpp33
-rw-r--r--src/0mq/mailbox.cpp87
-rw-r--r--src/0mq/mailbox.hpp74
-rw-r--r--src/0mq/msg_content.hpp52
-rw-r--r--src/0mq/mutex.hpp121
-rw-r--r--src/0mq/named_session.cpp85
-rw-r--r--src/0mq/named_session.hpp57
-rw-r--r--src/0mq/object.cpp467
-rw-r--r--src/0mq/object.hpp127
-rw-r--r--src/0mq/options.cpp344
-rw-r--r--src/0mq/options.hpp87
-rw-r--r--src/0mq/own.cpp214
-rw-r--r--src/0mq/own.hpp140
-rw-r--r--src/0mq/pair.cpp180
-rw-r--r--src/0mq/pair.hpp76
-rw-r--r--src/0mq/pgm_receiver.cpp259
-rw-r--r--src/0mq/pgm_receiver.hpp129
-rw-r--r--src/0mq/pgm_sender.cpp215
-rw-r--r--src/0mq/pgm_sender.hpp105
-rw-r--r--src/0mq/pgm_socket.cpp705
-rw-r--r--src/0mq/pgm_socket.hpp119
-rw-r--r--src/0mq/pipe.cpp409
-rw-r--r--src/0mq/pipe.hpp214
-rw-r--r--src/0mq/platform.hpp243
-rw-r--r--src/0mq/poll.cpp180
-rw-r--r--src/0mq/poll.hpp104
-rw-r--r--src/0mq/poller.hpp73
-rw-r--r--src/0mq/poller_base.cpp99
-rw-r--r--src/0mq/poller_base.hpp84
-rw-r--r--src/0mq/pub.cpp31
-rw-r--r--src/0mq/pub.hpp44
-rw-r--r--src/0mq/pull.cpp61
-rw-r--r--src/0mq/pull.hpp60
-rw-r--r--src/0mq/push.cpp62
-rw-r--r--src/0mq/push.hpp59
-rw-r--r--src/0mq/reaper.cpp121
-rw-r--r--src/0mq/reaper.hpp77
-rw-r--r--src/0mq/rep.cpp131
-rw-r--r--src/0mq/rep.hpp59
-rw-r--r--src/0mq/req.cpp125
-rw-r--r--src/0mq/req.hpp58
-rw-r--r--src/0mq/select.cpp212
-rw-r--r--src/0mq/select.hpp116
-rw-r--r--src/0mq/semaphore.hpp189
-rw-r--r--src/0mq/session.cpp347
-rw-r--r--src/0mq/session.hpp150
-rw-r--r--src/0mq/signaler.cpp344
-rw-r--r--src/0mq/signaler.hpp63
-rw-r--r--src/0mq/socket_base.cpp861
-rw-r--r--src/0mq/socket_base.hpp207
-rw-r--r--src/0mq/stdint.hpp63
-rw-r--r--src/0mq/sub.cpp75
-rw-r--r--src/0mq/sub.hpp50
-rw-r--r--src/0mq/swap.cpp323
-rw-r--r--src/0mq/swap.hpp123
-rw-r--r--src/0mq/tcp_connecter.cpp312
-rw-r--r--src/0mq/tcp_connecter.hpp81
-rw-r--r--src/0mq/tcp_listener.cpp371
-rw-r--r--src/0mq/tcp_listener.hpp73
-rw-r--r--src/0mq/tcp_socket.cpp239
-rw-r--r--src/0mq/tcp_socket.hpp72
-rw-r--r--src/0mq/thread.cpp99
-rw-r--r--src/0mq/thread.hpp78
-rw-r--r--src/0mq/transient_session.cpp41
-rw-r--r--src/0mq/transient_session.hpp52
-rw-r--r--src/0mq/trie.cpp181
-rw-r--r--src/0mq/trie.hpp59
-rw-r--r--src/0mq/uuid.cpp241
-rw-r--r--src/0mq/uuid.hpp116
-rw-r--r--src/0mq/windows.hpp177
-rw-r--r--src/0mq/wire.hpp99
-rw-r--r--src/0mq/xpub.cpp76
-rw-r--r--src/0mq/xpub.hpp61
-rw-r--r--src/0mq/xrep.cpp332
-rw-r--r--src/0mq/xrep.hpp116
-rw-r--r--src/0mq/xreq.cpp74
-rw-r--r--src/0mq/xreq.hpp65
-rw-r--r--src/0mq/xsub.cpp172
-rw-r--r--src/0mq/xsub.hpp80
-rw-r--r--src/0mq/ypipe.hpp209
-rw-r--r--src/0mq/yqueue.hpp198
-rw-r--r--src/0mq/zmq.cpp808
-rw-r--r--src/0mq/zmq.hpp340
-rw-r--r--src/0mq/zmq_connecter.cpp166
-rw-r--r--src/0mq/zmq_connecter.hpp92
-rw-r--r--src/0mq/zmq_engine.cpp220
-rw-r--r--src/0mq/zmq_engine.hpp87
-rw-r--r--src/0mq/zmq_init.cpp216
-rw-r--r--src/0mq/zmq_init.hpp93
-rw-r--r--src/0mq/zmq_listener.cpp78
-rw-r--r--src/0mq/zmq_listener.hpp67
-rw-r--r--src/Makefile.am11
-rw-r--r--src/hwclient.cpp38
-rw-r--r--src/hwserver.cpp41
-rw-r--r--src/include/impl/checksum.h78
-rw-r--r--src/include/impl/engine.h46
-rw-r--r--src/include/impl/errno.h42
-rw-r--r--src/include/impl/features.h58
-rw-r--r--src/include/impl/fixed.h159
-rw-r--r--src/include/impl/framework.h84
-rw-r--r--src/include/impl/galois.h156
-rw-r--r--src/include/impl/get_nprocs.h41
-rw-r--r--src/include/impl/getifaddrs.h79
-rw-r--r--src/include/impl/getnetbyname.h49
-rw-r--r--src/include/impl/getnodeaddr.h48
-rw-r--r--src/include/impl/getprotobyname.h49
-rw-r--r--src/include/impl/hashtable.h61
-rw-r--r--src/include/impl/histogram.h132
-rw-r--r--src/include/impl/i18n.h35
-rw-r--r--src/include/impl/indextoaddr.h44
-rw-r--r--src/include/impl/indextoname.h40
-rw-r--r--src/include/impl/inet_network.h46
-rw-r--r--src/include/impl/ip.h153
-rw-r--r--src/include/impl/list.h46
-rw-r--r--src/include/impl/math.h89
-rw-r--r--src/include/impl/md5.h64
-rw-r--r--src/include/impl/mem.h37
-rw-r--r--src/include/impl/messages.h361
-rw-r--r--src/include/impl/nametoindex.h43
-rw-r--r--src/include/impl/net.h57
-rw-r--r--src/include/impl/notify.h307
-rw-r--r--src/include/impl/packet_parse.h48
-rw-r--r--src/include/impl/packet_test.h43
-rw-r--r--src/include/impl/pgmMIB.h31
-rw-r--r--src/include/impl/pgmMIB_columns.h376
-rw-r--r--src/include/impl/pgmMIB_enums.h68
-rw-r--r--src/include/impl/processor.h51
-rw-r--r--src/include/impl/queue.h54
-rw-r--r--src/include/impl/rand.h53
-rw-r--r--src/include/impl/rate_control.h59
-rw-r--r--src/include/impl/receiver.h144
-rw-r--r--src/include/impl/reed_solomon.h54
-rw-r--r--src/include/impl/rwspinlock.h140
-rw-r--r--src/include/impl/rxw.h226
-rw-r--r--src/include/impl/security.h260
-rw-r--r--src/include/impl/slist.h55
-rw-r--r--src/include/impl/sn.h137
-rw-r--r--src/include/impl/sockaddr.h176
-rw-r--r--src/include/impl/socket.h189
-rw-r--r--src/include/impl/source.h78
-rw-r--r--src/include/impl/sqn_list.h41
-rw-r--r--src/include/impl/string.h62
-rw-r--r--src/include/impl/thread.h346
-rw-r--r--src/include/impl/ticket.h407
-rw-r--r--src/include/impl/time.h54
-rw-r--r--src/include/impl/timer.h61
-rw-r--r--src/include/impl/tsi.h42
-rw-r--r--src/include/impl/txw.h210
-rw-r--r--src/include/impl/wsastrerror.h40
-rw-r--r--src/include/pgm/atomic.h202
-rw-r--r--src/include/pgm/backtrace.h36
-rw-r--r--src/include/pgm/engine.h40
-rw-r--r--src/include/pgm/error.h112
-rw-r--r--src/include/pgm/gsi.h54
-rw-r--r--src/include/pgm/http.h39
-rw-r--r--src/include/pgm/if.h36
-rw-r--r--src/include/pgm/in.h52
-rw-r--r--src/include/pgm/ip/pgm.hh100
-rw-r--r--src/include/pgm/ip/pgm_endpoint.hh171
-rw-r--r--src/include/pgm/list.h43
-rw-r--r--src/include/pgm/log.h36
-rw-r--r--src/include/pgm/macros.h177
-rw-r--r--src/include/pgm/mem.h63
-rw-r--r--src/include/pgm/messages.h69
-rw-r--r--src/include/pgm/msgv.h57
-rw-r--r--src/include/pgm/packet.h478
-rw-r--r--src/include/pgm/pgm.h54
-rw-r--r--src/include/pgm/pgm.hh33
-rw-r--r--src/include/pgm/pgm_socket.hh157
-rw-r--r--src/include/pgm/retypes.h25
-rw-r--r--src/include/pgm/signal.h39
-rw-r--r--src/include/pgm/skbuff.h262
-rw-r--r--src/include/pgm/snmp.h37
-rw-r--r--src/include/pgm/socket.h191
-rw-r--r--src/include/pgm/time.h57
-rw-r--r--src/include/pgm/tsi.h52
-rw-r--r--src/include/pgm/types.h99
-rw-r--r--src/include/pgm/untypes.h25
-rw-r--r--src/include/pgm/version.h44
-rw-r--r--src/include/pgm/winint.h201
-rw-r--r--src/include/pgm/wininttypes.h257
-rw-r--r--src/include/pgm/zinttypes.h46
-rw-r--r--src/include/zmq.h269
-rw-r--r--src/include/zmq_utils.h64
-rw-r--r--src/pgm/Makefile.am64
-rw-r--r--src/pgm/checksum.c949
-rw-r--r--src/pgm/engine.c261
-rw-r--r--src/pgm/error.c518
-rwxr-xr-xsrc/pgm/galois_generator.pl139
-rw-r--r--src/pgm/galois_tables.c8297
-rw-r--r--src/pgm/get_nprocs.c214
-rw-r--r--src/pgm/getifaddrs.c871
-rw-r--r--src/pgm/getnetbyname.c289
-rw-r--r--src/pgm/getnodeaddr.c303
-rw-r--r--src/pgm/getprotobyname.c90
-rw-r--r--src/pgm/gsi.c227
-rw-r--r--src/pgm/hashtable.c338
-rw-r--r--src/pgm/histogram.c418
-rw-r--r--src/pgm/if.c1806
-rw-r--r--src/pgm/indextoaddr.c99
-rw-r--r--src/pgm/indextoname.c52
-rw-r--r--src/pgm/inet_network.c367
-rw-r--r--src/pgm/list.c152
-rw-r--r--src/pgm/math.c75
-rw-r--r--src/pgm/md5.c371
-rw-r--r--src/pgm/mem.c283
-rw-r--r--src/pgm/messages.c192
-rw-r--r--src/pgm/nametoindex.c252
-rw-r--r--src/pgm/net.c197
-rw-r--r--src/pgm/packet_parse.c622
-rw-r--r--src/pgm/packet_test.c1162
-rw-r--r--src/pgm/queue.c115
-rw-r--r--src/pgm/rand.c143
-rw-r--r--src/pgm/rate_control.c352
-rw-r--r--src/pgm/receiver.c2381
-rw-r--r--src/pgm/recv.c1056
-rw-r--r--src/pgm/reed_solomon.c583
-rw-r--r--src/pgm/rxw.c2263
-rw-r--r--src/pgm/skbuff.c115
-rw-r--r--src/pgm/slist.c174
-rw-r--r--src/pgm/sockaddr.c1318
-rw-r--r--src/pgm/socket.c2748
-rw-r--r--src/pgm/source.c2547
-rw-r--r--src/pgm/string.c518
-rw-r--r--src/pgm/thread.c546
-rw-r--r--src/pgm/time.c889
-rw-r--r--src/pgm/timer.c225
-rw-r--r--src/pgm/tsi.c121
-rw-r--r--src/pgm/txw.c776
-rw-r--r--src/pgm/version.c40
-rwxr-xr-xsrc/pgm/version_generator.py52
-rw-r--r--src/pgm/wsastrerror.c372
-rw-r--r--src/uuid/COPYING25
-rw-r--r--src/uuid/Makefile.am22
-rw-r--r--src/uuid/clear.c44
-rw-r--r--src/uuid/compare.c56
-rw-r--r--src/uuid/copy.c46
-rw-r--r--src/uuid/gen_uuid.c659
-rw-r--r--src/uuid/gen_uuid_nt.c93
-rw-r--r--src/uuid/isnull.c49
-rw-r--r--src/uuid/pack.c70
-rw-r--r--src/uuid/parse.c80
-rw-r--r--src/uuid/tst_uuid.c182
-rw-r--r--src/uuid/unpack.c64
-rw-r--r--src/uuid/unparse.c77
-rw-r--r--src/uuid/uuid.h103
-rw-r--r--src/uuid/uuidP.h59
-rw-r--r--src/uuid/uuid_time.c173
-rw-r--r--src/uuid/uuidd.h54
296 files changed, 68055 insertions, 3 deletions
diff --git a/Makefile.am b/Makefile.am
index af437a6..0a7b929 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1 +1,2 @@
+ACLOCAL_AMFLAGS = -I m4
SUBDIRS = src
diff --git a/configure.ac b/configure.ac
index 06e0fd9..05a48c8 100644
--- a/configure.ac
+++ b/configure.ac
@@ -31,12 +31,12 @@ AC_PROG_CPP
AC_PROG_INSTALL
AC_PROG_LN_S
AC_PROG_MAKE_SET
-
+AC_PROG_LIBTOOL
dnl Fortunately we have Solaris...
AC_CHECK_HEADERS(sys/sockio.h)
-AC_CHECK_FUNCS(srandom random)
+AC_CHECK_FUNCS(srandom random sysconf)
if test $ac_cv_func_srandom = no; then
# let's try with the older srand/rand functions
AC_CHECK_FUNCS(srand rand)
@@ -78,6 +78,9 @@ AC_SUBST(CXXFLAGS)
AC_CONFIG_FILES([
Makefile
src/Makefile
+src/uuid/Makefile
+src/pgm/Makefile
+src/0mq/Makefile
])
AC_OUTPUT
diff --git a/src/0mq/Makefile.am b/src/0mq/Makefile.am
new file mode 100644
index 0000000..e1a0f00
--- /dev/null
+++ b/src/0mq/Makefile.am
@@ -0,0 +1,142 @@
+INCLUDES = -I$(top_srcdir)/src -I$(top_srcdir)/src/include
+
+noinst_LTLIBRARIES = libzmq.la
+
+noinst_HEADERS = zmq.hpp
+
+libzmq_la_LIBADD = $(top_builddir)/src/uuid/libuuid.la
+
+libzmq_la_SOURCES = \
+ array.hpp \
+ atomic_counter.hpp \
+ atomic_ptr.hpp \
+ blob.hpp \
+ clock.hpp \
+ command.hpp \
+ config.hpp \
+ connect_session.hpp \
+ ctx.hpp \
+ decoder.hpp \
+ device.hpp \
+ devpoll.hpp \
+ dist.hpp \
+ encoder.hpp \
+ epoll.hpp \
+ err.hpp \
+ fd.hpp \
+ fq.hpp \
+ i_inout.hpp \
+ io_object.hpp \
+ io_thread.hpp \
+ ip.hpp \
+ i_engine.hpp \
+ i_poll_events.hpp \
+ kqueue.hpp \
+ lb.hpp \
+ likely.hpp \
+ mailbox.hpp \
+ msg_content.hpp \
+ mutex.hpp \
+ named_session.hpp \
+ object.hpp \
+ options.hpp \
+ own.hpp \
+ pgm_receiver.hpp \
+ pgm_sender.hpp \
+ pgm_socket.hpp \
+ pipe.hpp \
+ platform.hpp \
+ poll.hpp \
+ poller.hpp \
+ poller_base.hpp \
+ pair.hpp \
+ pub.hpp \
+ pull.hpp \
+ push.hpp \
+ reaper.hpp \
+ rep.hpp \
+ req.hpp \
+ select.hpp \
+ semaphore.hpp \
+ session.hpp \
+ signaler.hpp \
+ socket_base.hpp \
+ stdint.hpp \
+ sub.hpp \
+ swap.hpp \
+ tcp_connecter.hpp \
+ tcp_listener.hpp \
+ tcp_socket.hpp \
+ thread.hpp \
+ transient_session.hpp \
+ trie.hpp \
+ uuid.hpp \
+ windows.hpp \
+ wire.hpp \
+ xpub.hpp \
+ xrep.hpp \
+ xreq.hpp \
+ xsub.hpp \
+ ypipe.hpp \
+ yqueue.hpp \
+ zmq_connecter.hpp \
+ zmq_engine.hpp \
+ zmq_init.hpp \
+ zmq_listener.hpp \
+ clock.cpp \
+ command.cpp \
+ ctx.cpp \
+ connect_session.cpp \
+ decoder.cpp \
+ device.cpp \
+ devpoll.cpp \
+ dist.cpp \
+ encoder.cpp \
+ epoll.cpp \
+ err.cpp \
+ fq.cpp \
+ io_object.cpp \
+ io_thread.cpp \
+ ip.cpp \
+ kqueue.cpp \
+ lb.cpp \
+ mailbox.cpp \
+ named_session.cpp \
+ object.cpp \
+ options.cpp \
+ own.cpp \
+ pair.cpp \
+ pgm_receiver.cpp \
+ pgm_sender.cpp \
+ pgm_socket.cpp \
+ pipe.cpp \
+ poll.cpp \
+ poller_base.cpp \
+ pull.cpp \
+ push.cpp \
+ reaper.cpp \
+ pub.cpp \
+ rep.cpp \
+ req.cpp \
+ select.cpp \
+ session.cpp \
+ signaler.cpp \
+ socket_base.cpp \
+ sub.cpp \
+ swap.cpp \
+ tcp_connecter.cpp \
+ tcp_listener.cpp \
+ tcp_socket.cpp \
+ thread.cpp \
+ transient_session.cpp \
+ trie.cpp \
+ uuid.cpp \
+ xpub.cpp \
+ xrep.cpp \
+ xreq.cpp \
+ xsub.cpp \
+ zmq.cpp \
+ zmq_connecter.cpp \
+ zmq_engine.cpp \
+ zmq_init.cpp \
+ zmq_listener.cpp
diff --git a/src/0mq/array.hpp b/src/0mq/array.hpp
new file mode 100644
index 0000000..b9f7f78
--- /dev/null
+++ b/src/0mq/array.hpp
@@ -0,0 +1,147 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_ARRAY_INCLUDED__
+#define __ZMQ_ARRAY_INCLUDED__
+
+#include <vector>
+#include <algorithm>
+
+namespace zmq
+{
+
+ // Base class for objects stored in the array. Note that each object can
+ // be stored in at most one array.
+
+ class array_item_t
+ {
+ public:
+
+ inline array_item_t () :
+ array_index (-1)
+ {
+ }
+
+ // The destructor doesn't have to be virtual. It is mad virtual
+ // just to keep ICC and code checking tools from complaining.
+ inline virtual ~array_item_t ()
+ {
+ }
+
+ inline void set_array_index (int index_)
+ {
+ array_index = index_;
+ }
+
+ inline int get_array_index ()
+ {
+ return array_index;
+ }
+
+ private:
+
+ int array_index;
+
+ array_item_t (const array_item_t&);
+ const array_item_t &operator = (const array_item_t&);
+ };
+
+ // Fast array implementation with O(1) access to item, insertion and
+ // removal. Array stores pointers rather than objects. The objects have
+ // to be derived from array_item_t class.
+
+ template <typename T> class array_t
+ {
+ public:
+
+ typedef typename std::vector <T*>::size_type size_type;
+
+ inline array_t ()
+ {
+ }
+
+ inline ~array_t ()
+ {
+ }
+
+ inline size_type size ()
+ {
+ return items.size ();
+ }
+
+ inline bool empty ()
+ {
+ return items.empty ();
+ }
+
+ inline T *&operator [] (size_type index_)
+ {
+ return items [index_];
+ }
+
+ inline void push_back (T *item_)
+ {
+ if (item_)
+ item_->set_array_index (items.size ());
+ items.push_back (item_);
+ }
+
+ inline void erase (T *item_) {
+ erase (item_->get_array_index ());
+ }
+
+ inline void erase (size_type index_) {
+ if (items.back ())
+ items.back ()->set_array_index (index_);
+ items [index_] = items.back ();
+ items.pop_back ();
+ }
+
+ inline void swap (size_type index1_, size_type index2_)
+ {
+ if (items [index1_])
+ items [index1_]->set_array_index (index2_);
+ if (items [index2_])
+ items [index2_]->set_array_index (index1_);
+ std::swap (items [index1_], items [index2_]);
+ }
+
+ inline void clear ()
+ {
+ items.clear ();
+ }
+
+ inline size_type index (T *item_)
+ {
+ return (size_type) item_->get_array_index ();
+ }
+
+ private:
+
+ typedef std::vector <T*> items_t;
+ items_t items;
+
+ array_t (const array_t&);
+ const array_t &operator = (const array_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/atomic_counter.hpp b/src/0mq/atomic_counter.hpp
new file mode 100644
index 0000000..d7116d8
--- /dev/null
+++ b/src/0mq/atomic_counter.hpp
@@ -0,0 +1,164 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_ATOMIC_COUNTER_HPP_INCLUDED__
+#define __ZMQ_ATOMIC_COUNTER_HPP_INCLUDED__
+
+#include "stdint.hpp"
+#include "platform.hpp"
+
+#if defined ZMQ_FORCE_MUTEXES
+#define ZMQ_ATOMIC_COUNTER_MUTEX
+#elif (defined __i386__ || defined __x86_64__) && defined __GNUC__
+#define ZMQ_ATOMIC_COUNTER_X86
+#elif defined ZMQ_HAVE_WINDOWS
+#define ZMQ_ATOMIC_COUNTER_WINDOWS
+#elif (defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_NETBSD)
+#define ZMQ_ATOMIC_COUNTER_ATOMIC_H
+#else
+#define ZMQ_ATOMIC_COUNTER_MUTEX
+#endif
+
+#if defined ZMQ_ATOMIC_COUNTER_MUTEX
+#include "mutex.hpp"
+#elif defined ZMQ_ATOMIC_COUNTER_WINDOWS
+#include "windows.hpp"
+#elif defined ZMQ_ATOMIC_COUNTER_ATOMIC_H
+#include <atomic.h>
+#endif
+
+namespace zmq
+{
+
+ // This class represents an integer that can be incremented/decremented
+ // in atomic fashion.
+
+ class atomic_counter_t
+ {
+ public:
+
+ typedef uint32_t integer_t;
+
+ inline atomic_counter_t (integer_t value_ = 0) :
+ value (value_)
+ {
+ }
+
+ inline ~atomic_counter_t ()
+ {
+ }
+
+ // Set counter value (not thread-safe).
+ inline void set (integer_t value_)
+ {
+ value = value_;
+ }
+
+ // Atomic addition. Returns the old value.
+ inline integer_t add (integer_t increment_)
+ {
+ integer_t old_value;
+
+#if defined ZMQ_ATOMIC_COUNTER_WINDOWS
+ old_value = InterlockedExchangeAdd ((LONG*) &value, increment_);
+#elif defined ZMQ_ATOMIC_COUNTER_ATOMIC_H
+ integer_t new_value = atomic_add_32_nv (&value, increment_);
+ old_value = new_value - increment_;
+#elif defined ZMQ_ATOMIC_COUNTER_X86
+ __asm__ volatile (
+ "lock; xadd %0, %1 \n\t"
+ : "=r" (old_value), "=m" (value)
+ : "0" (increment_), "m" (value)
+ : "cc", "memory");
+#elif defined ZMQ_ATOMIC_COUNTER_MUTEX
+ sync.lock ();
+ old_value = value;
+ value += increment_;
+ sync.unlock ();
+#else
+#error atomic_counter is not implemented for this platform
+#endif
+ return old_value;
+ }
+
+ // Atomic subtraction. Returns false if the counter drops to zero.
+ inline bool sub (integer_t decrement)
+ {
+#if defined ZMQ_ATOMIC_COUNTER_WINDOWS
+ LONG delta = - ((LONG) decrement);
+ integer_t old = InterlockedExchangeAdd ((LONG*) &value, delta);
+ return old - decrement != 0;
+#elif defined ZMQ_ATOMIC_COUNTER_ATOMIC_H
+ int32_t delta = - ((int32_t) decrement);
+ integer_t nv = atomic_add_32_nv (&value, delta);
+ return nv != 0;
+#elif defined ZMQ_ATOMIC_COUNTER_X86
+ integer_t oldval = -decrement;
+ volatile integer_t *val = &value;
+ __asm__ volatile ("lock; xaddl %0,%1"
+ : "=r" (oldval), "=m" (*val)
+ : "0" (oldval), "m" (*val)
+ : "cc", "memory");
+ return oldval != decrement;
+#elif defined ZMQ_ATOMIC_COUNTER_MUTEX
+ sync.lock ();
+ value -= decrement;
+ bool result = value ? true : false;
+ sync.unlock ();
+ return result;
+#else
+#error atomic_counter is not implemented for this platform
+#endif
+ }
+
+ inline integer_t get ()
+ {
+ return value;
+ }
+
+ private:
+
+ volatile integer_t value;
+#if defined ZMQ_ATOMIC_COUNTER_MUTEX
+ mutex_t sync;
+#endif
+
+ atomic_counter_t (const atomic_counter_t&);
+ const atomic_counter_t& operator = (const atomic_counter_t&);
+ };
+
+}
+
+// Remove macros local to this file.
+#if defined ZMQ_ATOMIC_COUNTER_WINDOWS
+#undef ZMQ_ATOMIC_COUNTER_WINDOWS
+#endif
+#if defined ZMQ_ATOMIC_COUNTER_ATOMIC_H
+#undef ZMQ_ATOMIC_COUNTER_ATOMIC_H
+#endif
+#if defined ZMQ_ATOMIC_COUNTER_X86
+#undef ZMQ_ATOMIC_COUNTER_X86
+#endif
+#if defined ZMQ_ATOMIC_COUNTER_MUTEX
+#undef ZMQ_ATOMIC_COUNTER_MUTEX
+#endif
+
+#endif
+
diff --git a/src/0mq/atomic_ptr.hpp b/src/0mq/atomic_ptr.hpp
new file mode 100644
index 0000000..c106cd5
--- /dev/null
+++ b/src/0mq/atomic_ptr.hpp
@@ -0,0 +1,159 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_ATOMIC_PTR_HPP_INCLUDED__
+#define __ZMQ_ATOMIC_PTR_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#if defined ZMQ_FORCE_MUTEXES
+#define ZMQ_ATOMIC_PTR_MUTEX
+#elif (defined __i386__ || defined __x86_64__) && defined __GNUC__
+#define ZMQ_ATOMIC_PTR_X86
+#elif defined ZMQ_HAVE_WINDOWS
+#define ZMQ_ATOMIC_PTR_WINDOWS
+#elif (defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_NETBSD)
+#define ZMQ_ATOMIC_PTR_ATOMIC_H
+#else
+#define ZMQ_ATOMIC_PTR_MUTEX
+#endif
+
+#if defined ZMQ_ATOMIC_PTR_MUTEX
+#include "mutex.hpp"
+#elif defined ZMQ_ATOMIC_PTR_WINDOWS
+#include "windows.hpp"
+#elif defined ZMQ_ATOMIC_PTR_ATOMIC_H
+#include <atomic.h>
+#endif
+
+namespace zmq
+{
+
+ // This class encapsulates several atomic operations on pointers.
+
+ template <typename T> class atomic_ptr_t
+ {
+ public:
+
+ // Initialise atomic pointer
+ inline atomic_ptr_t ()
+ {
+ ptr = NULL;
+ }
+
+ // Destroy atomic pointer
+ inline ~atomic_ptr_t ()
+ {
+ }
+
+ // Set value of atomic pointer in a non-threadsafe way
+ // Use this function only when you are sure that at most one
+ // thread is accessing the pointer at the moment.
+ inline void set (T *ptr_)
+ {
+ this->ptr = ptr_;
+ }
+
+ // Perform atomic 'exchange pointers' operation. Pointer is set
+ // to the 'val' value. Old value is returned.
+ inline T *xchg (T *val_)
+ {
+#if defined ZMQ_ATOMIC_PTR_WINDOWS
+ return (T*) InterlockedExchangePointer ((PVOID*) &ptr, val_);
+#elif defined ZMQ_ATOMIC_PTR_ATOMIC_H
+ return (T*) atomic_swap_ptr (&ptr, val_);
+#elif defined ZMQ_ATOMIC_PTR_X86
+ T *old;
+ __asm__ volatile (
+ "lock; xchg %0, %2"
+ : "=r" (old), "=m" (ptr)
+ : "m" (ptr), "0" (val_));
+ return old;
+#elif defined ZMQ_ATOMIC_PTR_MUTEX
+ sync.lock ();
+ T *old = (T*) ptr;
+ ptr = val_;
+ sync.unlock ();
+ return old;
+#else
+#error atomic_ptr is not implemented for this platform
+#endif
+ }
+
+ // Perform atomic 'compare and swap' operation on the pointer.
+ // The pointer is compared to 'cmp' argument and if they are
+ // equal, its value is set to 'val'. Old value of the pointer
+ // is returned.
+ inline T *cas (T *cmp_, T *val_)
+ {
+#if defined ZMQ_ATOMIC_PTR_WINDOWS
+ return (T*) InterlockedCompareExchangePointer (
+ (volatile PVOID*) &ptr, val_, cmp_);
+#elif defined ZMQ_ATOMIC_PTR_ATOMIC_H
+ return (T*) atomic_cas_ptr (&ptr, cmp_, val_);
+#elif defined ZMQ_ATOMIC_PTR_X86
+ T *old;
+ __asm__ volatile (
+ "lock; cmpxchg %2, %3"
+ : "=a" (old), "=m" (ptr)
+ : "r" (val_), "m" (ptr), "0" (cmp_)
+ : "cc");
+ return old;
+#elif defined ZMQ_ATOMIC_PTR_MUTEX
+ sync.lock ();
+ T *old = (T*) ptr;
+ if (ptr == cmp_)
+ ptr = val_;
+ sync.unlock ();
+ return old;
+#else
+#error atomic_ptr is not implemented for this platform
+#endif
+ }
+
+ private:
+
+ volatile T *ptr;
+#if defined ZMQ_ATOMIC_PTR_MUTEX
+ mutex_t sync;
+#endif
+
+ atomic_ptr_t (const atomic_ptr_t&);
+ const atomic_ptr_t &operator = (const atomic_ptr_t&);
+ };
+
+}
+
+// Remove macros local to this file.
+#if defined ZMQ_ATOMIC_PTR_WINDOWS
+#undef ZMQ_ATOMIC_PTR_WINDOWS
+#endif
+#if defined ZMQ_ATOMIC_PTR_ATOMIC_H
+#undef ZMQ_ATOMIC_PTR_ATOMIC_H
+#endif
+#if defined ZMQ_ATOMIC_PTR_X86
+#undef ZMQ_ATOMIC_PTR_X86
+#endif
+#if defined ZMQ_ATOMIC_PTR_MUTEX
+#undef ZMQ_ATOMIC_PTR_MUTEX
+#endif
+
+#endif
+
diff --git a/src/0mq/blob.hpp b/src/0mq/blob.hpp
new file mode 100644
index 0000000..3c54ac3
--- /dev/null
+++ b/src/0mq/blob.hpp
@@ -0,0 +1,34 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_BLOB_HPP_INCLUDED__
+#define __ZMQ_BLOB_HPP_INCLUDED__
+
+#include <string>
+
+namespace zmq
+{
+
+ // Object to hold dynamically allocated opaque binary data.
+ typedef std::basic_string <unsigned char> blob_t;
+
+}
+
+#endif
diff --git a/src/0mq/clock.cpp b/src/0mq/clock.cpp
new file mode 100644
index 0000000..f1da091
--- /dev/null
+++ b/src/0mq/clock.cpp
@@ -0,0 +1,130 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "clock.hpp"
+#include "platform.hpp"
+#include "likely.hpp"
+#include "config.hpp"
+#include "err.hpp"
+
+#include <stddef.h>
+
+#if defined _MSC_VER
+#include <intrin.h>
+#endif
+
+#if !defined ZMQ_HAVE_WINDOWS
+#include <sys/time.h>
+#endif
+
+#if defined HAVE_CLOCK_GETTIME
+#include <time.h>
+#endif
+
+zmq::clock_t::clock_t () :
+ last_tsc (rdtsc ()),
+ last_time (now_us () / 1000)
+{
+}
+
+zmq::clock_t::~clock_t ()
+{
+}
+
+uint64_t zmq::clock_t::now_us ()
+{
+#if defined ZMQ_HAVE_WINDOWS
+
+ // Get the high resolution counter's accuracy.
+ LARGE_INTEGER ticksPerSecond;
+ QueryPerformanceFrequency (&ticksPerSecond);
+
+ // What time is it?
+ LARGE_INTEGER tick;
+ QueryPerformanceCounter (&tick);
+
+ // Convert the tick number into the number of seconds
+ // since the system was started.
+ double ticks_div = (double) (ticksPerSecond.QuadPart / 1000000);
+ return (uint64_t) (tick.QuadPart / ticks_div);
+
+#elif defined HAVE_CLOCK_GETTIME
+
+ // Use POSIX clock_gettime function to get precise monotonic time.
+ struct timespec tv;
+ int rc = clock_gettime (CLOCK_MONOTONIC, &tv);
+ errno_assert (rc == 0);
+ return (tv.tv_sec * (uint64_t) 1000000 + tv.tv_nsec / 1000);
+
+#else
+
+ // Use POSIX gettimeofday function to get precise time.
+ struct timeval tv;
+ int rc = gettimeofday (&tv, NULL);
+ errno_assert (rc == 0);
+ return (tv.tv_sec * (uint64_t) 1000000 + tv.tv_usec);
+
+#endif
+}
+
+uint64_t zmq::clock_t::now_ms ()
+{
+ uint64_t tsc = rdtsc ();
+
+ // If TSC is not supported, get precise time and chop off the microseconds.
+ if (!tsc)
+ return now_us () / 1000;
+
+ // If TSC haven't jumped back (in case of migration to a different
+ // CPU core) and if not too much time elapsed since last measurement,
+ // we can return cached time value.
+ if (likely (tsc - last_tsc <= (clock_precision / 2) && tsc >= last_tsc))
+ return last_time;
+
+ last_tsc = tsc;
+ last_time = now_us () / 1000;
+ return last_time;
+}
+
+uint64_t zmq::clock_t::rdtsc ()
+{
+#if (defined _MSC_VER && (defined _M_IX86 || defined _M_X64))
+ return __rdtsc ();
+#elif (defined __GNUC__ && (defined __i386__ || defined __x86_64__))
+ uint32_t low, high;
+ __asm__ volatile ("rdtsc" : "=a" (low), "=d" (high));
+ return (uint64_t) high << 32 | low;
+#elif (defined __SUNPRO_CC && (__SUNPRO_CC >= 0x5100) && (defined __i386 || \
+ defined __amd64 || defined __x86_64))
+ union {
+ uint64_t u64val;
+ uint32_t u32val [2];
+ } tsc;
+ asm("rdtsc" : "=a" (tsc.u32val [0]), "=d" (tsc.u32val [1]));
+ return tsc.u64val;
+#elif defined(__s390__)
+ uint64_t tsc;
+ asm("\tstck\t%0\n" : "=Q" (tsc) : : "cc");
+ tsc >>= 12; /* convert to microseconds just to be consistent */
+ return(tsc);
+#else
+ return 0;
+#endif
+}
diff --git a/src/0mq/clock.hpp b/src/0mq/clock.hpp
new file mode 100644
index 0000000..1b34989
--- /dev/null
+++ b/src/0mq/clock.hpp
@@ -0,0 +1,60 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_CLOCK_HPP_INCLUDED__
+#define __ZMQ_CLOCK_HPP_INCLUDED__
+
+#include "stdint.hpp"
+
+namespace zmq
+{
+
+ class clock_t
+ {
+ public:
+
+ clock_t ();
+ ~clock_t ();
+
+ // CPU's timestamp counter. Returns 0 if it's not available.
+ static uint64_t rdtsc ();
+
+ // High precision timestamp.
+ static uint64_t now_us ();
+
+ // Low precision timestamp. In tight loops generating it can be
+ // 10 to 100 times faster than the high precision timestamp.
+ uint64_t now_ms ();
+
+ private:
+
+ // TSC timestamp of when last time measurement was made.
+ uint64_t last_tsc;
+
+ // Physical time corresponding to the TSC above (in milliseconds).
+ uint64_t last_time;
+
+ clock_t (const clock_t&);
+ const clock_t &operator = (const clock_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/command.cpp b/src/0mq/command.cpp
new file mode 100644
index 0000000..e3f3d59
--- /dev/null
+++ b/src/0mq/command.cpp
@@ -0,0 +1,39 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdlib.h>
+
+#include "command.hpp"
+
+void zmq::deallocate_command (command_t *cmd_)
+{
+ switch (cmd_->type) {
+ case command_t::attach:
+ if (cmd_->args.attach.peer_identity)
+ free (cmd_->args.attach.peer_identity);
+ break;
+ case command_t::bind:
+ if (cmd_->args.bind.peer_identity)
+ free (cmd_->args.bind.peer_identity);
+ break;
+ default:
+ /* noop */;
+ }
+}
diff --git a/src/0mq/command.hpp b/src/0mq/command.hpp
new file mode 100644
index 0000000..35aed0f
--- /dev/null
+++ b/src/0mq/command.hpp
@@ -0,0 +1,147 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_COMMAND_HPP_INCLUDED__
+#define __ZMQ_COMMAND_HPP_INCLUDED__
+
+#include "stdint.hpp"
+
+namespace zmq
+{
+
+ // This structure defines the commands that can be sent between threads.
+
+ struct command_t
+ {
+ // Object to process the command.
+ class object_t *destination;
+
+ enum type_t
+ {
+ stop,
+ plug,
+ own,
+ attach,
+ bind,
+ activate_reader,
+ activate_writer,
+ pipe_term,
+ pipe_term_ack,
+ term_req,
+ term,
+ term_ack,
+ reap,
+ reaped,
+ done
+ } type;
+
+ union {
+
+ // Sent to I/O thread to let it know that it should
+ // terminate itself.
+ struct {
+ } stop;
+
+ // Sent to I/O object to make it register with its I/O thread.
+ struct {
+ } plug;
+
+ // Sent to socket to let it know about the newly created object.
+ struct {
+ class own_t *object;
+ } own;
+
+ // Attach the engine to the session. If engine is NULL, it informs
+ // session that the connection have failed.
+ struct {
+ struct i_engine *engine;
+ unsigned char peer_identity_size;
+ unsigned char *peer_identity;
+ } attach;
+
+ // Sent from session to socket to establish pipe(s) between them.
+ // Caller have used inc_seqnum beforehand sending the command.
+ struct {
+ class reader_t *in_pipe;
+ class writer_t *out_pipe;
+ unsigned char peer_identity_size;
+ unsigned char *peer_identity;
+ } bind;
+
+ // Sent by pipe writer to inform dormant pipe reader that there
+ // are messages in the pipe.
+ struct {
+ } activate_reader;
+
+ // Sent by pipe reader to inform pipe writer about how many
+ // messages it has read so far.
+ struct {
+ uint64_t msgs_read;
+ } activate_writer;
+
+ // Sent by pipe reader to pipe writer to ask it to terminate
+ // its end of the pipe.
+ struct {
+ } pipe_term;
+
+ // Pipe writer acknowledges pipe_term command.
+ struct {
+ } pipe_term_ack;
+
+ // Sent by I/O object ot the socket to request the shutdown of
+ // the I/O object.
+ struct {
+ class own_t *object;
+ } term_req;
+
+ // Sent by socket to I/O object to start its shutdown.
+ struct {
+ int linger;
+ } term;
+
+ // Sent by I/O object to the socket to acknowledge it has
+ // shut down.
+ struct {
+ } term_ack;
+
+ // Transfers the ownership of the closed socket
+ // to the reaper thread.
+ struct {
+ class socket_base_t *socket;
+ } reap;
+
+ // Closed socket notifies the reaper that it's already deallocated.
+ struct {
+ } reaped;
+
+ // Sent by reaper thread to the term thread when all the sockets
+ // are successfully deallocated.
+ struct {
+ } done;
+
+ } args;
+ };
+
+ // Function to deallocate dynamically allocated components of the command.
+ void deallocate_command (command_t *cmd_);
+
+}
+
+#endif
diff --git a/src/0mq/config.hpp b/src/0mq/config.hpp
new file mode 100644
index 0000000..db79284
--- /dev/null
+++ b/src/0mq/config.hpp
@@ -0,0 +1,95 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_CONFIG_HPP_INCLUDED__
+#define __ZMQ_CONFIG_HPP_INCLUDED__
+
+namespace zmq
+{
+
+ // Compile-time settings.
+
+ enum
+ {
+ // Maximum number of sockets that can be opened at the same time.
+ max_sockets = 512,
+
+ // Number of new messages in message pipe needed to trigger new memory
+ // allocation. Setting this parameter to 256 decreases the impact of
+ // memory allocation by approximately 99.6%
+ message_pipe_granularity = 256,
+
+ // Commands in pipe per allocation event.
+ command_pipe_granularity = 16,
+
+ // Size in bytes of the largest message that is still copied around
+ // rather than being reference-counted.
+ max_vsm_size = 29,
+
+ // Determines how often does socket poll for new commands when it
+ // still has unprocessed messages to handle. Thus, if it is set to 100,
+ // socket will process 100 inbound messages before doing the poll.
+ // If there are no unprocessed messages available, poll is done
+ // immediately. Decreasing the value trades overall latency for more
+ // real-time behaviour (less latency peaks).
+ inbound_poll_rate = 100,
+
+ // Maximal batching size for engines with receiving functionality.
+ // So, if there are 10 messages that fit into the batch size, all of
+ // them may be read by a single 'recv' system call, thus avoiding
+ // unnecessary network stack traversals.
+ in_batch_size = 8192,
+
+ // Maximal batching size for engines with sending functionality.
+ // So, if there are 10 messages that fit into the batch size, all of
+ // them may be written by a single 'send' system call, thus avoiding
+ // unnecessary network stack traversals.
+ out_batch_size = 8192,
+
+ // Maximal delta between high and low watermark.
+ max_wm_delta = 1024,
+
+ // Swap inteligently batches data for writing to disk. The size of
+ // the batch in bytes is specified by this option.
+ swap_block_size = 8192,
+
+ // Maximum number of events the I/O thread can process in one go.
+ max_io_events = 256,
+
+ // Maximal delay to process command in API thread (in CPU ticks).
+ // 3,000,000 ticks equals to 1 - 2 milliseconds on current CPUs.
+ // Note that delay is only applied when there is continuous stream of
+ // messages to process. If not so, commands are processed immediately.
+ max_command_delay = 3000000,
+
+ // Low-precision clock precision in CPU ticks. 1ms. Value of 1000000
+ // should be OK for CPU frequencies above 1GHz. If should work
+ // reasonably well for CPU frequencies above 500MHz. For lower CPU
+ // frequencies you may consider lowering this value to get best
+ // possible latencies.
+ clock_precision = 1000000,
+
+ // Maximum transport data unit size for PGM (TPDU).
+ pgm_max_tpdu = 1500
+ };
+
+}
+
+#endif
diff --git a/src/0mq/connect_session.cpp b/src/0mq/connect_session.cpp
new file mode 100644
index 0000000..0df9854
--- /dev/null
+++ b/src/0mq/connect_session.cpp
@@ -0,0 +1,119 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "connect_session.hpp"
+#include "zmq_connecter.hpp"
+#include "pgm_sender.hpp"
+#include "pgm_receiver.hpp"
+
+zmq::connect_session_t::connect_session_t (class io_thread_t *io_thread_,
+ class socket_base_t *socket_, const options_t &options_,
+ const char *protocol_, const char *address_) :
+ session_t (io_thread_, socket_, options_),
+ protocol (protocol_),
+ address (address_)
+{
+}
+
+zmq::connect_session_t::~connect_session_t ()
+{
+}
+
+void zmq::connect_session_t::process_plug ()
+{
+ // Start connection process immediately.
+ start_connecting (false);
+}
+
+void zmq::connect_session_t::start_connecting (bool wait_)
+{
+ // Choose I/O thread to run connecter in. Given that we are already
+ // running in an I/O thread, there must be at least one available.
+ io_thread_t *io_thread = choose_io_thread (options.affinity);
+ zmq_assert (io_thread);
+
+ // Create the connecter object.
+
+ // Both TCP and IPC transports are using the same infrastructure.
+ if (protocol == "tcp" || protocol == "ipc") {
+
+ zmq_connecter_t *connecter = new (std::nothrow) zmq_connecter_t (
+ io_thread, this, options, protocol.c_str (), address.c_str (),
+ wait_);
+ alloc_assert (connecter);
+ launch_child (connecter);
+ return;
+ }
+
+#if defined ZMQ_HAVE_OPENPGM
+
+ // Both PGM and EPGM transports are using the same infrastructure.
+ if (protocol == "pgm" || protocol == "epgm") {
+
+ // For EPGM transport with UDP encapsulation of PGM is used.
+ bool udp_encapsulation = (protocol == "epgm");
+
+ // At this point we'll create message pipes to the session straight
+ // away. There's no point in delaying it as no concept of 'connect'
+ // exists with PGM anyway.
+ if (options.type == ZMQ_PUB || options.type == ZMQ_XPUB) {
+
+ // PGM sender.
+ pgm_sender_t *pgm_sender = new (std::nothrow) pgm_sender_t (
+ io_thread, options);
+ alloc_assert (pgm_sender);
+
+ int rc = pgm_sender->init (udp_encapsulation, address.c_str ());
+ zmq_assert (rc == 0);
+
+ send_attach (this, pgm_sender, blob_t ());
+ }
+ else if (options.type == ZMQ_SUB || options.type == ZMQ_XSUB) {
+
+ // PGM receiver.
+ pgm_receiver_t *pgm_receiver = new (std::nothrow) pgm_receiver_t (
+ io_thread, options);
+ alloc_assert (pgm_receiver);
+
+ int rc = pgm_receiver->init (udp_encapsulation, address.c_str ());
+ zmq_assert (rc == 0);
+
+ send_attach (this, pgm_receiver, blob_t ());
+ }
+ else
+ zmq_assert (false);
+
+ return;
+ }
+#endif
+
+ zmq_assert (false);
+}
+
+void zmq::connect_session_t::attached (const blob_t &peer_identity_)
+{
+}
+
+void zmq::connect_session_t::detached ()
+{
+ // Reconnect.
+ start_connecting (true);
+}
+
diff --git a/src/0mq/connect_session.hpp b/src/0mq/connect_session.hpp
new file mode 100644
index 0000000..327ad2d
--- /dev/null
+++ b/src/0mq/connect_session.hpp
@@ -0,0 +1,65 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_CONNECT_SESSION_HPP_INCLUDED__
+#define __ZMQ_CONNECT_SESSION_HPP_INCLUDED__
+
+#include <string>
+
+#include "session.hpp"
+
+namespace zmq
+{
+
+ // Connect session contains an address to connect to. On disconnect it
+ // attempts to reconnect.
+
+ class connect_session_t : public session_t
+ {
+ public:
+
+ connect_session_t (class io_thread_t *io_thread_,
+ class socket_base_t *socket_, const options_t &options_,
+ const char *protocol_, const char *address_);
+ ~connect_session_t ();
+
+ private:
+
+ // Handlers for events from session base class.
+ void attached (const blob_t &peer_identity_);
+ void detached ();
+
+ // Start the connection process.
+ void start_connecting (bool wait_);
+
+ // Command handlers.
+ void process_plug ();
+
+ // Address to connect to.
+ std::string protocol;
+ std::string address;
+
+ connect_session_t (const connect_session_t&);
+ const connect_session_t &operator = (const connect_session_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/ctx.cpp b/src/0mq/ctx.cpp
new file mode 100644
index 0000000..9612cd1
--- /dev/null
+++ b/src/0mq/ctx.cpp
@@ -0,0 +1,324 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+#if defined ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+#include <new>
+#include <string.h>
+
+#include "ctx.hpp"
+#include "socket_base.hpp"
+#include "io_thread.hpp"
+#include "reaper.hpp"
+#include "err.hpp"
+#include "pipe.hpp"
+
+#if !defined ZMQ_HAVE_WINDOWS
+#include <unistd.h>
+#endif
+
+zmq::ctx_t::ctx_t (uint32_t io_threads_) :
+ tag (0xbadcafe0),
+ terminating (false)
+{
+ int rc;
+
+ // Initialise the array of mailboxes. Additional three slots are for
+ // internal log socket and the zmq_term thread the reaper thread.
+ slot_count = max_sockets + io_threads_ + 3;
+ slots = (mailbox_t**) malloc (sizeof (mailbox_t*) * slot_count);
+ alloc_assert (slots);
+
+ // Initialise the infrastructure for zmq_term thread.
+ slots [term_tid] = &term_mailbox;
+
+ // Create the reaper thread.
+ reaper = new (std::nothrow) reaper_t (this, reaper_tid);
+ alloc_assert (reaper);
+ slots [reaper_tid] = reaper->get_mailbox ();
+ reaper->start ();
+
+ // Create I/O thread objects and launch them.
+ for (uint32_t i = 2; i != io_threads_ + 2; i++) {
+ io_thread_t *io_thread = new (std::nothrow) io_thread_t (this, i);
+ alloc_assert (io_thread);
+ io_threads.push_back (io_thread);
+ slots [i] = io_thread->get_mailbox ();
+ io_thread->start ();
+ }
+
+ // In the unused part of the slot array, create a list of empty slots.
+ for (int32_t i = (int32_t) slot_count - 1;
+ i >= (int32_t) io_threads_ + 2; i--) {
+ empty_slots.push_back (i);
+ slots [i] = NULL;
+ }
+
+ // Create the logging infrastructure.
+ log_socket = create_socket (ZMQ_PUB);
+ zmq_assert (log_socket);
+ rc = log_socket->bind ("sys://log");
+ zmq_assert (rc == 0);
+}
+
+bool zmq::ctx_t::check_tag ()
+{
+ return tag == 0xbadcafe0;
+}
+
+zmq::ctx_t::~ctx_t ()
+{
+ // Check that there are no remaining sockets.
+ zmq_assert (sockets.empty ());
+
+ // Ask I/O threads to terminate. If stop signal wasn't sent to I/O
+ // thread subsequent invocation of destructor would hang-up.
+ for (io_threads_t::size_type i = 0; i != io_threads.size (); i++)
+ io_threads [i]->stop ();
+
+ // Wait till I/O threads actually terminate.
+ for (io_threads_t::size_type i = 0; i != io_threads.size (); i++)
+ delete io_threads [i];
+
+ // Deallocate the reaper thread object.
+ delete reaper;
+
+ // Deallocate the array of mailboxes. No special work is
+ // needed as mailboxes themselves were deallocated with their
+ // corresponding io_thread/socket objects.
+ free (slots);
+
+ // Remove the tag, so that the object is considered dead.
+ tag = 0xdeadbeef;
+}
+
+int zmq::ctx_t::terminate ()
+{
+ // Check whether termination was already underway, but interrupted and now
+ // restarted.
+ slot_sync.lock ();
+ bool restarted = terminating;
+ slot_sync.unlock ();
+
+ // First attempt to terminate the context.
+ if (!restarted) {
+
+ // Close the logging infrastructure.
+ log_sync.lock ();
+ int rc = log_socket->close ();
+ zmq_assert (rc == 0);
+ log_socket = NULL;
+ log_sync.unlock ();
+
+ // First send stop command to sockets so that any blocking calls can be
+ // interrupted. If there are no sockets we can ask reaper thread to stop.
+ slot_sync.lock ();
+ terminating = true;
+ for (sockets_t::size_type i = 0; i != sockets.size (); i++)
+ sockets [i]->stop ();
+ if (sockets.empty ())
+ reaper->stop ();
+ slot_sync.unlock ();
+ }
+
+ // Wait till reaper thread closes all the sockets.
+ command_t cmd;
+ int rc = term_mailbox.recv (&cmd, -1);
+ if (rc == -1 && errno == EINTR)
+ return -1;
+ zmq_assert (rc == 0);
+ zmq_assert (cmd.type == command_t::done);
+ slot_sync.lock ();
+ zmq_assert (sockets.empty ());
+ slot_sync.unlock ();
+
+ // Deallocate the resources.
+ delete this;
+
+ return 0;
+}
+
+zmq::socket_base_t *zmq::ctx_t::create_socket (int type_)
+{
+ slot_sync.lock ();
+
+ // Once zmq_term() was called, we can't create new sockets.
+ if (terminating) {
+ slot_sync.unlock ();
+ errno = ETERM;
+ return NULL;
+ }
+
+ // If max_sockets limit was reached, return error.
+ if (empty_slots.empty ()) {
+ slot_sync.unlock ();
+ errno = EMFILE;
+ return NULL;
+ }
+
+ // Choose a slot for the socket.
+ uint32_t slot = empty_slots.back ();
+ empty_slots.pop_back ();
+
+ // Create the socket and register its mailbox.
+ socket_base_t *s = socket_base_t::create (type_, this, slot);
+ if (!s) {
+ empty_slots.push_back (slot);
+ slot_sync.unlock ();
+ return NULL;
+ }
+ sockets.push_back (s);
+ slots [slot] = s->get_mailbox ();
+
+ slot_sync.unlock ();
+
+ return s;
+}
+
+void zmq::ctx_t::destroy_socket (class socket_base_t *socket_)
+{
+ slot_sync.lock ();
+
+ // Free the associared thread slot.
+ uint32_t tid = socket_->get_tid ();
+ empty_slots.push_back (tid);
+ slots [tid] = NULL;
+
+ // Remove the socket from the list of sockets.
+ sockets.erase (socket_);
+
+ // If zmq_term() was already called and there are no more socket
+ // we can ask reaper thread to terminate.
+ if (terminating && sockets.empty ())
+ reaper->stop ();
+
+ slot_sync.unlock ();
+}
+
+zmq::object_t *zmq::ctx_t::get_reaper ()
+{
+ return reaper;
+}
+
+void zmq::ctx_t::send_command (uint32_t tid_, const command_t &command_)
+{
+ slots [tid_]->send (command_);
+}
+
+zmq::io_thread_t *zmq::ctx_t::choose_io_thread (uint64_t affinity_)
+{
+ if (io_threads.empty ())
+ return NULL;
+
+ // Find the I/O thread with minimum load.
+ int min_load = -1;
+ io_threads_t::size_type result = 0;
+ for (io_threads_t::size_type i = 0; i != io_threads.size (); i++) {
+ if (!affinity_ || (affinity_ & (uint64_t (1) << i))) {
+ int load = io_threads [i]->get_load ();
+ if (min_load == -1 || load < min_load) {
+ min_load = load;
+ result = i;
+ }
+ }
+ }
+ zmq_assert (min_load != -1);
+ return io_threads [result];
+}
+
+int zmq::ctx_t::register_endpoint (const char *addr_, endpoint_t &endpoint_)
+{
+ endpoints_sync.lock ();
+
+ bool inserted = endpoints.insert (endpoints_t::value_type (
+ std::string (addr_), endpoint_)).second;
+ if (!inserted) {
+ errno = EADDRINUSE;
+ endpoints_sync.unlock ();
+ return -1;
+ }
+
+ endpoints_sync.unlock ();
+ return 0;
+}
+
+void zmq::ctx_t::unregister_endpoints (socket_base_t *socket_)
+{
+ endpoints_sync.lock ();
+
+ endpoints_t::iterator it = endpoints.begin ();
+ while (it != endpoints.end ()) {
+ if (it->second.socket == socket_) {
+ endpoints_t::iterator to_erase = it;
+ ++it;
+ endpoints.erase (to_erase);
+ continue;
+ }
+ ++it;
+ }
+
+ endpoints_sync.unlock ();
+}
+
+zmq::endpoint_t zmq::ctx_t::find_endpoint (const char *addr_)
+{
+ endpoints_sync.lock ();
+
+ endpoints_t::iterator it = endpoints.find (addr_);
+ if (it == endpoints.end ()) {
+ endpoints_sync.unlock ();
+ errno = ECONNREFUSED;
+ endpoint_t empty = {NULL, options_t()};
+ return empty;
+ }
+ endpoint_t *endpoint = &it->second;
+
+ // Increment the command sequence number of the peer so that it won't
+ // get deallocated until "bind" command is issued by the caller.
+ // The subsequent 'bind' has to be called with inc_seqnum parameter
+ // set to false, so that the seqnum isn't incremented twice.
+ endpoint->socket->inc_seqnum ();
+
+ endpoints_sync.unlock ();
+ return *endpoint;
+}
+
+void zmq::ctx_t::log (const char *format_, va_list args_)
+{
+ // Create the log message.
+ zmq_msg_t msg;
+ int rc = zmq_msg_init_size (&msg, strlen (format_) + 1);
+ zmq_assert (rc == 0);
+ memcpy (zmq_msg_data (&msg), format_, zmq_msg_size (&msg));
+
+ // At this point we migrate the log socket to the current thread.
+ // We rely on mutex for executing the memory barrier.
+ log_sync.lock ();
+ if (log_socket)
+ log_socket->send (&msg, 0);
+ log_sync.unlock ();
+
+ zmq_msg_close (&msg);
+}
+
+
diff --git a/src/0mq/ctx.hpp b/src/0mq/ctx.hpp
new file mode 100644
index 0000000..33d5dad
--- /dev/null
+++ b/src/0mq/ctx.hpp
@@ -0,0 +1,159 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_CTX_HPP_INCLUDED__
+#define __ZMQ_CTX_HPP_INCLUDED__
+
+#include <map>
+#include <vector>
+#include <string>
+#include <stdarg.h>
+
+#include "../include/zmq.h"
+
+#include "mailbox.hpp"
+#include "semaphore.hpp"
+#include "ypipe.hpp"
+#include "array.hpp"
+#include "config.hpp"
+#include "mutex.hpp"
+#include "stdint.hpp"
+#include "thread.hpp"
+#include "options.hpp"
+
+namespace zmq
+{
+ // Information associated with inproc endpoint. Note that endpoint options
+ // are registered as well so that the peer can access them without a need
+ // for synchronisation, handshaking or similar.
+ struct endpoint_t
+ {
+ class socket_base_t *socket;
+ options_t options;
+ };
+
+ // Context object encapsulates all the global state associated with
+ // the library.
+
+ class ctx_t
+ {
+ public:
+
+ // Create the context object. The argument specifies the size
+ // of I/O thread pool to create.
+ ctx_t (uint32_t io_threads_);
+
+ // Returns false if object is not a context.
+ bool check_tag ();
+
+ // This function is called when user invokes zmq_term. If there are
+ // no more sockets open it'll cause all the infrastructure to be shut
+ // down. If there are open sockets still, the deallocation happens
+ // after the last one is closed.
+ int terminate ();
+
+ // Create and destroy a socket.
+ class socket_base_t *create_socket (int type_);
+ void destroy_socket (class socket_base_t *socket_);
+
+ // Send command to the destination thread.
+ void send_command (uint32_t tid_, const command_t &command_);
+
+ // Returns the I/O thread that is the least busy at the moment.
+ // Affinity specifies which I/O threads are eligible (0 = all).
+ // Returns NULL is no I/O thread is available.
+ class io_thread_t *choose_io_thread (uint64_t affinity_);
+
+ // Returns reaper thread object.
+ class object_t *get_reaper ();
+
+ // Management of inproc endpoints.
+ int register_endpoint (const char *addr_, endpoint_t &endpoint_);
+ void unregister_endpoints (class socket_base_t *socket_);
+ endpoint_t find_endpoint (const char *addr_);
+
+ // Logging.
+ void log (const char *format_, va_list args_);
+
+ enum {
+ term_tid = 0,
+ reaper_tid = 1
+ };
+
+ private:
+
+ ~ctx_t ();
+
+ // Used to check whether the object is a context.
+ uint32_t tag;
+
+ // Sockets belonging to this context. We need the list so that
+ // we can notify the sockets when zmq_term() is called. The sockets
+ // will return ETERM then.
+ typedef array_t <socket_base_t> sockets_t;
+ sockets_t sockets;
+
+ // List of unused thread slots.
+ typedef std::vector <uint32_t> emtpy_slots_t;
+ emtpy_slots_t empty_slots;
+
+ // If true, zmq_term was already called.
+ bool terminating;
+
+ // Synchronisation of accesses to global slot-related data:
+ // sockets, empty_slots, terminating. It also synchronises
+ // access to zombie sockets as such (as oposed to slots) and provides
+ // a memory barrier to ensure that all CPU cores see the same data.
+ mutex_t slot_sync;
+
+ // The reaper thread.
+ class reaper_t *reaper;
+
+ // I/O threads.
+ typedef std::vector <class io_thread_t*> io_threads_t;
+ io_threads_t io_threads;
+
+ // Array of pointers to mailboxes for both application and I/O threads.
+ uint32_t slot_count;
+ mailbox_t **slots;
+
+ // Mailbox for zmq_term thread.
+ mailbox_t term_mailbox;
+
+ // List of inproc endpoints within this context.
+ typedef std::map <std::string, endpoint_t> endpoints_t;
+ endpoints_t endpoints;
+
+ // Synchronisation of access to the list of inproc endpoints.
+ mutex_t endpoints_sync;
+
+ // PUB socket for logging. The socket is shared among all the threads,
+ // thus it is synchronised by a mutex.
+ class socket_base_t *log_socket;
+ mutex_t log_sync;
+
+ ctx_t (const ctx_t&);
+ const ctx_t &operator = (const ctx_t&);
+ };
+
+}
+
+#endif
+
diff --git a/src/0mq/decoder.cpp b/src/0mq/decoder.cpp
new file mode 100644
index 0000000..84ecd92
--- /dev/null
+++ b/src/0mq/decoder.cpp
@@ -0,0 +1,129 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "decoder.hpp"
+#include "i_inout.hpp"
+#include "wire.hpp"
+#include "err.hpp"
+
+zmq::decoder_t::decoder_t (size_t bufsize_) :
+ decoder_base_t <decoder_t> (bufsize_),
+ destination (NULL)
+{
+ zmq_msg_init (&in_progress);
+
+ // At the beginning, read one byte and go to one_byte_size_ready state.
+ next_step (tmpbuf, 1, &decoder_t::one_byte_size_ready);
+}
+
+zmq::decoder_t::~decoder_t ()
+{
+ zmq_msg_close (&in_progress);
+}
+
+void zmq::decoder_t::set_inout (i_inout *destination_)
+{
+ destination = destination_;
+}
+
+bool zmq::decoder_t::one_byte_size_ready ()
+{
+ // First byte of size is read. If it is 0xff read 8-byte size.
+ // Otherwise allocate the buffer for message data and read the
+ // message data into it.
+ if (*tmpbuf == 0xff)
+ next_step (tmpbuf, 8, &decoder_t::eight_byte_size_ready);
+ else {
+
+ // There has to be at least one byte (the flags) in the message).
+ if (!*tmpbuf) {
+ decoding_error ();
+ return false;
+ }
+
+ // in_progress is initialised at this point so in theory we should
+ // close it before calling zmq_msg_init_size, however, it's a 0-byte
+ // message and thus we can treat it as uninitialised...
+ int rc = zmq_msg_init_size (&in_progress, *tmpbuf - 1);
+ if (rc != 0 && errno == ENOMEM) {
+ rc = zmq_msg_init (&in_progress);
+ errno_assert (rc == 0);
+ decoding_error ();
+ return false;
+ }
+ errno_assert (rc == 0);
+
+ next_step (tmpbuf, 1, &decoder_t::flags_ready);
+ }
+ return true;
+}
+
+bool zmq::decoder_t::eight_byte_size_ready ()
+{
+ // 8-byte size is read. Allocate the buffer for message body and
+ // read the message data into it.
+ size_t size = (size_t) get_uint64 (tmpbuf);
+
+ // There has to be at least one byte (the flags) in the message).
+ if (!size) {
+ decoding_error ();
+ return false;
+ }
+
+ // in_progress is initialised at this point so in theory we should
+ // close it before calling zmq_msg_init_size, however, it's a 0-byte
+ // message and thus we can treat it as uninitialised...
+ int rc = zmq_msg_init_size (&in_progress, size - 1);
+ if (rc != 0 && errno == ENOMEM) {
+ rc = zmq_msg_init (&in_progress);
+ errno_assert (rc == 0);
+ decoding_error ();
+ return false;
+ }
+ errno_assert (rc == 0);
+
+ next_step (tmpbuf, 1, &decoder_t::flags_ready);
+ return true;
+}
+
+bool zmq::decoder_t::flags_ready ()
+{
+ // Store the flags from the wire into the message structure.
+ in_progress.flags = tmpbuf [0] | ~ZMQ_MSG_MASK;
+
+ next_step (zmq_msg_data (&in_progress), zmq_msg_size (&in_progress),
+ &decoder_t::message_ready);
+
+ return true;
+}
+
+bool zmq::decoder_t::message_ready ()
+{
+ // Message is completely read. Push it further and start reading
+ // new message. (in_progress is a 0-byte message after this point.)
+ if (!destination || !destination->write (&in_progress))
+ return false;
+
+ next_step (tmpbuf, 1, &decoder_t::one_byte_size_ready);
+ return true;
+}
diff --git a/src/0mq/decoder.hpp b/src/0mq/decoder.hpp
new file mode 100644
index 0000000..f554e46
--- /dev/null
+++ b/src/0mq/decoder.hpp
@@ -0,0 +1,207 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_DECODER_HPP_INCLUDED__
+#define __ZMQ_DECODER_HPP_INCLUDED__
+
+#include <stddef.h>
+#include <string.h>
+#include <stdlib.h>
+#include <algorithm>
+
+#include "err.hpp"
+
+#include "../include/zmq.h"
+
+namespace zmq
+{
+
+ // Helper base class for decoders that know the amount of data to read
+ // in advance at any moment. Knowing the amount in advance is a property
+ // of the protocol used. 0MQ framing protocol is based size-prefixed
+ // paradigm, whixh qualifies it to be parsed by this class.
+ // On the other hand, XML-based transports (like XMPP or SOAP) don't allow
+ // for knowing the size of data to read in advance and should use different
+ // decoding algorithms.
+ //
+ // This class implements the state machine that parses the incoming buffer.
+ // Derived class should implement individual state machine actions.
+
+ template <typename T> class decoder_base_t
+ {
+ public:
+
+ inline decoder_base_t (size_t bufsize_) :
+ read_pos (NULL),
+ to_read (0),
+ next (NULL),
+ bufsize (bufsize_)
+ {
+ buf = (unsigned char*) malloc (bufsize_);
+ alloc_assert (buf);
+ }
+
+ // The destructor doesn't have to be virtual. It is mad virtual
+ // just to keep ICC and code checking tools from complaining.
+ inline virtual ~decoder_base_t ()
+ {
+ free (buf);
+ }
+
+ // Returns a buffer to be filled with binary data.
+ inline void get_buffer (unsigned char **data_, size_t *size_)
+ {
+ // If we are expected to read large message, we'll opt for zero-
+ // copy, i.e. we'll ask caller to fill the data directly to the
+ // message. Note that subsequent read(s) are non-blocking, thus
+ // each single read reads at most SO_RCVBUF bytes at once not
+ // depending on how large is the chunk returned from here.
+ // As a consequence, large messages being received won't block
+ // other engines running in the same I/O thread for excessive
+ // amounts of time.
+ if (to_read >= bufsize) {
+ *data_ = read_pos;
+ *size_ = to_read;
+ return;
+ }
+
+ *data_ = buf;
+ *size_ = bufsize;
+ }
+
+ // Processes the data in the buffer previously allocated using
+ // get_buffer function. size_ argument specifies nemuber of bytes
+ // actually filled into the buffer. Function returns number of
+ // bytes actually processed.
+ inline size_t process_buffer (unsigned char *data_, size_t size_)
+ {
+ // Check if we had an error in previous attempt.
+ if (unlikely (!(static_cast <T*> (this)->next)))
+ return (size_t) -1;
+
+ // In case of zero-copy simply adjust the pointers, no copying
+ // is required. Also, run the state machine in case all the data
+ // were processed.
+ if (data_ == read_pos) {
+ read_pos += size_;
+ to_read -= size_;
+
+ while (!to_read) {
+ if (!(static_cast <T*> (this)->*next) ()) {
+ if (unlikely (!(static_cast <T*> (this)->next)))
+ return (size_t) -1;
+ return size_;
+ }
+ }
+ return size_;
+ }
+
+ size_t pos = 0;
+ while (true) {
+
+ // Try to get more space in the message to fill in.
+ // If none is available, return.
+ while (!to_read) {
+ if (!(static_cast <T*> (this)->*next) ()) {
+ if (unlikely (!(static_cast <T*> (this)->next)))
+ return (size_t) -1;
+ return pos;
+ }
+ }
+
+ // If there are no more data in the buffer, return.
+ if (pos == size_)
+ return pos;
+
+ // Copy the data from buffer to the message.
+ size_t to_copy = std::min (to_read, size_ - pos);
+ memcpy (read_pos, data_ + pos, to_copy);
+ read_pos += to_copy;
+ pos += to_copy;
+ to_read -= to_copy;
+ }
+ }
+
+ protected:
+
+ // Prototype of state machine action. Action should return false if
+ // it is unable to push the data to the system.
+ typedef bool (T::*step_t) ();
+
+ // This function should be called from derived class to read data
+ // from the buffer and schedule next state machine action.
+ inline void next_step (void *read_pos_, size_t to_read_,
+ step_t next_)
+ {
+ read_pos = (unsigned char*) read_pos_;
+ to_read = to_read_;
+ next = next_;
+ }
+
+ // This function should be called from the derived class to
+ // abort decoder state machine.
+ inline void decoding_error ()
+ {
+ next = NULL;
+ }
+
+ private:
+
+ unsigned char *read_pos;
+ size_t to_read;
+ step_t next;
+
+ size_t bufsize;
+ unsigned char *buf;
+
+ decoder_base_t (const decoder_base_t&);
+ const decoder_base_t &operator = (const decoder_base_t&);
+ };
+
+ // Decoder for 0MQ framing protocol. Converts data batches into messages.
+
+ class decoder_t : public decoder_base_t <decoder_t>
+ {
+ public:
+
+ decoder_t (size_t bufsize_);
+ ~decoder_t ();
+
+ void set_inout (struct i_inout *destination_);
+
+ private:
+
+ bool one_byte_size_ready ();
+ bool eight_byte_size_ready ();
+ bool flags_ready ();
+ bool message_ready ();
+
+ struct i_inout *destination;
+ unsigned char tmpbuf [8];
+ ::zmq_msg_t in_progress;
+
+ decoder_t (const decoder_t&);
+ void operator = (const decoder_t&);
+ };
+
+}
+
+#endif
+
diff --git a/src/0mq/device.cpp b/src/0mq/device.cpp
new file mode 100644
index 0000000..4d86e91
--- /dev/null
+++ b/src/0mq/device.cpp
@@ -0,0 +1,134 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stddef.h>
+
+#include "platform.hpp"
+
+// On AIX, poll.h has to be included before zmq.h to get consistent
+// definition of pollfd structure (AIX uses 'reqevents' and 'retnevents'
+// instead of 'events' and 'revents' and defines macros to map from POSIX-y
+// names to AIX-specific names).
+#if defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
+ defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
+ defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
+ defined ZMQ_HAVE_NETBSD
+#include <poll.h>
+#endif
+
+#include "../include/zmq.h"
+
+#include "device.hpp"
+#include "socket_base.hpp"
+#include "likely.hpp"
+#include "err.hpp"
+
+int zmq::device (class socket_base_t *insocket_,
+ class socket_base_t *outsocket_)
+{
+ zmq_msg_t msg;
+ int rc = zmq_msg_init (&msg);
+
+ if (rc != 0) {
+ return -1;
+ }
+
+ int64_t more;
+ size_t moresz;
+
+ zmq_pollitem_t items [2];
+ items [0].socket = insocket_;
+ items [0].fd = 0;
+ items [0].events = ZMQ_POLLIN;
+ items [0].revents = 0;
+ items [1].socket = outsocket_;
+ items [1].fd = 0;
+ items [1].events = ZMQ_POLLIN;
+ items [1].revents = 0;
+
+ while (true) {
+
+ // Wait while there are either requests or replies to process.
+ rc = zmq_poll (&items [0], 2, -1);
+ if (unlikely (rc < 0)) {
+ return -1;
+ }
+
+ // The algorithm below asumes ratio of request and replies processed
+ // under full load to be 1:1. Although processing requests replies
+ // first is tempting it is suspectible to DoS attacks (overloading
+ // the system with unsolicited replies).
+
+ // Process a request.
+ if (items [0].revents & ZMQ_POLLIN) {
+ while (true) {
+
+ rc = insocket_->recv (&msg, 0);
+ if (unlikely (rc < 0)) {
+ return -1;
+ }
+
+ moresz = sizeof (more);
+ rc = insocket_->getsockopt (ZMQ_RCVMORE, &more, &moresz);
+ if (unlikely (rc < 0)) {
+ return -1;
+ }
+
+ rc = outsocket_->send (&msg, more ? ZMQ_SNDMORE : 0);
+ if (unlikely (rc < 0)) {
+ return -1;
+ }
+
+ if (!more)
+ break;
+ }
+ }
+
+ // Process a reply.
+ if (items [1].revents & ZMQ_POLLIN) {
+ while (true) {
+
+ rc = outsocket_->recv (&msg, 0);
+ if (unlikely (rc < 0)) {
+ return -1;
+ }
+
+ moresz = sizeof (more);
+ rc = outsocket_->getsockopt (ZMQ_RCVMORE, &more, &moresz);
+ if (unlikely (rc < 0)) {
+ return -1;
+ }
+
+ rc = insocket_->send (&msg, more ? ZMQ_SNDMORE : 0);
+ if (unlikely (rc < 0)) {
+ return -1;
+ }
+
+ if (!more)
+ break;
+ }
+ }
+
+ }
+
+ return 0;
+}
+
diff --git a/src/0mq/device.hpp b/src/0mq/device.hpp
new file mode 100644
index 0000000..c5b7118
--- /dev/null
+++ b/src/0mq/device.hpp
@@ -0,0 +1,32 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_DEVICE_HPP_INCLUDED__
+#define __ZMQ_DEVICE_HPP_INCLUDED__
+
+namespace zmq
+{
+
+ int device (class socket_base_t *insocket_,
+ class socket_base_t *outsocket_);
+
+}
+
+#endif
diff --git a/src/0mq/devpoll.cpp b/src/0mq/devpoll.cpp
new file mode 100644
index 0000000..25763c6
--- /dev/null
+++ b/src/0mq/devpoll.cpp
@@ -0,0 +1,190 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_HPUX
+
+#include <sys/devpoll.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <limits.h>
+#include <algorithm>
+
+#include "devpoll.hpp"
+#include "err.hpp"
+#include "config.hpp"
+#include "i_poll_events.hpp"
+
+zmq::devpoll_t::devpoll_t () :
+ stopping (false)
+{
+ devpoll_fd = open ("/dev/poll", O_RDWR);
+ errno_assert (devpoll_fd != -1);
+}
+
+zmq::devpoll_t::~devpoll_t ()
+{
+ worker.stop ();
+ close (devpoll_fd);
+}
+
+void zmq::devpoll_t::devpoll_ctl (fd_t fd_, short events_)
+{
+ struct pollfd pfd = {fd_, events_, 0};
+ ssize_t rc = write (devpoll_fd, &pfd, sizeof pfd);
+ zmq_assert (rc == sizeof pfd);
+}
+
+zmq::devpoll_t::handle_t zmq::devpoll_t::add_fd (fd_t fd_,
+ i_poll_events *reactor_)
+{
+ // If the file descriptor table is too small expand it.
+ fd_table_t::size_type sz = fd_table.size ();
+ if (sz <= (fd_table_t::size_type) fd_) {
+ fd_table.resize (fd_ + 1);
+ while (sz != (fd_table_t::size_type) (fd_ + 1)) {
+ fd_table [sz].valid = false;
+ ++sz;
+ }
+ }
+
+ assert (!fd_table [fd_].valid);
+
+ fd_table [fd_].events = 0;
+ fd_table [fd_].reactor = reactor_;
+ fd_table [fd_].valid = true;
+ fd_table [fd_].accepted = false;
+
+ devpoll_ctl (fd_, 0);
+ pending_list.push_back (fd_);
+
+ // Increase the load metric of the thread.
+ adjust_load (1);
+
+ return fd_;
+}
+
+void zmq::devpoll_t::rm_fd (handle_t handle_)
+{
+ assert (fd_table [handle_].valid);
+
+ devpoll_ctl (handle_, POLLREMOVE);
+ fd_table [handle_].valid = false;
+
+ // Decrease the load metric of the thread.
+ adjust_load (-1);
+}
+
+void zmq::devpoll_t::set_pollin (handle_t handle_)
+{
+ devpoll_ctl (handle_, POLLREMOVE);
+ fd_table [handle_].events |= POLLIN;
+ devpoll_ctl (handle_, fd_table [handle_].events);
+}
+
+void zmq::devpoll_t::reset_pollin (handle_t handle_)
+{
+ devpoll_ctl (handle_, POLLREMOVE);
+ fd_table [handle_].events &= ~((short) POLLIN);
+ devpoll_ctl (handle_, fd_table [handle_].events);
+}
+
+void zmq::devpoll_t::set_pollout (handle_t handle_)
+{
+ devpoll_ctl (handle_, POLLREMOVE);
+ fd_table [handle_].events |= POLLOUT;
+ devpoll_ctl (handle_, fd_table [handle_].events);
+}
+
+void zmq::devpoll_t::reset_pollout (handle_t handle_)
+{
+ devpoll_ctl (handle_, POLLREMOVE);
+ fd_table [handle_].events &= ~((short) POLLOUT);
+ devpoll_ctl (handle_, fd_table [handle_].events);
+}
+
+void zmq::devpoll_t::start ()
+{
+ worker.start (worker_routine, this);
+}
+
+void zmq::devpoll_t::stop ()
+{
+ stopping = true;
+}
+
+void zmq::devpoll_t::loop ()
+{
+ while (!stopping) {
+
+ struct pollfd ev_buf [max_io_events];
+ struct dvpoll poll_req;
+
+ for (pending_list_t::size_type i = 0; i < pending_list.size (); i ++)
+ fd_table [pending_list [i]].accepted = true;
+ pending_list.clear ();
+
+ // Execute any due timers.
+ int timeout = (int) execute_timers ();
+
+ // Wait for events.
+ // On Solaris, we can retrieve no more then (OPEN_MAX - 1) events.
+ poll_req.dp_fds = &ev_buf [0];
+#if defined ZMQ_HAVE_SOLARIS
+ poll_req.dp_nfds = std::min ((int) max_io_events, OPEN_MAX - 1);
+#else
+ poll_req.dp_nfds = max_io_events;
+#endif
+ poll_req.dp_timeout = timeout ? timeout : -1;
+ int n = ioctl (devpoll_fd, DP_POLL, &poll_req);
+ if (n == -1 && errno == EINTR)
+ continue;
+ errno_assert (n != -1);
+
+ for (int i = 0; i < n; i ++) {
+
+ fd_entry_t *fd_ptr = &fd_table [ev_buf [i].fd];
+ if (!fd_ptr->valid || !fd_ptr->accepted)
+ continue;
+ if (ev_buf [i].revents & (POLLERR | POLLHUP))
+ fd_ptr->reactor->in_event ();
+ if (!fd_ptr->valid || !fd_ptr->accepted)
+ continue;
+ if (ev_buf [i].revents & POLLOUT)
+ fd_ptr->reactor->out_event ();
+ if (!fd_ptr->valid || !fd_ptr->accepted)
+ continue;
+ if (ev_buf [i].revents & POLLIN)
+ fd_ptr->reactor->in_event ();
+ }
+ }
+}
+
+void zmq::devpoll_t::worker_routine (void *arg_)
+{
+ ((devpoll_t*) arg_)->loop ();
+}
+
+#endif
diff --git a/src/0mq/devpoll.hpp b/src/0mq/devpoll.hpp
new file mode 100644
index 0000000..2eaaeb2
--- /dev/null
+++ b/src/0mq/devpoll.hpp
@@ -0,0 +1,100 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_DEVPOLL_HPP_INCLUDED__
+#define __ZMQ_DEVPOLL_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_HPUX
+
+#include <vector>
+
+#include "fd.hpp"
+#include "thread.hpp"
+#include "poller_base.hpp"
+
+namespace zmq
+{
+
+ // Implements socket polling mechanism using the "/dev/poll" interface.
+
+ class devpoll_t : public poller_base_t
+ {
+ public:
+
+ typedef fd_t handle_t;
+
+ devpoll_t ();
+ ~devpoll_t ();
+
+ // "poller" concept.
+ handle_t add_fd (fd_t fd_, struct i_poll_events *events_);
+ void rm_fd (handle_t handle_);
+ void set_pollin (handle_t handle_);
+ void reset_pollin (handle_t handle_);
+ void set_pollout (handle_t handle_);
+ void reset_pollout (handle_t handle_);
+ void start ();
+ void stop ();
+
+ private:
+
+ // Main worker thread routine.
+ static void worker_routine (void *arg_);
+
+ // Main event loop.
+ void loop ();
+
+ // File descriptor referring to "/dev/poll" pseudo-device.
+ fd_t devpoll_fd;
+
+ struct fd_entry_t
+ {
+ short events;
+ struct i_poll_events *reactor;
+ bool valid;
+ bool accepted;
+ };
+
+ typedef std::vector <fd_entry_t> fd_table_t;
+ fd_table_t fd_table;
+
+ typedef std::vector <fd_t> pending_list_t;
+ pending_list_t pending_list;
+
+ // Pollset manipulation function.
+ void devpoll_ctl (fd_t fd_, short events_);
+
+ // If true, thread is in the process of shutting down.
+ bool stopping;
+
+ // Handle of the physical thread doing the I/O work.
+ thread_t worker;
+
+ devpoll_t (const devpoll_t&);
+ const devpoll_t &operator = (const devpoll_t&);
+ };
+
+}
+
+#endif
+
+#endif
diff --git a/src/0mq/dist.cpp b/src/0mq/dist.cpp
new file mode 100644
index 0000000..d74e69f
--- /dev/null
+++ b/src/0mq/dist.cpp
@@ -0,0 +1,200 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "dist.hpp"
+#include "pipe.hpp"
+#include "err.hpp"
+#include "own.hpp"
+#include "msg_content.hpp"
+#include "likely.hpp"
+
+zmq::dist_t::dist_t (own_t *sink_) :
+ active (0),
+ eligible (0),
+ more (false),
+ sink (sink_),
+ terminating (false)
+{
+}
+
+zmq::dist_t::~dist_t ()
+{
+ zmq_assert (pipes.empty ());
+}
+
+void zmq::dist_t::attach (writer_t *pipe_)
+{
+ pipe_->set_event_sink (this);
+
+ // If we are in the middle of sending a message, we'll add new pipe
+ // into the list of eligible pipes. Otherwise we add it to the list
+ // of active pipes.
+ if (more) {
+ pipes.push_back (pipe_);
+ pipes.swap (eligible, pipes.size () - 1);
+ eligible++;
+ }
+ else {
+ pipes.push_back (pipe_);
+ pipes.swap (active, pipes.size () - 1);
+ active++;
+ eligible++;
+ }
+
+ if (unlikely (terminating)) {
+ sink->register_term_acks (1);
+ pipe_->terminate ();
+ }
+}
+
+void zmq::dist_t::terminate ()
+{
+ zmq_assert (!terminating);
+ terminating = true;
+
+ sink->register_term_acks (pipes.size ());
+ for (pipes_t::size_type i = 0; i != pipes.size (); i++)
+ pipes [i]->terminate ();
+}
+
+void zmq::dist_t::terminated (writer_t *pipe_)
+{
+ // Remove the pipe from the list; adjust number of active and/or
+ // eligible pipes accordingly.
+ if (pipes.index (pipe_) < active)
+ active--;
+ if (pipes.index (pipe_) < eligible)
+ eligible--;
+ pipes.erase (pipe_);
+
+ if (unlikely (terminating))
+ sink->unregister_term_ack ();
+}
+
+void zmq::dist_t::activated (writer_t *pipe_)
+{
+ // Move the pipe from passive to eligible state.
+ pipes.swap (pipes.index (pipe_), eligible);
+ eligible++;
+
+ // If there's no message being sent at the moment, move it to
+ // the active state.
+ if (!more) {
+ pipes.swap (eligible - 1, active);
+ active++;
+ }
+}
+
+int zmq::dist_t::send (zmq_msg_t *msg_, int flags_)
+{
+ // Is this end of a multipart message?
+ bool msg_more = msg_->flags & ZMQ_MSG_MORE;
+
+ // Push the message to active pipes.
+ distribute (msg_, flags_);
+
+ // If multipart message is fully sent, activate all the eligible pipes.
+ if (!msg_more)
+ active = eligible;
+
+ more = msg_more;
+
+ return 0;
+}
+
+void zmq::dist_t::distribute (zmq_msg_t *msg_, int flags_)
+{
+ // If there are no active pipes available, simply drop the message.
+ if (active == 0) {
+ int rc = zmq_msg_close (msg_);
+ zmq_assert (rc == 0);
+ rc = zmq_msg_init (msg_);
+ zmq_assert (rc == 0);
+ return;
+ }
+
+ msg_content_t *content = (msg_content_t*) msg_->content;
+
+ // For VSMs the copying is straighforward.
+ if (content == (msg_content_t*) ZMQ_VSM) {
+ for (pipes_t::size_type i = 0; i < active;)
+ if (write (pipes [i], msg_))
+ i++;
+ int rc = zmq_msg_init (msg_);
+ zmq_assert (rc == 0);
+ return;
+ }
+
+ // Optimisation for the case when there's only a single pipe
+ // to send the message to - no refcount adjustment i.e. no atomic
+ // operations are needed.
+ if (active == 1) {
+ if (!write (pipes [0], msg_)) {
+ int rc = zmq_msg_close (msg_);
+ zmq_assert (rc == 0);
+ }
+ int rc = zmq_msg_init (msg_);
+ zmq_assert (rc == 0);
+ return;
+ }
+
+ // There are at least 2 destinations for the message. That means we have
+ // to deal with reference counting. First add N-1 references to
+ // the content (we are holding one reference anyway, that's why -1).
+ if (msg_->flags & ZMQ_MSG_SHARED)
+ content->refcnt.add (active - 1);
+ else {
+ content->refcnt.set (active);
+ msg_->flags |= ZMQ_MSG_SHARED;
+ }
+
+ // Push the message to all destinations.
+ for (pipes_t::size_type i = 0; i < active;) {
+ if (!write (pipes [i], msg_))
+ content->refcnt.sub (1);
+ else
+ i++;
+ }
+
+ // Detach the original message from the data buffer.
+ int rc = zmq_msg_init (msg_);
+ zmq_assert (rc == 0);
+}
+
+bool zmq::dist_t::has_out ()
+{
+ return true;
+}
+
+bool zmq::dist_t::write (class writer_t *pipe_, zmq_msg_t *msg_)
+{
+ if (!pipe_->write (msg_)) {
+ pipes.swap (pipes.index (pipe_), active - 1);
+ active--;
+ pipes.swap (active, eligible - 1);
+ eligible--;
+ return false;
+ }
+ if (!(msg_->flags & ZMQ_MSG_MORE))
+ pipe_->flush ();
+ return true;
+}
diff --git a/src/0mq/dist.hpp b/src/0mq/dist.hpp
new file mode 100644
index 0000000..45aaf90
--- /dev/null
+++ b/src/0mq/dist.hpp
@@ -0,0 +1,90 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_DIST_HPP_INCLUDED__
+#define __ZMQ_DIST_HPP_INCLUDED__
+
+#include <vector>
+
+#include "array.hpp"
+#include "pipe.hpp"
+
+namespace zmq
+{
+
+ // Class manages a set of outbound pipes. It sends each messages to
+ // each of them.
+ class dist_t : public i_writer_events
+ {
+ public:
+
+ dist_t (class own_t *sink_);
+ ~dist_t ();
+
+ void attach (writer_t *pipe_);
+ void terminate ();
+ int send (zmq_msg_t *msg_, int flags_);
+ bool has_out ();
+
+ // i_writer_events interface implementation.
+ void activated (writer_t *pipe_);
+ void terminated (writer_t *pipe_);
+
+ private:
+
+ // Write the message to the pipe. Make the pipe inactive if writing
+ // fails. In such a case false is returned.
+ bool write (class writer_t *pipe_, zmq_msg_t *msg_);
+
+ // Put the message to all active pipes.
+ void distribute (zmq_msg_t *msg_, int flags_);
+
+ // List of outbound pipes.
+ typedef array_t <class writer_t> pipes_t;
+ pipes_t pipes;
+
+ // Number of active pipes. All the active pipes are located at the
+ // beginning of the pipes array. These are the pipes the messages
+ // can be sent to at the moment.
+ pipes_t::size_type active;
+
+ // Number of pipes eligible for sending messages to. This includes all
+ // the active pipes plus all the pipes that we can in theory send
+ // messages to (the HWM is not yet reached), but sending a message
+ // to them would result in partial message being delivered, ie. message
+ // with initial parts missing.
+ pipes_t::size_type eligible;
+
+ // True if last we are in the middle of a multipart message.
+ bool more;
+
+ // Object to send events to.
+ class own_t *sink;
+
+ // If true, termination process is already underway.
+ bool terminating;
+
+ dist_t (const dist_t&);
+ const dist_t &operator = (const dist_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/encoder.cpp b/src/0mq/encoder.cpp
new file mode 100644
index 0000000..88e1dff
--- /dev/null
+++ b/src/0mq/encoder.cpp
@@ -0,0 +1,90 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "encoder.hpp"
+#include "i_inout.hpp"
+#include "wire.hpp"
+
+zmq::encoder_t::encoder_t (size_t bufsize_) :
+ encoder_base_t <encoder_t> (bufsize_),
+ source (NULL)
+{
+ zmq_msg_init (&in_progress);
+
+ // Write 0 bytes to the batch and go to message_ready state.
+ next_step (NULL, 0, &encoder_t::message_ready, true);
+}
+
+zmq::encoder_t::~encoder_t ()
+{
+ zmq_msg_close (&in_progress);
+}
+
+void zmq::encoder_t::set_inout (i_inout *source_)
+{
+ source = source_;
+}
+
+bool zmq::encoder_t::size_ready ()
+{
+ // Write message body into the buffer.
+ next_step (zmq_msg_data (&in_progress), zmq_msg_size (&in_progress),
+ &encoder_t::message_ready, false);
+ return true;
+}
+
+bool zmq::encoder_t::message_ready ()
+{
+ // Destroy content of the old message.
+ zmq_msg_close (&in_progress);
+
+ // Read new message. If there is none, return false.
+ // Note that new state is set only if write is successful. That way
+ // unsuccessful write will cause retry on the next state machine
+ // invocation.
+ if (!source || !source->read (&in_progress)) {
+ zmq_msg_init (&in_progress);
+ return false;
+ }
+
+ // Get the message size.
+ size_t size = zmq_msg_size (&in_progress);
+
+ // Account for the 'flags' byte.
+ size++;
+
+ // For messages less than 255 bytes long, write one byte of message size.
+ // For longer messages write 0xff escape character followed by 8-byte
+ // message size. In both cases 'flags' field follows.
+ if (size < 255) {
+ tmpbuf [0] = (unsigned char) size;
+ tmpbuf [1] = (in_progress.flags & ~ZMQ_MSG_SHARED);
+ next_step (tmpbuf, 2, &encoder_t::size_ready,
+ !(in_progress.flags & ZMQ_MSG_MORE));
+ }
+ else {
+ tmpbuf [0] = 0xff;
+ put_uint64 (tmpbuf + 1, size);
+ tmpbuf [9] = (in_progress.flags & ~ZMQ_MSG_SHARED);
+ next_step (tmpbuf, 10, &encoder_t::size_ready,
+ !(in_progress.flags & ZMQ_MSG_MORE));
+ }
+ return true;
+}
diff --git a/src/0mq/encoder.hpp b/src/0mq/encoder.hpp
new file mode 100644
index 0000000..918ec2b
--- /dev/null
+++ b/src/0mq/encoder.hpp
@@ -0,0 +1,184 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_ENCODER_HPP_INCLUDED__
+#define __ZMQ_ENCODER_HPP_INCLUDED__
+
+#include <stddef.h>
+#include <string.h>
+#include <stdlib.h>
+#include <algorithm>
+
+#include "err.hpp"
+
+#include "../include/zmq.h"
+
+namespace zmq
+{
+
+ // Helper base class for encoders. It implements the state machine that
+ // fills the outgoing buffer. Derived classes should implement individual
+ // state machine actions.
+
+ template <typename T> class encoder_base_t
+ {
+ public:
+
+ inline encoder_base_t (size_t bufsize_) :
+ bufsize (bufsize_)
+ {
+ buf = (unsigned char*) malloc (bufsize_);
+ alloc_assert (buf);
+ }
+
+ // The destructor doesn't have to be virtual. It is made virtual
+ // just to keep ICC and code checking tools from complaining.
+ inline virtual ~encoder_base_t ()
+ {
+ free (buf);
+ }
+
+ // The function returns a batch of binary data. The data
+ // are filled to a supplied buffer. If no buffer is supplied (data_
+ // points to NULL) decoder object will provide buffer of its own.
+ // If offset is not NULL, it is filled by offset of the first message
+ // in the batch.If there's no beginning of a message in the batch,
+ // offset is set to -1.
+ inline void get_data (unsigned char **data_, size_t *size_,
+ int *offset_ = NULL)
+ {
+ unsigned char *buffer = !*data_ ? buf : *data_;
+ size_t buffersize = !*data_ ? bufsize : *size_;
+
+ size_t pos = 0;
+ if (offset_)
+ *offset_ = -1;
+
+ while (true) {
+
+ // If there are no more data to return, run the state machine.
+ // If there are still no data, return what we already have
+ // in the buffer.
+ if (!to_write) {
+ if (!(static_cast <T*> (this)->*next) ()) {
+ *data_ = buffer;
+ *size_ = pos;
+ return;
+ }
+
+ // If beginning of the message was processed, adjust the
+ // first-message-offset.
+ if (beginning) {
+ if (offset_ && *offset_ == -1)
+ *offset_ = pos;
+ beginning = false;
+ }
+ }
+
+ // If there are no data in the buffer yet and we are able to
+ // fill whole buffer in a single go, let's use zero-copy.
+ // There's no disadvantage to it as we cannot stuck multiple
+ // messages into the buffer anyway. Note that subsequent
+ // write(s) are non-blocking, thus each single write writes
+ // at most SO_SNDBUF bytes at once not depending on how large
+ // is the chunk returned from here.
+ // As a consequence, large messages being sent won't block
+ // other engines running in the same I/O thread for excessive
+ // amounts of time.
+ if (!pos && !*data_ && to_write >= buffersize) {
+ *data_ = write_pos;
+ *size_ = to_write;
+ write_pos = NULL;
+ to_write = 0;
+ return;
+ }
+
+ // Copy data to the buffer. If the buffer is full, return.
+ size_t to_copy = std::min (to_write, buffersize - pos);
+ memcpy (buffer + pos, write_pos, to_copy);
+ pos += to_copy;
+ write_pos += to_copy;
+ to_write -= to_copy;
+ if (pos == buffersize) {
+ *data_ = buffer;
+ *size_ = pos;
+ return;
+ }
+ }
+ }
+
+ protected:
+
+ // Prototype of state machine action.
+ typedef bool (T::*step_t) ();
+
+ // This function should be called from derived class to write the data
+ // to the buffer and schedule next state machine action. Set beginning
+ // to true when you are writing first byte of a message.
+ inline void next_step (void *write_pos_, size_t to_write_,
+ step_t next_, bool beginning_)
+ {
+ write_pos = (unsigned char*) write_pos_;
+ to_write = to_write_;
+ next = next_;
+ beginning = beginning_;
+ }
+
+ private:
+
+ unsigned char *write_pos;
+ size_t to_write;
+ step_t next;
+ bool beginning;
+
+ size_t bufsize;
+ unsigned char *buf;
+
+ encoder_base_t (const encoder_base_t&);
+ void operator = (const encoder_base_t&);
+ };
+
+ // Encoder for 0MQ framing protocol. Converts messages into data batches.
+
+ class encoder_t : public encoder_base_t <encoder_t>
+ {
+ public:
+
+ encoder_t (size_t bufsize_);
+ ~encoder_t ();
+
+ void set_inout (struct i_inout *source_);
+
+ private:
+
+ bool size_ready ();
+ bool message_ready ();
+
+ struct i_inout *source;
+ ::zmq_msg_t in_progress;
+ unsigned char tmpbuf [10];
+
+ encoder_t (const encoder_t&);
+ const encoder_t &operator = (const encoder_t&);
+ };
+}
+
+#endif
+
diff --git a/src/0mq/epoll.cpp b/src/0mq/epoll.cpp
new file mode 100644
index 0000000..2c84f8c
--- /dev/null
+++ b/src/0mq/epoll.cpp
@@ -0,0 +1,177 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+
+#ifdef ZMQ_HAVE_LINUX
+
+#include <sys/epoll.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <algorithm>
+#include <new>
+
+#include "epoll.hpp"
+#include "err.hpp"
+#include "config.hpp"
+#include "i_poll_events.hpp"
+
+zmq::epoll_t::epoll_t () :
+ stopping (false)
+{
+ epoll_fd = epoll_create (1);
+ errno_assert (epoll_fd != -1);
+}
+
+zmq::epoll_t::~epoll_t ()
+{
+ // Wait till the worker thread exits.
+ worker.stop ();
+
+ close (epoll_fd);
+ for (retired_t::iterator it = retired.begin (); it != retired.end (); ++it)
+ delete *it;
+}
+
+zmq::epoll_t::handle_t zmq::epoll_t::add_fd (fd_t fd_, i_poll_events *events_)
+{
+ poll_entry_t *pe = new (std::nothrow) poll_entry_t;
+ alloc_assert (pe);
+
+ // The memset is not actually needed. It's here to prevent debugging
+ // tools to complain about using uninitialised memory.
+ memset (pe, 0, sizeof (poll_entry_t));
+
+ pe->fd = fd_;
+ pe->ev.events = 0;
+ pe->ev.data.ptr = pe;
+ pe->events = events_;
+
+ int rc = epoll_ctl (epoll_fd, EPOLL_CTL_ADD, fd_, &pe->ev);
+ errno_assert (rc != -1);
+
+ // Increase the load metric of the thread.
+ adjust_load (1);
+
+ return pe;
+}
+
+void zmq::epoll_t::rm_fd (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ int rc = epoll_ctl (epoll_fd, EPOLL_CTL_DEL, pe->fd, &pe->ev);
+ errno_assert (rc != -1);
+ pe->fd = retired_fd;
+ retired.push_back (pe);
+
+ // Decrease the load metric of the thread.
+ adjust_load (-1);
+}
+
+void zmq::epoll_t::set_pollin (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ pe->ev.events |= EPOLLIN;
+ int rc = epoll_ctl (epoll_fd, EPOLL_CTL_MOD, pe->fd, &pe->ev);
+ errno_assert (rc != -1);
+}
+
+void zmq::epoll_t::reset_pollin (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ pe->ev.events &= ~((short) EPOLLIN);
+ int rc = epoll_ctl (epoll_fd, EPOLL_CTL_MOD, pe->fd, &pe->ev);
+ errno_assert (rc != -1);
+}
+
+void zmq::epoll_t::set_pollout (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ pe->ev.events |= EPOLLOUT;
+ int rc = epoll_ctl (epoll_fd, EPOLL_CTL_MOD, pe->fd, &pe->ev);
+ errno_assert (rc != -1);
+}
+
+void zmq::epoll_t::reset_pollout (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ pe->ev.events &= ~((short) EPOLLOUT);
+ int rc = epoll_ctl (epoll_fd, EPOLL_CTL_MOD, pe->fd, &pe->ev);
+ errno_assert (rc != -1);
+}
+
+void zmq::epoll_t::start ()
+{
+ worker.start (worker_routine, this);
+}
+
+void zmq::epoll_t::stop ()
+{
+ stopping = true;
+}
+
+void zmq::epoll_t::loop ()
+{
+ epoll_event ev_buf [max_io_events];
+
+ while (!stopping) {
+
+ // Execute any due timers.
+ int timeout = (int) execute_timers ();
+
+ // Wait for events.
+ int n = epoll_wait (epoll_fd, &ev_buf [0], max_io_events,
+ timeout ? timeout : -1);
+ if (n == -1 && errno == EINTR)
+ continue;
+ errno_assert (n != -1);
+
+ for (int i = 0; i < n; i ++) {
+ poll_entry_t *pe = ((poll_entry_t*) ev_buf [i].data.ptr);
+
+ if (pe->fd == retired_fd)
+ continue;
+ if (ev_buf [i].events & (EPOLLERR | EPOLLHUP))
+ pe->events->in_event ();
+ if (pe->fd == retired_fd)
+ continue;
+ if (ev_buf [i].events & EPOLLOUT)
+ pe->events->out_event ();
+ if (pe->fd == retired_fd)
+ continue;
+ if (ev_buf [i].events & EPOLLIN)
+ pe->events->in_event ();
+ }
+
+ // Destroy retired event sources.
+ for (retired_t::iterator it = retired.begin (); it != retired.end ();
+ ++it)
+ delete *it;
+ retired.clear ();
+ }
+}
+
+void zmq::epoll_t::worker_routine (void *arg_)
+{
+ ((epoll_t*) arg_)->loop ();
+}
+
+#endif
diff --git a/src/0mq/epoll.hpp b/src/0mq/epoll.hpp
new file mode 100644
index 0000000..7e5195e
--- /dev/null
+++ b/src/0mq/epoll.hpp
@@ -0,0 +1,96 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_EPOLL_HPP_INCLUDED__
+#define __ZMQ_EPOLL_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#ifdef ZMQ_HAVE_LINUX
+
+#include <vector>
+#include <sys/epoll.h>
+
+#include "fd.hpp"
+#include "thread.hpp"
+#include "poller_base.hpp"
+
+namespace zmq
+{
+
+ // This class implements socket polling mechanism using the Linux-specific
+ // epoll mechanism.
+
+ class epoll_t : public poller_base_t
+ {
+ public:
+
+ typedef void* handle_t;
+
+ epoll_t ();
+ ~epoll_t ();
+
+ // "poller" concept.
+ handle_t add_fd (fd_t fd_, struct i_poll_events *events_);
+ void rm_fd (handle_t handle_);
+ void set_pollin (handle_t handle_);
+ void reset_pollin (handle_t handle_);
+ void set_pollout (handle_t handle_);
+ void reset_pollout (handle_t handle_);
+ void start ();
+ void stop ();
+
+ private:
+
+ // Main worker thread routine.
+ static void worker_routine (void *arg_);
+
+ // Main event loop.
+ void loop ();
+
+ // Main epoll file descriptor
+ fd_t epoll_fd;
+
+ struct poll_entry_t
+ {
+ fd_t fd;
+ epoll_event ev;
+ struct i_poll_events *events;
+ };
+
+ // List of retired event sources.
+ typedef std::vector <poll_entry_t*> retired_t;
+ retired_t retired;
+
+ // If true, thread is in the process of shutting down.
+ bool stopping;
+
+ // Handle of the physical thread doing the I/O work.
+ thread_t worker;
+
+ epoll_t (const epoll_t&);
+ const epoll_t &operator = (const epoll_t&);
+ };
+
+}
+
+#endif
+
+#endif
diff --git a/src/0mq/err.cpp b/src/0mq/err.cpp
new file mode 100644
index 0000000..ddc08ee
--- /dev/null
+++ b/src/0mq/err.cpp
@@ -0,0 +1,251 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "err.hpp"
+#include "platform.hpp"
+
+const char *zmq::errno_to_string (int errno_)
+{
+ switch (errno_) {
+#if defined ZMQ_HAVE_WINDOWS
+ case ENOTSUP:
+ return "Not supported";
+ case EPROTONOSUPPORT:
+ return "Protocol not supported";
+ case ENOBUFS:
+ return "No buffer space available";
+ case ENETDOWN:
+ return "Network is down";
+ case EADDRINUSE:
+ return "Address in use";
+ case EADDRNOTAVAIL:
+ return "Address not available";
+ case ECONNREFUSED:
+ return "Connection refused";
+ case EINPROGRESS:
+ return "Operation in progress";
+#endif
+ case EFSM:
+ return "Operation cannot be accomplished in current state";
+ case ENOCOMPATPROTO:
+ return "The protocol is not compatible with the socket type";
+ case ETERM:
+ return "Context was terminated";
+ case EMTHREAD:
+ return "No thread available";
+ default:
+#if defined _MSC_VER
+#pragma warning (push)
+#pragma warning (disable:4996)
+#endif
+ return strerror (errno_);
+#if defined _MSC_VER
+#pragma warning (pop)
+#endif
+ }
+}
+
+void zmq::zmq_abort(const char *errmsg_)
+{
+#if defined ZMQ_HAVE_WINDOWS
+
+ // Raise STATUS_FATAL_APP_EXIT.
+ ULONG_PTR extra_info [1];
+ extra_info [0] = (ULONG_PTR) errmsg_;
+ RaiseException (0x40000015, EXCEPTION_NONCONTINUABLE, 1, extra_info);
+#else
+ abort ();
+#endif
+}
+
+#ifdef ZMQ_HAVE_WINDOWS
+
+const char *zmq::wsa_error()
+{
+ int no = WSAGetLastError ();
+ // TODO: This is not a generic way to handle this...
+ if (no == WSAEWOULDBLOCK)
+ return NULL;
+
+ return wsa_error_no (no);
+}
+
+const char *zmq::wsa_error_no (int no_)
+{
+ // TODO: It seems that list of Windows socket errors is longer than this.
+ // Investigate whether there's a way to convert it into the string
+ // automatically (wsaError->HRESULT->string?).
+ return
+ (no_ == WSABASEERR) ?
+ "No Error" :
+ (no_ == WSAEINTR) ?
+ "Interrupted system call" :
+ (no_ == WSAEBADF) ?
+ "Bad file number" :
+ (no_ == WSAEACCES) ?
+ "Permission denied" :
+ (no_ == WSAEFAULT) ?
+ "Bad address" :
+ (no_ == WSAEINVAL) ?
+ "Invalid argument" :
+ (no_ == WSAEMFILE) ?
+ "Too many open files" :
+ (no_ == WSAEWOULDBLOCK) ?
+ "Operation would block" :
+ (no_ == WSAEINPROGRESS) ?
+ "Operation now in progress" :
+ (no_ == WSAEALREADY) ?
+ "Operation already in progress" :
+ (no_ == WSAENOTSOCK) ?
+ "Socket operation on non-socket" :
+ (no_ == WSAEDESTADDRREQ) ?
+ "Destination address required" :
+ (no_ == WSAEMSGSIZE) ?
+ "Message too long" :
+ (no_ == WSAEPROTOTYPE) ?
+ "Protocol wrong type for socket" :
+ (no_ == WSAENOPROTOOPT) ?
+ "Bad protocol option" :
+ (no_ == WSAEPROTONOSUPPORT) ?
+ "Protocol not supported" :
+ (no_ == WSAESOCKTNOSUPPORT) ?
+ "Socket type not supported" :
+ (no_ == WSAEOPNOTSUPP) ?
+ "Operation not supported on socket" :
+ (no_ == WSAEPFNOSUPPORT) ?
+ "Protocol family not supported" :
+ (no_ == WSAEAFNOSUPPORT) ?
+ "Address family not supported by protocol family" :
+ (no_ == WSAEADDRINUSE) ?
+ "Address already in use" :
+ (no_ == WSAEADDRNOTAVAIL) ?
+ "Can't assign requested address" :
+ (no_ == WSAENETDOWN) ?
+ "Network is down" :
+ (no_ == WSAENETUNREACH) ?
+ "Network is unreachable" :
+ (no_ == WSAENETRESET) ?
+ "Net dropped connection or reset" :
+ (no_ == WSAECONNABORTED) ?
+ "Software caused connection abort" :
+ (no_ == WSAECONNRESET) ?
+ "Connection reset by peer" :
+ (no_ == WSAENOBUFS) ?
+ "No buffer space available" :
+ (no_ == WSAEISCONN) ?
+ "Socket is already connected" :
+ (no_ == WSAENOTCONN) ?
+ "Socket is not connected" :
+ (no_ == WSAESHUTDOWN) ?
+ "Can't send after socket shutdown" :
+ (no_ == WSAETOOMANYREFS) ?
+ "Too many references can't splice" :
+ (no_ == WSAETIMEDOUT) ?
+ "Connection timed out" :
+ (no_ == WSAECONNREFUSED) ?
+ "Connection refused" :
+ (no_ == WSAELOOP) ?
+ "Too many levels of symbolic links" :
+ (no_ == WSAENAMETOOLONG) ?
+ "File name too long" :
+ (no_ == WSAEHOSTDOWN) ?
+ "Host is down" :
+ (no_ == WSAEHOSTUNREACH) ?
+ "No Route to Host" :
+ (no_ == WSAENOTEMPTY) ?
+ "Directory not empty" :
+ (no_ == WSAEPROCLIM) ?
+ "Too many processes" :
+ (no_ == WSAEUSERS) ?
+ "Too many users" :
+ (no_ == WSAEDQUOT) ?
+ "Disc Quota Exceeded" :
+ (no_ == WSAESTALE) ?
+ "Stale NFS file handle" :
+ (no_ == WSAEREMOTE) ?
+ "Too many levels of remote in path" :
+ (no_ == WSASYSNOTREADY) ?
+ "Network SubSystem is unavailable" :
+ (no_ == WSAVERNOTSUPPORTED) ?
+ "WINSOCK DLL Version out of range" :
+ (no_ == WSANOTINITIALISED) ?
+ "Successful WSASTARTUP not yet performed" :
+ (no_ == WSAHOST_NOT_FOUND) ?
+ "Host not found" :
+ (no_ == WSATRY_AGAIN) ?
+ "Non-Authoritative Host not found" :
+ (no_ == WSANO_RECOVERY) ?
+ "Non-Recoverable errors: FORMERR REFUSED NOTIMP" :
+ (no_ == WSANO_DATA) ?
+ "Valid name no data record of requested" :
+ "error not defined";
+}
+
+void zmq::win_error (char *buffer_, size_t buffer_size_)
+{
+ DWORD errcode = GetLastError ();
+ DWORD rc = FormatMessageA (FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, MAKELANGID(LANG_NEUTRAL,
+ SUBLANG_DEFAULT), buffer_, buffer_size_, NULL );
+ zmq_assert (rc);
+}
+
+void zmq::wsa_error_to_errno ()
+{
+ int errcode = WSAGetLastError ();
+ switch (errcode) {
+ case WSAEINPROGRESS:
+ errno = EAGAIN;
+ return;
+ case WSAEBADF:
+ errno = EBADF;
+ return;
+ case WSAEINVAL:
+ errno = EINVAL;
+ return;
+ case WSAEMFILE:
+ errno = EMFILE;
+ return;
+ case WSAEFAULT:
+ errno = EFAULT;
+ return;
+ case WSAEPROTONOSUPPORT:
+ errno = EPROTONOSUPPORT;
+ return;
+ case WSAENOBUFS:
+ errno = ENOBUFS;
+ return;
+ case WSAENETDOWN:
+ errno = ENETDOWN;
+ return;
+ case WSAEADDRINUSE:
+ errno = EADDRINUSE;
+ return;
+ case WSAEADDRNOTAVAIL:
+ errno = EADDRNOTAVAIL;
+ return;
+ default:
+ wsa_assert (false);
+ }
+}
+
+#endif
diff --git a/src/0mq/err.hpp b/src/0mq/err.hpp
new file mode 100644
index 0000000..7c7a9d8
--- /dev/null
+++ b/src/0mq/err.hpp
@@ -0,0 +1,150 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_ERR_HPP_INCLUDED__
+#define __ZMQ_ERR_HPP_INCLUDED__
+
+// 0MQ-specific error codes are defined in zmq.h
+#include "../include/zmq.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+#include "platform.hpp"
+#include "likely.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#else
+#include <netdb.h>
+#endif
+
+namespace zmq
+{
+ const char *errno_to_string (int errno_);
+ void zmq_abort (const char *errmsg_);
+}
+
+#ifdef ZMQ_HAVE_WINDOWS
+
+namespace zmq
+{
+ const char *wsa_error ();
+ const char *wsa_error_no (int no_);
+ void win_error (char *buffer_, size_t buffer_size_);
+ void wsa_error_to_errno ();
+}
+
+// Provides convenient way to check WSA-style errors on Windows.
+#define wsa_assert(x) \
+ do {\
+ if (unlikely (!(x))) {\
+ const char *errstr = zmq::wsa_error ();\
+ if (errstr != NULL) {\
+ fprintf (stderr, "Assertion failed: %s (%s:%d)\n", errstr, \
+ __FILE__, __LINE__);\
+ zmq::zmq_abort (errstr);\
+ }\
+ }\
+ } while (false)
+
+// Provides convenient way to assert on WSA-style errors on Windows.
+#define wsa_assert_no(no) \
+ do {\
+ const char *errstr = zmq::wsa_error_no (no);\
+ if (errstr != NULL) {\
+ fprintf (stderr, "Assertion failed: %s (%s:%d)\n", errstr, \
+ __FILE__, __LINE__);\
+ zmq::zmq_abort (errstr);\
+ }\
+ } while (false)
+
+// Provides convenient way to check GetLastError-style errors on Windows.
+#define win_assert(x) \
+ do {\
+ if (unlikely (!(x))) {\
+ char errstr [256];\
+ zmq::win_error (errstr, 256);\
+ fprintf (stderr, "Assertion failed: %s (%s:%d)\n", errstr, \
+ __FILE__, __LINE__);\
+ zmq::zmq_abort (errstr);\
+ }\
+ } while (false)
+
+#endif
+
+// This macro works in exactly the same way as the normal assert. It is used
+// in its stead because standard assert on Win32 in broken - it prints nothing
+// when used within the scope of JNI library.
+#define zmq_assert(x) \
+ do {\
+ if (unlikely (!(x))) {\
+ fprintf (stderr, "Assertion failed: %s (%s:%d)\n", #x, \
+ __FILE__, __LINE__);\
+ zmq::zmq_abort (#x);\
+ }\
+ } while (false)
+
+// Provides convenient way to check for errno-style errors.
+#define errno_assert(x) \
+ do {\
+ if (unlikely (!(x))) {\
+ const char *errstr = strerror (errno);\
+ fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__);\
+ zmq::zmq_abort (errstr);\
+ }\
+ } while (false)
+
+// Provides convenient way to check for POSIX errors.
+#define posix_assert(x) \
+ do {\
+ if (unlikely (x)) {\
+ const char *errstr = strerror (x);\
+ fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__);\
+ zmq::zmq_abort (errstr);\
+ }\
+ } while (false)
+
+// Provides convenient way to check for errors from getaddrinfo.
+#define gai_assert(x) \
+ do {\
+ if (unlikely (x)) {\
+ const char *errstr = gai_strerror (x);\
+ fprintf (stderr, "%s (%s:%d)\n", errstr, __FILE__, __LINE__);\
+ zmq::zmq_abort (errstr);\
+ }\
+ } while (false)
+
+// Provides convenient way to check whether memory allocation have succeeded.
+#define alloc_assert(x) \
+ do {\
+ if (unlikely (!x)) {\
+ fprintf (stderr, "FATAL ERROR: OUT OF MEMORY (%s:%d)\n",\
+ __FILE__, __LINE__);\
+ zmq::zmq_abort ("FATAL ERROR: OUT OF MEMORY");\
+ }\
+ } while (false)
+
+#endif
+
+
diff --git a/src/0mq/fd.hpp b/src/0mq/fd.hpp
new file mode 100644
index 0000000..3b15024
--- /dev/null
+++ b/src/0mq/fd.hpp
@@ -0,0 +1,45 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_FD_HPP_INCLUDED__
+#define __ZMQ_FD_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+namespace zmq
+{
+#ifdef ZMQ_HAVE_WINDOWS
+#if defined _MSC_VER &&_MSC_VER <= 1400
+ typedef UINT_PTR fd_t;
+ enum {retired_fd = (fd_t)(~0)};
+#else
+ typedef SOCKET fd_t;
+ enum {retired_fd = INVALID_SOCKET};
+#endif
+#else
+ typedef int fd_t;
+ enum {retired_fd = -1};
+#endif
+}
+#endif
diff --git a/src/0mq/fq.cpp b/src/0mq/fq.cpp
new file mode 100644
index 0000000..a1952d8
--- /dev/null
+++ b/src/0mq/fq.cpp
@@ -0,0 +1,164 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "fq.hpp"
+#include "pipe.hpp"
+#include "err.hpp"
+#include "own.hpp"
+
+zmq::fq_t::fq_t (own_t *sink_) :
+ active (0),
+ current (0),
+ more (false),
+ sink (sink_),
+ terminating (false)
+{
+}
+
+zmq::fq_t::~fq_t ()
+{
+ zmq_assert (pipes.empty ());
+}
+
+void zmq::fq_t::attach (reader_t *pipe_)
+{
+ pipe_->set_event_sink (this);
+
+ pipes.push_back (pipe_);
+ pipes.swap (active, pipes.size () - 1);
+ active++;
+
+ // If we are already terminating, ask the pipe to terminate straight away.
+ if (terminating) {
+ sink->register_term_acks (1);
+ pipe_->terminate ();
+ }
+}
+
+void zmq::fq_t::terminated (reader_t *pipe_)
+{
+ // Make sure that we are not closing current pipe while
+ // message is half-read.
+ zmq_assert (terminating || (!more || pipes [current] != pipe_));
+
+ // Remove the pipe from the list; adjust number of active pipes
+ // accordingly.
+ if (pipes.index (pipe_) < active) {
+ active--;
+ if (current == active)
+ current = 0;
+ }
+ pipes.erase (pipe_);
+
+ if (terminating)
+ sink->unregister_term_ack ();
+}
+
+void zmq::fq_t::delimited (reader_t *pipe_)
+{
+}
+
+void zmq::fq_t::terminate ()
+{
+ zmq_assert (!terminating);
+ terminating = true;
+
+ sink->register_term_acks (pipes.size ());
+ for (pipes_t::size_type i = 0; i != pipes.size (); i++)
+ pipes [i]->terminate ();
+}
+
+void zmq::fq_t::activated (reader_t *pipe_)
+{
+ // Move the pipe to the list of active pipes.
+ pipes.swap (pipes.index (pipe_), active);
+ active++;
+}
+
+int zmq::fq_t::recv (zmq_msg_t *msg_, int flags_)
+{
+ // Deallocate old content of the message.
+ zmq_msg_close (msg_);
+
+ // Round-robin over the pipes to get the next message.
+ for (int count = active; count != 0; count--) {
+
+ // Try to fetch new message. If we've already read part of the message
+ // subsequent part should be immediately available.
+ bool fetched = pipes [current]->read (msg_);
+
+ // Check the atomicity of the message. If we've already received the
+ // first part of the message we should get the remaining parts
+ // without blocking.
+ zmq_assert (!(more && !fetched));
+
+ // Note that when message is not fetched, current pipe is deactivated
+ // and replaced by another active pipe. Thus we don't have to increase
+ // the 'current' pointer.
+ if (fetched) {
+ more = msg_->flags & ZMQ_MSG_MORE;
+ if (!more) {
+ current++;
+ if (current >= active)
+ current = 0;
+ }
+ return 0;
+ }
+ else {
+ active--;
+ pipes.swap (current, active);
+ if (current == active)
+ current = 0;
+ }
+ }
+
+ // No message is available. Initialise the output parameter
+ // to be a 0-byte message.
+ zmq_msg_init (msg_);
+ errno = EAGAIN;
+ return -1;
+}
+
+bool zmq::fq_t::has_in ()
+{
+ // There are subsequent parts of the partly-read message available.
+ if (more)
+ return true;
+
+ // Note that messing with current doesn't break the fairness of fair
+ // queueing algorithm. If there are no messages available current will
+ // get back to its original value. Otherwise it'll point to the first
+ // pipe holding messages, skipping only pipes with no messages available.
+ for (int count = active; count != 0; count--) {
+ if (pipes [current]->check_read ())
+ return true;
+
+ // Deactivate the pipe.
+ active--;
+ pipes.swap (current, active);
+ if (current == active)
+ current = 0;
+ }
+
+ return false;
+}
+
diff --git a/src/0mq/fq.hpp b/src/0mq/fq.hpp
new file mode 100644
index 0000000..8c6c95c
--- /dev/null
+++ b/src/0mq/fq.hpp
@@ -0,0 +1,80 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_FQ_HPP_INCLUDED__
+#define __ZMQ_FQ_HPP_INCLUDED__
+
+#include "array.hpp"
+#include "pipe.hpp"
+
+namespace zmq
+{
+
+ // Class manages a set of inbound pipes. On receive it performs fair
+ // queueing (RFC970) so that senders gone berserk won't cause denial of
+ // service for decent senders.
+ class fq_t : public i_reader_events
+ {
+ public:
+
+ fq_t (class own_t *sink_);
+ ~fq_t ();
+
+ void attach (reader_t *pipe_);
+ void terminate ();
+
+ int recv (zmq_msg_t *msg_, int flags_);
+ bool has_in ();
+
+ // i_reader_events implementation.
+ void activated (reader_t *pipe_);
+ void terminated (reader_t *pipe_);
+ void delimited (reader_t *pipe_);
+
+ private:
+
+ // Inbound pipes.
+ typedef array_t <reader_t> pipes_t;
+ pipes_t pipes;
+
+ // Number of active pipes. All the active pipes are located at the
+ // beginning of the pipes array.
+ pipes_t::size_type active;
+
+ // Index of the next bound pipe to read a message from.
+ pipes_t::size_type current;
+
+ // If true, part of a multipart message was already received, but
+ // there are following parts still waiting in the current pipe.
+ bool more;
+
+ // Object to send events to.
+ class own_t *sink;
+
+ // If true, termination process is already underway.
+ bool terminating;
+
+ fq_t (const fq_t&);
+ const fq_t &operator = (const fq_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/i_engine.hpp b/src/0mq/i_engine.hpp
new file mode 100644
index 0000000..7bd4ea6
--- /dev/null
+++ b/src/0mq/i_engine.hpp
@@ -0,0 +1,53 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_I_ENGINE_HPP_INCLUDED__
+#define __ZMQ_I_ENGINE_HPP_INCLUDED__
+
+namespace zmq
+{
+
+ struct i_engine
+ {
+ virtual ~i_engine () {}
+
+ // Plug the engine to the session.
+ virtual void plug (class io_thread_t *io_thread_,
+ struct i_inout *inout_) = 0;
+
+ // Unplug the engine from the session.
+ virtual void unplug () = 0;
+
+ // Terminate and deallocate the engine. Note that 'detached'
+ // events are not fired on termination.
+ virtual void terminate () = 0;
+
+ // This method is called by the session to signalise that more
+ // messages can be written to the pipe.
+ virtual void activate_in () = 0;
+
+ // This method is called by the session to signalise that there
+ // are messages to send available.
+ virtual void activate_out () = 0;
+ };
+
+}
+
+#endif
diff --git a/src/0mq/i_inout.hpp b/src/0mq/i_inout.hpp
new file mode 100644
index 0000000..057b46c
--- /dev/null
+++ b/src/0mq/i_inout.hpp
@@ -0,0 +1,50 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_I_INOUT_HPP_INCLUDED__
+#define __ZMQ_I_INOUT_HPP_INCLUDED__
+
+#include "../include/zmq.h"
+
+#include "stdint.hpp"
+
+namespace zmq
+{
+
+ struct i_inout
+ {
+ virtual ~i_inout () {}
+
+ // Engine asks for a message to send to the network.
+ virtual bool read (::zmq_msg_t *msg_) = 0;
+
+ // Engine received message from the network and sends it further on.
+ virtual bool write (::zmq_msg_t *msg_) = 0;
+
+ // Flush all the previously written messages.
+ virtual void flush () = 0;
+
+ // Engine is dead. Drop all the references to it.
+ virtual void detach () = 0;
+ };
+
+}
+
+#endif
diff --git a/src/0mq/i_poll_events.hpp b/src/0mq/i_poll_events.hpp
new file mode 100644
index 0000000..fa9fb25
--- /dev/null
+++ b/src/0mq/i_poll_events.hpp
@@ -0,0 +1,46 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_I_POLL_EVENTS_HPP_INCLUDED__
+#define __ZMQ_I_POLL_EVENTS_HPP_INCLUDED__
+
+namespace zmq
+{
+
+ // Virtual interface to be exposed by object that want to be notified
+ // about events on file descriptors.
+
+ struct i_poll_events
+ {
+ virtual ~i_poll_events () {}
+
+ // Called by I/O thread when file descriptor is ready for reading.
+ virtual void in_event () = 0;
+
+ // Called by I/O thread when file descriptor is ready for writing.
+ virtual void out_event () = 0;
+
+ // Called when timer expires.
+ virtual void timer_event (int id_) = 0;
+ };
+
+}
+
+#endif
diff --git a/src/0mq/io_object.cpp b/src/0mq/io_object.cpp
new file mode 100644
index 0000000..e68917c
--- /dev/null
+++ b/src/0mq/io_object.cpp
@@ -0,0 +1,107 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "io_object.hpp"
+#include "io_thread.hpp"
+#include "err.hpp"
+
+zmq::io_object_t::io_object_t (io_thread_t *io_thread_) :
+ poller (NULL)
+{
+ if (io_thread_)
+ plug (io_thread_);
+}
+
+zmq::io_object_t::~io_object_t ()
+{
+}
+
+void zmq::io_object_t::plug (io_thread_t *io_thread_)
+{
+ zmq_assert (io_thread_);
+ zmq_assert (!poller);
+
+ // Retrieve the poller from the thread we are running in.
+ poller = io_thread_->get_poller ();
+}
+
+void zmq::io_object_t::unplug ()
+{
+ zmq_assert (poller);
+
+ // Forget about old poller in preparation to be migrated
+ // to a different I/O thread.
+ poller = NULL;
+}
+
+zmq::io_object_t::handle_t zmq::io_object_t::add_fd (fd_t fd_)
+{
+ return poller->add_fd (fd_, this);
+}
+
+void zmq::io_object_t::rm_fd (handle_t handle_)
+{
+ poller->rm_fd (handle_);
+}
+
+void zmq::io_object_t::set_pollin (handle_t handle_)
+{
+ poller->set_pollin (handle_);
+}
+
+void zmq::io_object_t::reset_pollin (handle_t handle_)
+{
+ poller->reset_pollin (handle_);
+}
+
+void zmq::io_object_t::set_pollout (handle_t handle_)
+{
+ poller->set_pollout (handle_);
+}
+
+void zmq::io_object_t::reset_pollout (handle_t handle_)
+{
+ poller->reset_pollout (handle_);
+}
+
+void zmq::io_object_t::add_timer (int timeout_, int id_)
+{
+ poller->add_timer (timeout_, this, id_);
+}
+
+void zmq::io_object_t::cancel_timer (int id_)
+{
+ poller->cancel_timer (this, id_);
+}
+
+void zmq::io_object_t::in_event ()
+{
+ zmq_assert (false);
+}
+
+void zmq::io_object_t::out_event ()
+{
+ zmq_assert (false);
+}
+
+void zmq::io_object_t::timer_event (int id_)
+{
+ zmq_assert (false);
+}
diff --git a/src/0mq/io_object.hpp b/src/0mq/io_object.hpp
new file mode 100644
index 0000000..fb0d1e3
--- /dev/null
+++ b/src/0mq/io_object.hpp
@@ -0,0 +1,78 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_IO_OBJECT_HPP_INCLUDED__
+#define __ZMQ_IO_OBJECT_HPP_INCLUDED__
+
+#include <stddef.h>
+
+#include "stdint.hpp"
+#include "poller.hpp"
+#include "i_poll_events.hpp"
+
+namespace zmq
+{
+
+ // Simple base class for objects that live in I/O threads.
+ // It makes communication with the poller object easier and
+ // makes defining unneeded event handlers unnecessary.
+
+ class io_object_t : public i_poll_events
+ {
+ public:
+
+ io_object_t (class io_thread_t *io_thread_ = NULL);
+ ~io_object_t ();
+
+ // When migrating an object from one I/O thread to another, first
+ // unplug it, then migrate it, then plug it to the new thread.
+ void plug (class io_thread_t *io_thread_);
+ void unplug ();
+
+ protected:
+
+ typedef poller_t::handle_t handle_t;
+
+ // Methods to access underlying poller object.
+ handle_t add_fd (fd_t fd_);
+ void rm_fd (handle_t handle_);
+ void set_pollin (handle_t handle_);
+ void reset_pollin (handle_t handle_);
+ void set_pollout (handle_t handle_);
+ void reset_pollout (handle_t handle_);
+ void add_timer (int timout_, int id_);
+ void cancel_timer (int id_);
+
+ // i_poll_events interface implementation.
+ void in_event ();
+ void out_event ();
+ void timer_event (int id_);
+
+ private:
+
+ poller_t *poller;
+
+ io_object_t (const io_object_t&);
+ const io_object_t &operator = (const io_object_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/io_thread.cpp b/src/0mq/io_thread.cpp
new file mode 100644
index 0000000..bb7971d
--- /dev/null
+++ b/src/0mq/io_thread.cpp
@@ -0,0 +1,109 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <new>
+
+#include "../include/zmq.h"
+
+#include "io_thread.hpp"
+#include "platform.hpp"
+#include "err.hpp"
+#include "ctx.hpp"
+
+zmq::io_thread_t::io_thread_t (ctx_t *ctx_, uint32_t tid_) :
+ object_t (ctx_, tid_)
+{
+ poller = new (std::nothrow) poller_t;
+ alloc_assert (poller);
+
+ mailbox_handle = poller->add_fd (mailbox.get_fd (), this);
+ poller->set_pollin (mailbox_handle);
+}
+
+zmq::io_thread_t::~io_thread_t ()
+{
+ delete poller;
+}
+
+void zmq::io_thread_t::start ()
+{
+ // Start the underlying I/O thread.
+ poller->start ();
+}
+
+void zmq::io_thread_t::stop ()
+{
+ send_stop ();
+}
+
+zmq::mailbox_t *zmq::io_thread_t::get_mailbox ()
+{
+ return &mailbox;
+}
+
+int zmq::io_thread_t::get_load ()
+{
+ return poller->get_load ();
+}
+
+void zmq::io_thread_t::in_event ()
+{
+ // TODO: Do we want to limit number of commands I/O thread can
+ // process in a single go?
+
+ while (true) {
+
+ // Get the next command. If there is none, exit.
+ command_t cmd;
+ int rc = mailbox.recv (&cmd, 0);
+ if (rc != 0 && errno == EINTR)
+ continue;
+ if (rc != 0 && errno == EAGAIN)
+ break;
+ errno_assert (rc == 0);
+
+ // Process the command.
+ cmd.destination->process_command (cmd);
+ }
+}
+
+void zmq::io_thread_t::out_event ()
+{
+ // We are never polling for POLLOUT here. This function is never called.
+ zmq_assert (false);
+}
+
+void zmq::io_thread_t::timer_event (int id_)
+{
+ // No timers here. This function is never called.
+ zmq_assert (false);
+}
+
+zmq::poller_t *zmq::io_thread_t::get_poller ()
+{
+ zmq_assert (poller);
+ return poller;
+}
+
+void zmq::io_thread_t::process_stop ()
+{
+ poller->rm_fd (mailbox_handle);
+ poller->stop ();
+}
diff --git a/src/0mq/io_thread.hpp b/src/0mq/io_thread.hpp
new file mode 100644
index 0000000..f578d4e
--- /dev/null
+++ b/src/0mq/io_thread.hpp
@@ -0,0 +1,88 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_IO_THREAD_HPP_INCLUDED__
+#define __ZMQ_IO_THREAD_HPP_INCLUDED__
+
+#include <vector>
+
+#include "stdint.hpp"
+#include "object.hpp"
+#include "poller.hpp"
+#include "i_poll_events.hpp"
+#include "mailbox.hpp"
+
+namespace zmq
+{
+
+ // Generic part of the I/O thread. Polling-mechanism-specific features
+ // are implemented in separate "polling objects".
+
+ class io_thread_t : public object_t, public i_poll_events
+ {
+ public:
+
+ io_thread_t (class ctx_t *ctx_, uint32_t tid_);
+
+ // Clean-up. If the thread was started, it's neccessary to call 'stop'
+ // before invoking destructor. Otherwise the destructor would hang up.
+ ~io_thread_t ();
+
+ // Launch the physical thread.
+ void start ();
+
+ // Ask underlying thread to stop.
+ void stop ();
+
+ // Returns mailbox associated with this I/O thread.
+ mailbox_t *get_mailbox ();
+
+ // i_poll_events implementation.
+ void in_event ();
+ void out_event ();
+ void timer_event (int id_);
+
+ // Used by io_objects to retrieve the assciated poller object.
+ poller_t *get_poller ();
+
+ // Command handlers.
+ void process_stop ();
+
+ // Returns load experienced by the I/O thread.
+ int get_load ();
+
+ private:
+
+ // I/O thread accesses incoming commands via this mailbox.
+ mailbox_t mailbox;
+
+ // Handle associated with mailbox' file descriptor.
+ poller_t::handle_t mailbox_handle;
+
+ // I/O multiplexing is performed using a poller object.
+ poller_t *poller;
+
+ io_thread_t (const io_thread_t&);
+ const io_thread_t &operator = (const io_thread_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/ip.cpp b/src/0mq/ip.cpp
new file mode 100644
index 0000000..7ef698b
--- /dev/null
+++ b/src/0mq/ip.cpp
@@ -0,0 +1,369 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "ip.hpp"
+#include "err.hpp"
+#include "platform.hpp"
+#include "stdint.hpp"
+#include <stdlib.h>
+#include <string.h>
+#include <stdlib.h>
+#include <string>
+
+#if defined ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#else
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <unistd.h>
+#endif
+
+#if defined ZMQ_HAVE_OPENVMS
+#include <ioctl.h>
+#endif
+
+#if defined ZMQ_HAVE_SOLARIS
+#include <sys/sockio.h>
+#include <net/if.h>
+
+// On Solaris platform, network interface name can be queried by ioctl.
+static int resolve_nic_name (in_addr* addr_, char const *interface_)
+{
+ // Create a socket.
+ int fd = socket (AF_INET, SOCK_DGRAM, 0);
+ zmq_assert (fd != -1);
+
+ // Retrieve number of interfaces.
+ lifnum ifn;
+ ifn.lifn_family = AF_UNSPEC;
+ ifn.lifn_flags = 0;
+ int rc = ioctl (fd, SIOCGLIFNUM, (char*) &ifn);
+ zmq_assert (rc != -1);
+
+ // Allocate memory to get interface names.
+ size_t ifr_size = sizeof (struct lifreq) * ifn.lifn_count;
+ char *ifr = (char*) malloc (ifr_size);
+ alloc_assert (ifr);
+
+ // Retrieve interface names.
+ lifconf ifc;
+ ifc.lifc_family = AF_UNSPEC;
+ ifc.lifc_flags = 0;
+ ifc.lifc_len = ifr_size;
+ ifc.lifc_buf = ifr;
+ rc = ioctl (fd, SIOCGLIFCONF, (char*) &ifc);
+ zmq_assert (rc != -1);
+
+ // Find the interface with the specified name and AF_INET family.
+ bool found = false;
+ lifreq *ifrp = ifc.lifc_req;
+ for (int n = 0; n < (int) (ifc.lifc_len / sizeof (lifreq));
+ n ++, ifrp ++) {
+ if (!strcmp (interface_, ifrp->lifr_name)) {
+ rc = ioctl (fd, SIOCGLIFADDR, (char*) ifrp);
+ zmq_assert (rc != -1);
+ if (ifrp->lifr_addr.ss_family == AF_INET) {
+ *addr_ = ((sockaddr_in*) &ifrp->lifr_addr)->sin_addr;
+ found = true;
+ break;
+ }
+ }
+ }
+
+ // Clean-up.
+ free (ifr);
+ close (fd);
+
+ if (!found) {
+ errno = ENODEV;
+ return -1;
+ }
+
+ return 0;
+}
+
+#elif defined ZMQ_HAVE_AIX || defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_ANDROID
+#include <sys/ioctl.h>
+#include <net/if.h>
+
+static int resolve_nic_name (in_addr* addr_, char const *interface_)
+{
+ // Create a socket.
+ int sd = socket (AF_INET, SOCK_DGRAM, 0);
+ zmq_assert (sd != -1);
+
+ struct ifreq ifr;
+
+ // Copy interface name for ioctl get.
+ strncpy (ifr.ifr_name, interface_, sizeof (ifr.ifr_name));
+
+ // Fetch interface address.
+ int rc = ioctl (sd, SIOCGIFADDR, (caddr_t) &ifr, sizeof (struct ifreq));
+
+ // Clean up.
+ close (sd);
+
+ if (rc == -1) {
+ errno = ENODEV;
+ return -1;
+ }
+
+ struct sockaddr *sa = (struct sockaddr *) &ifr.ifr_addr;
+ *addr_ = ((sockaddr_in*)sa)->sin_addr;
+ return 0;
+}
+
+#elif ((defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_OPENBSD ||\
+ defined ZMQ_HAVE_QNXNTO || defined ZMQ_HAVE_NETBSD)\
+ && defined ZMQ_HAVE_IFADDRS)
+
+#include <ifaddrs.h>
+
+// On these platforms, network interface name can be queried
+// using getifaddrs function.
+static int resolve_nic_name (in_addr* addr_, char const *interface_)
+{
+ // Get the addresses.
+ ifaddrs* ifa = NULL;
+ int rc = getifaddrs (&ifa);
+ zmq_assert (rc == 0);
+ zmq_assert (ifa != NULL);
+
+ // Find the corresponding network interface.
+ bool found = false;
+ for (ifaddrs *ifp = ifa; ifp != NULL ;ifp = ifp->ifa_next)
+ if (ifp->ifa_addr && ifp->ifa_addr->sa_family == AF_INET
+ && !strcmp (interface_, ifp->ifa_name))
+ {
+ *addr_ = ((sockaddr_in*) ifp->ifa_addr)->sin_addr;
+ found = true;
+ break;
+ }
+
+ // Clean-up;
+ freeifaddrs (ifa);
+
+ if (!found) {
+ errno = ENODEV;
+ return -1;
+ }
+
+ return 0;
+}
+
+#else
+
+// On other platforms we assume there are no sane interface names.
+// This is true especially of Windows.
+static int resolve_nic_name (in_addr* addr_, char const *interface_)
+{
+ errno = ENODEV;
+ return -1;
+}
+
+#endif
+
+int zmq::open_socket (int domain_, int type_, int protocol_)
+{
+ // Setting this option result in sane behaviour when exec() functions
+ // are used. Old sockets are closed and don't block TCP ports etc.
+#if defined HAVE_SOCK_CLOEXEC
+ type_ |= SOCK_CLOEXEC;
+#endif
+
+ int s = socket (domain_, type_, protocol_);
+ if (s == -1)
+ return -1;
+
+ // If there's no SOCK_CLOEXEC, let's try the second best option. Note that
+ // race condition can cause socket not to be closed (if fork happens
+ // between socket creation and this point).
+#if !defined HAVE_SOCK_CLOEXEC && defined FD_CLOEXEC
+ int rc = fcntl (s, F_SETFD, FD_CLOEXEC);
+ errno_assert (rc != -1);
+#endif
+
+ return s;
+}
+
+int zmq::resolve_ip_interface (sockaddr_storage* addr_, socklen_t *addr_len_,
+ char const *interface_)
+{
+ // Find the ':' at end that separates NIC name from service.
+ const char *delimiter = strrchr (interface_, ':');
+ if (!delimiter) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ // Separate the name/port.
+ std::string iface (interface_, delimiter - interface_);
+ std::string service (delimiter + 1);
+
+ // Initialize the output parameter.
+ memset (addr_, 0, sizeof (*addr_));
+
+ // Initialise IPv4-format family/port.
+ sockaddr_in ip4_addr;
+ memset (&ip4_addr, 0, sizeof (ip4_addr));
+ ip4_addr.sin_family = AF_INET;
+ ip4_addr.sin_port = htons ((uint16_t) atoi (service.c_str()));
+
+ // Initialize temporary output pointers with ip4_addr
+ sockaddr *out_addr = (sockaddr *) &ip4_addr;
+ size_t out_addrlen = sizeof (ip4_addr);
+
+ // 0 is not a valid port.
+ if (!ip4_addr.sin_port) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ // * resolves to INADDR_ANY.
+ if (iface.compare("*") == 0) {
+ ip4_addr.sin_addr.s_addr = htonl (INADDR_ANY);
+ zmq_assert (out_addrlen <= sizeof (*addr_));
+ memcpy (addr_, out_addr, out_addrlen);
+ *addr_len_ = out_addrlen;
+ return 0;
+ }
+
+ // Try to resolve the string as a NIC name.
+ int rc = resolve_nic_name (&ip4_addr.sin_addr, iface.c_str());
+ if (rc != 0 && errno != ENODEV)
+ return rc;
+ if (rc == 0) {
+ zmq_assert (out_addrlen <= sizeof (*addr_));
+ memcpy (addr_, out_addr, out_addrlen);
+ *addr_len_ = out_addrlen;
+ return 0;
+ }
+
+ // There's no such interface name. Assume literal address.
+#if defined ZMQ_HAVE_OPENVMS && defined __ia64
+ __addrinfo64 *res = NULL;
+ __addrinfo64 req;
+#else
+ addrinfo *res = NULL;
+ addrinfo req;
+#endif
+ memset (&req, 0, sizeof (req));
+
+ // We only support IPv4 addresses for now.
+ req.ai_family = AF_INET;
+
+ // Arbitrary, not used in the output, but avoids duplicate results.
+ req.ai_socktype = SOCK_STREAM;
+
+ // Restrict hostname/service to literals to avoid any DNS lookups or
+ // service-name irregularity due to indeterminate socktype.
+ req.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV;
+
+ // Resolve the literal address. Some of the error info is lost in case
+ // of error, however, there's no way to report EAI errors via errno.
+ rc = getaddrinfo (iface.c_str(), service.c_str(), &req, &res);
+ if (rc) {
+ errno = ENODEV;
+ return -1;
+ }
+
+ // Use the first result.
+ zmq_assert ((size_t) (res->ai_addrlen) <= sizeof (*addr_));
+ memcpy (addr_, res->ai_addr, res->ai_addrlen);
+ *addr_len_ = res->ai_addrlen;
+
+ // Cleanup getaddrinfo after copying the possibly referenced result.
+ if (res)
+ freeaddrinfo (res);
+
+ return 0;
+}
+
+int zmq::resolve_ip_hostname (sockaddr_storage *addr_, socklen_t *addr_len_,
+ const char *hostname_)
+{
+ // Find the ':' that separates hostname name from service.
+ const char *delimiter = strchr (hostname_, ':');
+ if (!delimiter) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ // Separate the hostname and service.
+ std::string hostname (hostname_, delimiter - hostname_);
+ std::string service (delimiter + 1);
+
+ // Set up the query.
+ addrinfo req;
+ memset (&req, 0, sizeof (req));
+
+ // We only support IPv4 addresses for now.
+ req.ai_family = AF_INET;
+
+ // Need to choose one to avoid duplicate results from getaddrinfo() - this
+ // doesn't really matter, since it's not included in the addr-output.
+ req.ai_socktype = SOCK_STREAM;
+
+ // Avoid named services due to unclear socktype.
+ req.ai_flags = AI_NUMERICSERV;
+
+ // Resolve host name. Some of the error info is lost in case of error,
+ // however, there's no way to report EAI errors via errno.
+ addrinfo *res;
+ int rc = getaddrinfo (hostname.c_str (), service.c_str (), &req, &res);
+ if (rc) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ // Copy first result to output addr with hostname and service.
+ zmq_assert ((size_t) (res->ai_addrlen) <= sizeof (*addr_));
+ memcpy (addr_, res->ai_addr, res->ai_addrlen);
+ *addr_len_ = res->ai_addrlen;
+
+ freeaddrinfo (res);
+
+ return 0;
+}
+
+int zmq::resolve_local_path (sockaddr_storage *addr_, socklen_t *addr_len_,
+ const char *path_)
+{
+#if defined ZMQ_HAVE_WINDOWS || defined ZMQ_HAVE_OPENVMS
+ errno = EPROTONOSUPPORT;
+ return -1;
+#else
+ sockaddr_un *un = (sockaddr_un*) addr_;
+ if (strlen (path_) >= sizeof (un->sun_path))
+ {
+ errno = ENAMETOOLONG;
+ return -1;
+ }
+ strcpy (un->sun_path, path_);
+ un->sun_family = AF_UNIX;
+ *addr_len_ = sizeof (sockaddr_un);
+ return 0;
+#endif
+}
+
diff --git a/src/0mq/ip.hpp b/src/0mq/ip.hpp
new file mode 100644
index 0000000..1d44325
--- /dev/null
+++ b/src/0mq/ip.hpp
@@ -0,0 +1,70 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_IP_HPP_INCLUDED__
+#define __ZMQ_IP_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#else
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#endif
+
+#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS
+#include <sys/un.h>
+#endif
+
+// Some platforms (notably Darwin/OSX and NetBSD) do not define all AI_
+// flags for getaddrinfo(). This can be worked around safely by defining
+// these to 0.
+#ifndef AI_ADDRCONFIG
+#define AI_ADDRCONFIG 0
+#endif
+#ifndef AI_NUMERICSERV
+#define AI_NUMERICSERV 0
+#endif
+
+namespace zmq
+{
+ // Same as socket(2), but allows for transparent tweaking the options.
+ int open_socket (int domain_, int type_, int protocol_);
+
+ // Resolves network interface name in <nic-name>:<port> format. Symbol "*"
+ // (asterisk) resolves to INADDR_ANY (all network interfaces).
+ int resolve_ip_interface (sockaddr_storage *addr_, socklen_t *addr_len_,
+ char const *interface_);
+
+ // This function resolves a string in <hostname>:<port-number> format.
+ // Hostname can be either the name of the host or its IP address.
+ int resolve_ip_hostname (sockaddr_storage *addr_, socklen_t *addr_len_,
+ const char *hostname_);
+
+ // This function sets up address for UNIX domain transport.
+ int resolve_local_path (sockaddr_storage *addr_, socklen_t *addr_len_,
+ const char* pathname_);
+}
+
+#endif
diff --git a/src/0mq/kqueue.cpp b/src/0mq/kqueue.cpp
new file mode 100644
index 0000000..fe4b65d
--- /dev/null
+++ b/src/0mq/kqueue.cpp
@@ -0,0 +1,203 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_FREEBSD || defined ZMQ_HAVE_OPENBSD ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_NETBSD
+
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/event.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <algorithm>
+#include <new>
+
+#include "kqueue.hpp"
+#include "err.hpp"
+#include "config.hpp"
+#include "i_poll_events.hpp"
+#include "likely.hpp"
+
+// NetBSD defines (struct kevent).udata as intptr_t, everyone else
+// as void *.
+#if defined ZMQ_HAVE_NETBSD
+#define kevent_udata_t intptr_t
+#else
+#define kevent_udata_t void *
+#endif
+
+zmq::kqueue_t::kqueue_t () :
+ stopping (false)
+{
+ // Create event queue
+ kqueue_fd = kqueue ();
+ errno_assert (kqueue_fd != -1);
+}
+
+zmq::kqueue_t::~kqueue_t ()
+{
+ worker.stop ();
+ close (kqueue_fd);
+}
+
+void zmq::kqueue_t::kevent_add (fd_t fd_, short filter_, void *udata_)
+{
+ struct kevent ev;
+
+ EV_SET (&ev, fd_, filter_, EV_ADD, 0, 0, (kevent_udata_t)udata_);
+ int rc = kevent (kqueue_fd, &ev, 1, NULL, 0, NULL);
+ errno_assert (rc != -1);
+}
+
+void zmq::kqueue_t::kevent_delete (fd_t fd_, short filter_)
+{
+ struct kevent ev;
+
+ EV_SET (&ev, fd_, filter_, EV_DELETE, 0, 0, 0);
+ int rc = kevent (kqueue_fd, &ev, 1, NULL, 0, NULL);
+ errno_assert (rc != -1);
+}
+
+zmq::kqueue_t::handle_t zmq::kqueue_t::add_fd (fd_t fd_,
+ i_poll_events *reactor_)
+{
+ poll_entry_t *pe = new (std::nothrow) poll_entry_t;
+ alloc_assert (pe);
+
+ pe->fd = fd_;
+ pe->flag_pollin = 0;
+ pe->flag_pollout = 0;
+ pe->reactor = reactor_;
+
+ adjust_load (1);
+
+ return pe;
+}
+
+void zmq::kqueue_t::rm_fd (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ if (pe->flag_pollin)
+ kevent_delete (pe->fd, EVFILT_READ);
+ if (pe->flag_pollout)
+ kevent_delete (pe->fd, EVFILT_WRITE);
+ pe->fd = retired_fd;
+ retired.push_back (pe);
+
+ adjust_load (-1);
+}
+
+void zmq::kqueue_t::set_pollin (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ if (likely (!pe->flag_pollin)) {
+ pe->flag_pollin = true;
+ kevent_add (pe->fd, EVFILT_READ, pe);
+ }
+}
+
+void zmq::kqueue_t::reset_pollin (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ if (likely (pe->flag_pollin)) {
+ pe->flag_pollin = false;
+ kevent_delete (pe->fd, EVFILT_READ);
+ }
+}
+
+void zmq::kqueue_t::set_pollout (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ if (likely (!pe->flag_pollout)) {
+ pe->flag_pollout = true;
+ kevent_add (pe->fd, EVFILT_WRITE, pe);
+ }
+}
+
+void zmq::kqueue_t::reset_pollout (handle_t handle_)
+{
+ poll_entry_t *pe = (poll_entry_t*) handle_;
+ if (likely (pe->flag_pollout)) {
+ pe->flag_pollout = false;
+ kevent_delete (pe->fd, EVFILT_WRITE);
+ }
+}
+
+void zmq::kqueue_t::start ()
+{
+ worker.start (worker_routine, this);
+}
+
+void zmq::kqueue_t::stop ()
+{
+ stopping = true;
+}
+
+void zmq::kqueue_t::loop ()
+{
+ while (!stopping) {
+
+ // Execute any due timers.
+ int timeout = (int) execute_timers ();
+
+ // Wait for events.
+ struct kevent ev_buf [max_io_events];
+ timespec ts = {timeout / 1000, (timeout % 1000) * 1000000};
+ int n = kevent (kqueue_fd, NULL, 0, &ev_buf [0], max_io_events,
+ timeout ? &ts: NULL);
+ if (n == -1 && errno == EINTR)
+ continue;
+ errno_assert (n != -1);
+
+ for (int i = 0; i < n; i ++) {
+ poll_entry_t *pe = (poll_entry_t*) ev_buf [i].udata;
+
+ if (pe->fd == retired_fd)
+ continue;
+ if (ev_buf [i].flags & EV_EOF)
+ pe->reactor->in_event ();
+ if (pe->fd == retired_fd)
+ continue;
+ if (ev_buf [i].filter == EVFILT_WRITE)
+ pe->reactor->out_event ();
+ if (pe->fd == retired_fd)
+ continue;
+ if (ev_buf [i].filter == EVFILT_READ)
+ pe->reactor->in_event ();
+ }
+
+ // Destroy retired event sources.
+ for (retired_t::iterator it = retired.begin (); it != retired.end ();
+ ++it)
+ delete *it;
+ retired.clear ();
+ }
+}
+
+void zmq::kqueue_t::worker_routine (void *arg_)
+{
+ ((kqueue_t*) arg_)->loop ();
+}
+
+// Don't pollute namespace with defines local to this file
+#undef kevent_udata_t
+#endif
diff --git a/src/0mq/kqueue.hpp b/src/0mq/kqueue.hpp
new file mode 100644
index 0000000..d564c7c
--- /dev/null
+++ b/src/0mq/kqueue.hpp
@@ -0,0 +1,103 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_KQUEUE_HPP_INCLUDED__
+#define __ZMQ_KQUEUE_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_FREEBSD || defined ZMQ_HAVE_OPENBSD ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_NETBSD
+
+#include <vector>
+
+#include "fd.hpp"
+#include "thread.hpp"
+#include "poller_base.hpp"
+
+namespace zmq
+{
+
+ // Implements socket polling mechanism using the BSD-specific
+ // kqueue interface.
+
+ class kqueue_t : public poller_base_t
+ {
+ public:
+
+ typedef void* handle_t;
+
+ kqueue_t ();
+ ~kqueue_t ();
+
+ // "poller" concept.
+ handle_t add_fd (fd_t fd_, struct i_poll_events *events_);
+ void rm_fd (handle_t handle_);
+ void set_pollin (handle_t handle_);
+ void reset_pollin (handle_t handle_);
+ void set_pollout (handle_t handle_);
+ void reset_pollout (handle_t handle_);
+ void start ();
+ void stop ();
+
+ private:
+
+ // Main worker thread routine.
+ static void worker_routine (void *arg_);
+
+ // Main event loop.
+ void loop ();
+
+ // File descriptor referring to the kernel event queue.
+ fd_t kqueue_fd;
+
+ // Adds the event to the kqueue.
+ void kevent_add (fd_t fd_, short filter_, void *udata_);
+
+ // Deletes the event from the kqueue.
+ void kevent_delete (fd_t fd_, short filter_);
+
+ struct poll_entry_t
+ {
+ fd_t fd;
+ bool flag_pollin;
+ bool flag_pollout;
+ i_poll_events *reactor;
+ };
+
+ // List of retired event sources.
+ typedef std::vector <poll_entry_t*> retired_t;
+ retired_t retired;
+
+ // If true, thread is in the process of shutting down.
+ bool stopping;
+
+ // Handle of the physical thread doing the I/O work.
+ thread_t worker;
+
+ kqueue_t (const kqueue_t&);
+ const kqueue_t &operator = (const kqueue_t&);
+ };
+
+}
+
+#endif
+
+#endif
diff --git a/src/0mq/lb.cpp b/src/0mq/lb.cpp
new file mode 100644
index 0000000..95af4a1
--- /dev/null
+++ b/src/0mq/lb.cpp
@@ -0,0 +1,174 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "lb.hpp"
+#include "pipe.hpp"
+#include "err.hpp"
+#include "own.hpp"
+
+zmq::lb_t::lb_t (own_t *sink_) :
+ active (0),
+ current (0),
+ more (false),
+ dropping (false),
+ sink (sink_),
+ terminating (false)
+{
+}
+
+zmq::lb_t::~lb_t ()
+{
+ zmq_assert (pipes.empty ());
+}
+
+void zmq::lb_t::attach (writer_t *pipe_)
+{
+ pipe_->set_event_sink (this);
+
+ pipes.push_back (pipe_);
+ pipes.swap (active, pipes.size () - 1);
+ active++;
+
+ if (terminating) {
+ sink->register_term_acks (1);
+ pipe_->terminate ();
+ }
+}
+
+void zmq::lb_t::terminate ()
+{
+ zmq_assert (!terminating);
+ terminating = true;
+
+ sink->register_term_acks (pipes.size ());
+ for (pipes_t::size_type i = 0; i != pipes.size (); i++)
+ pipes [i]->terminate ();
+}
+
+void zmq::lb_t::terminated (writer_t *pipe_)
+{
+ pipes_t::size_type index = pipes.index (pipe_);
+
+ // If we are in the middle of multipart message and current pipe
+ // have disconnected, we have to drop the remainder of the message.
+ if (index == current && more)
+ dropping = true;
+
+ // Remove the pipe from the list; adjust number of active pipes
+ // accordingly.
+ if (index < active) {
+ active--;
+ if (current == active)
+ current = 0;
+ }
+ pipes.erase (pipe_);
+
+ if (terminating)
+ sink->unregister_term_ack ();
+}
+
+void zmq::lb_t::activated (writer_t *pipe_)
+{
+ // Move the pipe to the list of active pipes.
+ pipes.swap (pipes.index (pipe_), active);
+ active++;
+}
+
+int zmq::lb_t::send (zmq_msg_t *msg_, int flags_)
+{
+ // Drop the message if required. If we are at the end of the message
+ // switch back to non-dropping mode.
+ if (dropping) {
+
+ more = msg_->flags & ZMQ_MSG_MORE;
+ if (!more)
+ dropping = false;
+
+ int rc = zmq_msg_close (msg_);
+ errno_assert (rc == 0);
+ rc = zmq_msg_init (msg_);
+ zmq_assert (rc == 0);
+ return 0;
+ }
+
+ while (active > 0) {
+ if (pipes [current]->write (msg_)) {
+ more = msg_->flags & ZMQ_MSG_MORE;
+ break;
+ }
+
+ zmq_assert (!more);
+ active--;
+ if (current < active)
+ pipes.swap (current, active);
+ else
+ current = 0;
+ }
+
+ // If there are no pipes we cannot send the message.
+ if (active == 0) {
+ errno = EAGAIN;
+ return -1;
+ }
+
+ // If it's final part of the message we can fluch it downstream and
+ // continue round-robinning (load balance).
+ if (!more) {
+ pipes [current]->flush ();
+ current = (current + 1) % active;
+ }
+
+ // Detach the message from the data buffer.
+ int rc = zmq_msg_init (msg_);
+ zmq_assert (rc == 0);
+
+ return 0;
+}
+
+bool zmq::lb_t::has_out ()
+{
+ // If one part of the message was already written we can definitely
+ // write the rest of the message.
+ if (more)
+ return true;
+
+ while (active > 0) {
+
+ // Check whether zero-sized message can be written to the pipe.
+ zmq_msg_t msg;
+ zmq_msg_init (&msg);
+ if (pipes [current]->check_write (&msg)) {
+ zmq_msg_close (&msg);
+ return true;
+ }
+ zmq_msg_close (&msg);
+
+ // Deactivate the pipe.
+ active--;
+ pipes.swap (current, active);
+ if (current == active)
+ current = 0;
+ }
+
+ return false;
+}
+
diff --git a/src/0mq/lb.hpp b/src/0mq/lb.hpp
new file mode 100644
index 0000000..0dc11e2
--- /dev/null
+++ b/src/0mq/lb.hpp
@@ -0,0 +1,79 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_LB_HPP_INCLUDED__
+#define __ZMQ_LB_HPP_INCLUDED__
+
+#include "array.hpp"
+#include "pipe.hpp"
+
+namespace zmq
+{
+
+ // Class manages a set of outbound pipes. On send it load balances
+ // messages fairly among the pipes.
+ class lb_t : public i_writer_events
+ {
+ public:
+
+ lb_t (class own_t *sink_);
+ ~lb_t ();
+
+ void attach (writer_t *pipe_);
+ void terminate ();
+ int send (zmq_msg_t *msg_, int flags_);
+ bool has_out ();
+
+ // i_writer_events interface implementation.
+ void activated (writer_t *pipe_);
+ void terminated (writer_t *pipe_);
+
+ private:
+
+ // List of outbound pipes.
+ typedef array_t <class writer_t> pipes_t;
+ pipes_t pipes;
+
+ // Number of active pipes. All the active pipes are located at the
+ // beginning of the pipes array.
+ pipes_t::size_type active;
+
+ // Points to the last pipe that the most recent message was sent to.
+ pipes_t::size_type current;
+
+ // True if last we are in the middle of a multipart message.
+ bool more;
+
+ // True if we are dropping current message.
+ bool dropping;
+
+ // Object to send events to.
+ class own_t *sink;
+
+ // If true, termination process is already underway.
+ bool terminating;
+
+ lb_t (const lb_t&);
+ const lb_t &operator = (const lb_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/libzmq.pc.in b/src/0mq/libzmq.pc.in
new file mode 100644
index 0000000..ba155a3
--- /dev/null
+++ b/src/0mq/libzmq.pc.in
@@ -0,0 +1,10 @@
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libzmq
+Description: 0MQ c++ library
+Version: @VERSION@
+Libs: -L${libdir} -lzmq
+Cflags: -I${includedir}
diff --git a/src/0mq/likely.hpp b/src/0mq/likely.hpp
new file mode 100644
index 0000000..a524a50
--- /dev/null
+++ b/src/0mq/likely.hpp
@@ -0,0 +1,33 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_LIKELY_HPP_INCLUDED__
+#define __ZMQ_LIKELY_HPP_INCLUDED__
+
+#if defined __GNUC__
+#define likely(x) __builtin_expect ((x), 1)
+#define unlikely(x) __builtin_expect ((x), 0)
+#else
+#define likely(x) (x)
+#define unlikely(x) (x)
+#endif
+
+
+#endif
diff --git a/src/0mq/mailbox.cpp b/src/0mq/mailbox.cpp
new file mode 100644
index 0000000..24fa739
--- /dev/null
+++ b/src/0mq/mailbox.cpp
@@ -0,0 +1,87 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "mailbox.hpp"
+#include "platform.hpp"
+#include "err.hpp"
+
+zmq::mailbox_t::mailbox_t ()
+{
+ // 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
+ // new command is posted.
+ bool ok = cpipe.read (NULL);
+ zmq_assert (!ok);
+ active = false;
+}
+
+zmq::mailbox_t::~mailbox_t ()
+{
+ // TODO: Retrieve and deallocate commands inside the cpipe.
+
+ // Work around problem that other threads might still be in our
+ // send() method, by waiting on the mutex before disappearing.
+ sync.lock ();
+ sync.unlock ();
+}
+
+zmq::fd_t zmq::mailbox_t::get_fd ()
+{
+ return signaler.get_fd ();
+}
+
+void zmq::mailbox_t::send (const command_t &cmd_)
+{
+ sync.lock ();
+ cpipe.write (cmd_, false);
+ bool ok = cpipe.flush ();
+ sync.unlock ();
+ if (!ok)
+ signaler.send ();
+}
+
+int zmq::mailbox_t::recv (command_t *cmd_, int timeout_)
+{
+ // Try to get the command straight away.
+ if (active) {
+ bool ok = cpipe.read (cmd_);
+ if (ok)
+ return 0;
+
+ // If there are no more commands available, switch into passive state.
+ active = false;
+ signaler.recv ();
+ }
+
+ // Wait for signal from the command sender.
+ int rc = signaler.wait (timeout_);
+ if (rc != 0 && (errno == EAGAIN || errno == EINTR))
+ return -1;
+
+ // We've got the signal. Now we can switch into active state.
+ active = true;
+
+ // Get a command.
+ errno_assert (rc == 0);
+ bool ok = cpipe.read (cmd_);
+ zmq_assert (ok);
+ return 0;
+}
+
diff --git a/src/0mq/mailbox.hpp b/src/0mq/mailbox.hpp
new file mode 100644
index 0000000..0675b99
--- /dev/null
+++ b/src/0mq/mailbox.hpp
@@ -0,0 +1,74 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_MAILBOX_HPP_INCLUDED__
+#define __ZMQ_MAILBOX_HPP_INCLUDED__
+
+#include <stddef.h>
+
+#include "platform.hpp"
+#include "signaler.hpp"
+#include "fd.hpp"
+#include "config.hpp"
+#include "command.hpp"
+#include "ypipe.hpp"
+#include "mutex.hpp"
+
+namespace zmq
+{
+
+ class mailbox_t
+ {
+ public:
+
+ mailbox_t ();
+ ~mailbox_t ();
+
+ fd_t get_fd ();
+ void send (const command_t &cmd_);
+ int recv (command_t *cmd_, int timeout_);
+
+ private:
+
+ // The pipe to store actual commands.
+ typedef ypipe_t <command_t, command_pipe_granularity> cpipe_t;
+ cpipe_t cpipe;
+
+ // Signaler to pass signals from writer thread to reader thread.
+ signaler_t signaler;
+
+ // There's only one thread receiving from the mailbox, but there
+ // is arbitrary number of threads sending. Given that ypipe requires
+ // synchronised access on both of its endpoints, we have to synchronise
+ // the sending side.
+ mutex_t sync;
+
+ // True if the underlying pipe is active, ie. when we are allowed to
+ // read commands from it.
+ bool active;
+
+ // Disable copying of mailbox_t object.
+ mailbox_t (const mailbox_t&);
+ const mailbox_t &operator = (const mailbox_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/msg_content.hpp b/src/0mq/msg_content.hpp
new file mode 100644
index 0000000..7e22098
--- /dev/null
+++ b/src/0mq/msg_content.hpp
@@ -0,0 +1,52 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_MSG_HPP_INCLUDE__
+#define __ZMQ_MSG_HPP_INCLUDE__
+
+#include <stddef.h>
+
+#include "../include/zmq.h"
+
+#include "atomic_counter.hpp"
+
+namespace zmq
+{
+
+ // Shared message buffer. Message data are either allocated in one
+ // continuous block along with this structure - thus avoiding one
+ // malloc/free pair or they are stored in used-supplied memory.
+ // In the latter case, ffn member stores pointer to the function to be
+ // used to deallocate the data. If the buffer is actually shared (there
+ // are at least 2 references to it) refcount member contains number of
+ // references.
+
+ struct msg_content_t
+ {
+ void *data;
+ size_t size;
+ zmq_free_fn *ffn;
+ void *hint;
+ zmq::atomic_counter_t refcnt;
+ };
+
+}
+
+#endif
diff --git a/src/0mq/mutex.hpp b/src/0mq/mutex.hpp
new file mode 100644
index 0000000..9b13ffa
--- /dev/null
+++ b/src/0mq/mutex.hpp
@@ -0,0 +1,121 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_MUTEX_HPP_INCLUDED__
+#define __ZMQ_MUTEX_HPP_INCLUDED__
+
+#include "platform.hpp"
+#include "err.hpp"
+
+// Mutex class encapsulates OS mutex in a platform-independent way.
+
+#ifdef ZMQ_HAVE_WINDOWS
+
+#include "windows.hpp"
+
+namespace zmq
+{
+
+ class mutex_t
+ {
+ public:
+ inline mutex_t ()
+ {
+ InitializeCriticalSection (&cs);
+ }
+
+ inline ~mutex_t ()
+ {
+ DeleteCriticalSection (&cs);
+ }
+
+ inline void lock ()
+ {
+ EnterCriticalSection (&cs);
+ }
+
+ inline void unlock ()
+ {
+ LeaveCriticalSection (&cs);
+ }
+
+ private:
+
+ CRITICAL_SECTION cs;
+
+ // Disable copy construction and assignment.
+ mutex_t (const mutex_t&);
+ void operator = (const mutex_t&);
+ };
+
+}
+
+#else
+
+#include <pthread.h>
+
+namespace zmq
+{
+
+ class mutex_t
+ {
+ public:
+ inline mutex_t ()
+ {
+ int rc = pthread_mutex_init (&mutex, NULL);
+ if (rc)
+ posix_assert (rc);
+ }
+
+ inline ~mutex_t ()
+ {
+ int rc = pthread_mutex_destroy (&mutex);
+ if (rc)
+ posix_assert (rc);
+ }
+
+ inline void lock ()
+ {
+ int rc = pthread_mutex_lock (&mutex);
+ if (rc)
+ posix_assert (rc);
+ }
+
+ inline void unlock ()
+ {
+ int rc = pthread_mutex_unlock (&mutex);
+ if (rc)
+ posix_assert (rc);
+ }
+
+ private:
+
+ pthread_mutex_t mutex;
+
+ // Disable copy construction and assignment.
+ mutex_t (const mutex_t&);
+ const mutex_t &operator = (const mutex_t&);
+ };
+
+}
+
+#endif
+
+#endif
diff --git a/src/0mq/named_session.cpp b/src/0mq/named_session.cpp
new file mode 100644
index 0000000..2532c5a
--- /dev/null
+++ b/src/0mq/named_session.cpp
@@ -0,0 +1,85 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "named_session.hpp"
+#include "socket_base.hpp"
+
+zmq::named_session_t::named_session_t (class io_thread_t *io_thread_,
+ socket_base_t *socket_, const options_t &options_,
+ const blob_t &name_) :
+ session_t (io_thread_, socket_, options_),
+ name (name_)
+{
+ // Make double sure that the session has valid name.
+ zmq_assert (!name.empty ());
+ zmq_assert (name [0] != 0);
+
+ if (!socket_->register_session (name, this)) {
+
+ // TODO: There's already a session with the specified
+ // identity. We should log the error and drop the
+ // session.
+ zmq_assert (false);
+ }
+}
+
+zmq::named_session_t::~named_session_t ()
+{
+ // Unregister the session from the global list of named sessions.
+ if (!name.empty ())
+ unregister_session (name);
+}
+
+void zmq::named_session_t::attached (const blob_t &peer_identity_)
+{
+ if (!name.empty ()) {
+
+ // If both IDs are temporary, no checking is needed.
+ // TODO: Old ID should be reused in this case...
+ if (name.empty () || name [0] != 0 ||
+ peer_identity_.empty () || peer_identity_ [0] != 0) {
+
+ // If we already know the peer name do nothing, just check whether
+ // it haven't changed.
+ zmq_assert (name == peer_identity_);
+ }
+ }
+ else if (!peer_identity_.empty ()) {
+
+ // Store the peer identity.
+ name = peer_identity_;
+
+ // Register the session using the peer name.
+ if (!register_session (name, this)) {
+
+ // TODO: There's already a session with the specified
+ // identity. We should presumably syslog it and drop the
+ // session.
+ zmq_assert (false);
+ }
+ }
+}
+
+void zmq::named_session_t::detached ()
+{
+ // Do nothing. Named sessions are never destroyed because of disconnection,
+ // neither they have to actively reconnect.
+}
+
diff --git a/src/0mq/named_session.hpp b/src/0mq/named_session.hpp
new file mode 100644
index 0000000..cf31209
--- /dev/null
+++ b/src/0mq/named_session.hpp
@@ -0,0 +1,57 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_NAMED_SESSION_HPP_INCLUDED__
+#define __ZMQ_NAMED_SESSION_HPP_INCLUDED__
+
+#include "session.hpp"
+#include "blob.hpp"
+
+namespace zmq
+{
+
+ // Named session is created by listener object when the peer identifies
+ // itself by a strong name. Named session survives reconnections.
+
+ class named_session_t : public session_t
+ {
+ public:
+
+ named_session_t (class io_thread_t *io_thread_,
+ class socket_base_t *socket_, const options_t &options_,
+ const blob_t &name_);
+ ~named_session_t ();
+
+ // Handlers for events from session base class.
+ void attached (const blob_t &peer_identity_);
+ void detached ();
+
+ private:
+
+ // Name of the session. Corresponds to the peer's strong identity.
+ blob_t name;
+
+ named_session_t (const named_session_t&);
+ const named_session_t &operator = (const named_session_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/object.cpp b/src/0mq/object.cpp
new file mode 100644
index 0000000..e2ca6d6
--- /dev/null
+++ b/src/0mq/object.cpp
@@ -0,0 +1,467 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <string.h>
+#include <stdarg.h>
+
+#include "object.hpp"
+#include "ctx.hpp"
+#include "err.hpp"
+#include "pipe.hpp"
+#include "io_thread.hpp"
+#include "session.hpp"
+#include "socket_base.hpp"
+
+zmq::object_t::object_t (ctx_t *ctx_, uint32_t tid_) :
+ ctx (ctx_),
+ tid (tid_)
+{
+}
+
+zmq::object_t::object_t (object_t *parent_) :
+ ctx (parent_->ctx),
+ tid (parent_->tid)
+{
+}
+
+zmq::object_t::~object_t ()
+{
+}
+
+uint32_t zmq::object_t::get_tid ()
+{
+ return tid;
+}
+
+zmq::ctx_t *zmq::object_t::get_ctx ()
+{
+ return ctx;
+}
+
+void zmq::object_t::process_command (command_t &cmd_)
+{
+ switch (cmd_.type) {
+
+ case command_t::activate_reader:
+ process_activate_reader ();
+ break;
+
+ case command_t::activate_writer:
+ process_activate_writer (cmd_.args.activate_writer.msgs_read);
+ break;
+
+ case command_t::stop:
+ process_stop ();
+ break;
+
+ case command_t::plug:
+ process_plug ();
+ process_seqnum ();
+ return;
+
+ case command_t::own:
+ process_own (cmd_.args.own.object);
+ process_seqnum ();
+ break;
+
+ case command_t::attach:
+ process_attach (cmd_.args.attach.engine,
+ cmd_.args.attach.peer_identity ?
+ blob_t (cmd_.args.attach.peer_identity,
+ cmd_.args.attach.peer_identity_size) : blob_t ());
+ process_seqnum ();
+ break;
+
+ case command_t::bind:
+ process_bind (cmd_.args.bind.in_pipe, cmd_.args.bind.out_pipe,
+ cmd_.args.bind.peer_identity ? blob_t (cmd_.args.bind.peer_identity,
+ cmd_.args.bind.peer_identity_size) : blob_t ());
+ process_seqnum ();
+ break;
+
+ case command_t::pipe_term:
+ process_pipe_term ();
+ return;
+
+ case command_t::pipe_term_ack:
+ process_pipe_term_ack ();
+ break;
+
+ case command_t::term_req:
+ process_term_req (cmd_.args.term_req.object);
+ break;
+
+ case command_t::term:
+ process_term (cmd_.args.term.linger);
+ break;
+
+ case command_t::term_ack:
+ process_term_ack ();
+ break;
+
+ case command_t::reap:
+ process_reap (cmd_.args.reap.socket);
+ break;
+
+ case command_t::reaped:
+ process_reaped ();
+ break;
+
+ default:
+ zmq_assert (false);
+ }
+
+ // The assumption here is that each command is processed once only,
+ // so deallocating it after processing is all right.
+ deallocate_command (&cmd_);
+}
+
+int zmq::object_t::register_endpoint (const char *addr_, endpoint_t &endpoint_)
+{
+ return ctx->register_endpoint (addr_, endpoint_);
+}
+
+void zmq::object_t::unregister_endpoints (socket_base_t *socket_)
+{
+ return ctx->unregister_endpoints (socket_);
+}
+
+zmq::endpoint_t zmq::object_t::find_endpoint (const char *addr_)
+{
+ return ctx->find_endpoint (addr_);
+}
+
+void zmq::object_t::destroy_socket (socket_base_t *socket_)
+{
+ ctx->destroy_socket (socket_);
+}
+
+void zmq::object_t::log (const char *format_, ...)
+{
+ va_list args;
+ va_start (args, format_);
+ ctx->log (format_, args);
+ va_end (args);
+}
+
+zmq::io_thread_t *zmq::object_t::choose_io_thread (uint64_t affinity_)
+{
+ return ctx->choose_io_thread (affinity_);
+}
+
+void zmq::object_t::send_stop ()
+{
+ // 'stop' command goes always from administrative thread to
+ // the current object.
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = this;
+ cmd.type = command_t::stop;
+ ctx->send_command (tid, cmd);
+}
+
+void zmq::object_t::send_plug (own_t *destination_, bool inc_seqnum_)
+{
+ if (inc_seqnum_)
+ destination_->inc_seqnum ();
+
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::plug;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_own (own_t *destination_, own_t *object_)
+{
+ destination_->inc_seqnum ();
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::own;
+ cmd.args.own.object = object_;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_attach (session_t *destination_, i_engine *engine_,
+ const blob_t &peer_identity_, bool inc_seqnum_)
+{
+ if (inc_seqnum_)
+ destination_->inc_seqnum ();
+
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::attach;
+ cmd.args.attach.engine = engine_;
+ if (peer_identity_.empty ()) {
+ cmd.args.attach.peer_identity_size = 0;
+ cmd.args.attach.peer_identity = NULL;
+ }
+ else {
+ zmq_assert (peer_identity_.size () <= 0xff);
+ cmd.args.attach.peer_identity_size =
+ (unsigned char) peer_identity_.size ();
+ cmd.args.attach.peer_identity =
+ (unsigned char*) malloc (peer_identity_.size ());
+ alloc_assert (cmd.args.attach.peer_identity_size);
+ memcpy (cmd.args.attach.peer_identity, peer_identity_.data (),
+ peer_identity_.size ());
+ }
+ send_command (cmd);
+}
+
+void zmq::object_t::send_bind (own_t *destination_, reader_t *in_pipe_,
+ writer_t *out_pipe_, const blob_t &peer_identity_, bool inc_seqnum_)
+{
+ if (inc_seqnum_)
+ destination_->inc_seqnum ();
+
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::bind;
+ cmd.args.bind.in_pipe = in_pipe_;
+ cmd.args.bind.out_pipe = out_pipe_;
+ if (peer_identity_.empty ()) {
+ cmd.args.bind.peer_identity_size = 0;
+ cmd.args.bind.peer_identity = NULL;
+ }
+ else {
+ zmq_assert (peer_identity_.size () <= 0xff);
+ cmd.args.bind.peer_identity_size =
+ (unsigned char) peer_identity_.size ();
+ cmd.args.bind.peer_identity =
+ (unsigned char*) malloc (peer_identity_.size ());
+ alloc_assert (cmd.args.bind.peer_identity_size);
+ memcpy (cmd.args.bind.peer_identity, peer_identity_.data (),
+ peer_identity_.size ());
+ }
+ send_command (cmd);
+}
+
+void zmq::object_t::send_activate_reader (reader_t *destination_)
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::activate_reader;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_activate_writer (writer_t *destination_,
+ uint64_t msgs_read_)
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::activate_writer;
+ cmd.args.activate_writer.msgs_read = msgs_read_;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_pipe_term (writer_t *destination_)
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::pipe_term;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_pipe_term_ack (reader_t *destination_)
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::pipe_term_ack;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_term_req (own_t *destination_,
+ own_t *object_)
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::term_req;
+ cmd.args.term_req.object = object_;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_term (own_t *destination_, int linger_)
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::term;
+ cmd.args.term.linger = linger_;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_term_ack (own_t *destination_)
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = destination_;
+ cmd.type = command_t::term_ack;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_reap (class socket_base_t *socket_)
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = ctx->get_reaper ();
+ cmd.type = command_t::reap;
+ cmd.args.reap.socket = socket_;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_reaped ()
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = ctx->get_reaper ();
+ cmd.type = command_t::reaped;
+ send_command (cmd);
+}
+
+void zmq::object_t::send_done ()
+{
+ command_t cmd;
+#if defined ZMQ_MAKE_VALGRIND_HAPPY
+ memset (&cmd, 0, sizeof (cmd));
+#endif
+ cmd.destination = NULL;
+ cmd.type = command_t::done;
+ ctx->send_command (ctx_t::term_tid, cmd);
+}
+
+void zmq::object_t::process_stop ()
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_plug ()
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_own (own_t *object_)
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_attach (i_engine *engine_,
+ const blob_t &peer_identity_)
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_bind (reader_t *in_pipe_, writer_t *out_pipe_,
+ const blob_t &peer_identity_)
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_activate_reader ()
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_activate_writer (uint64_t msgs_read_)
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_pipe_term ()
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_pipe_term_ack ()
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_term_req (own_t *object_)
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_term (int linger_)
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_term_ack ()
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_reap (class socket_base_t *socket_)
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_reaped ()
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::process_seqnum ()
+{
+ zmq_assert (false);
+}
+
+void zmq::object_t::send_command (command_t &cmd_)
+{
+ ctx->send_command (cmd_.destination->get_tid (), cmd_);
+}
+
diff --git a/src/0mq/object.hpp b/src/0mq/object.hpp
new file mode 100644
index 0000000..706303b
--- /dev/null
+++ b/src/0mq/object.hpp
@@ -0,0 +1,127 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_OBJECT_HPP_INCLUDED__
+#define __ZMQ_OBJECT_HPP_INCLUDED__
+
+#include "../include/zmq.h"
+
+#include "stdint.hpp"
+#include "blob.hpp"
+
+namespace zmq
+{
+ // Base class for all objects that participate in inter-thread
+ // communication.
+
+ class object_t
+ {
+ public:
+
+ object_t (class ctx_t *ctx_, uint32_t tid_);
+ object_t (object_t *parent_);
+ virtual ~object_t ();
+
+ uint32_t get_tid ();
+ ctx_t *get_ctx ();
+ void process_command (struct command_t &cmd_);
+
+ protected:
+
+ // Using following function, socket is able to access global
+ // repository of inproc endpoints.
+ int register_endpoint (const char *addr_, struct endpoint_t &endpoint_);
+ void unregister_endpoints (class socket_base_t *socket_);
+ struct endpoint_t find_endpoint (const char *addr_);
+ void destroy_socket (class socket_base_t *socket_);
+
+ // Logs an message.
+ void log (const char *format_, ...);
+
+ // Chooses least loaded I/O thread.
+ class io_thread_t *choose_io_thread (uint64_t affinity_);
+
+ // Derived object can use these functions to send commands
+ // to other objects.
+ void send_stop ();
+ void send_plug (class own_t *destination_,
+ bool inc_seqnum_ = true);
+ void send_own (class own_t *destination_,
+ class own_t *object_);
+ void send_attach (class session_t *destination_,
+ struct i_engine *engine_, const blob_t &peer_identity_,
+ bool inc_seqnum_ = true);
+ void send_bind (class own_t *destination_,
+ class reader_t *in_pipe_, class writer_t *out_pipe_,
+ const blob_t &peer_identity_, bool inc_seqnum_ = true);
+ void send_activate_reader (class reader_t *destination_);
+ void send_activate_writer (class writer_t *destination_,
+ uint64_t msgs_read_);
+ void send_pipe_term (class writer_t *destination_);
+ void send_pipe_term_ack (class reader_t *destination_);
+ void send_term_req (class own_t *destination_,
+ class own_t *object_);
+ void send_term (class own_t *destination_, int linger_);
+ void send_term_ack (class own_t *destination_);
+ void send_reap (class socket_base_t *socket_);
+ void send_reaped ();
+ void send_done ();
+
+ // These handlers can be overloaded by the derived objects. They are
+ // called when command arrives from another thread.
+ virtual void process_stop ();
+ virtual void process_plug ();
+ virtual void process_own (class own_t *object_);
+ virtual void process_attach (struct i_engine *engine_,
+ const blob_t &peer_identity_);
+ virtual void process_bind (class reader_t *in_pipe_,
+ class writer_t *out_pipe_, const blob_t &peer_identity_);
+ virtual void process_activate_reader ();
+ virtual void process_activate_writer (uint64_t msgs_read_);
+ virtual void process_pipe_term ();
+ virtual void process_pipe_term_ack ();
+ virtual void process_term_req (class own_t *object_);
+ virtual void process_term (int linger_);
+ virtual void process_term_ack ();
+ virtual void process_reap (class socket_base_t *socket_);
+ virtual void process_reaped ();
+
+ // Special handler called after a command that requires a seqnum
+ // was processed. The implementation should catch up with its counter
+ // of processed commands here.
+ virtual void process_seqnum ();
+
+ private:
+
+ // Context provides access to the global state.
+ class ctx_t *ctx;
+
+ // Thread ID of the thread the object belongs to.
+ uint32_t tid;
+
+ void send_command (command_t &cmd_);
+
+ object_t (const object_t&);
+ const object_t &operator = (const object_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/options.cpp b/src/0mq/options.cpp
new file mode 100644
index 0000000..952907b
--- /dev/null
+++ b/src/0mq/options.cpp
@@ -0,0 +1,344 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <string.h>
+#ifndef ZMQ_HAVE_WINDOWS
+#include <sys/stat.h>
+#endif
+
+#include "../include/zmq.h"
+#include "options.hpp"
+#include "err.hpp"
+
+zmq::options_t::options_t () :
+ hwm (0),
+ swap (0),
+ affinity (0),
+ rate (40 * 1000),
+ recovery_ivl (10),
+ recovery_ivl_msec (-1),
+ use_multicast_loop (true),
+ sndbuf (0),
+ rcvbuf (0),
+ type (-1),
+ linger (-1),
+ reconnect_ivl (100),
+ reconnect_ivl_max (0),
+ backlog (100),
+ requires_in (false),
+ requires_out (false),
+ immediate_connect (true)
+{
+}
+
+int zmq::options_t::setsockopt (int option_, const void *optval_,
+ size_t optvallen_)
+{
+ switch (option_) {
+
+ case ZMQ_HWM:
+ if (optvallen_ != sizeof (uint64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ hwm = *((uint64_t*) optval_);
+ return 0;
+
+ case ZMQ_SWAP:
+ if (optvallen_ != sizeof (int64_t) || *((int64_t*) optval_) < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ // Check that SWAP directory (.) is writable
+ struct stat stat_buf;
+ if (stat (".", &stat_buf) || ((stat_buf.st_mode & S_IWRITE) == 0)) {
+ errno = EACCES;
+ return -1;
+ }
+ swap = *((int64_t*) optval_);
+ return 0;
+
+ case ZMQ_AFFINITY:
+ if (optvallen_ != sizeof (uint64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ affinity = *((uint64_t*) optval_);
+ return 0;
+
+ case ZMQ_IDENTITY:
+
+ // Empty identity is invalid as well as identity longer than
+ // 255 bytes. Identity starting with binary zero is invalid
+ // as these are used for auto-generated identities.
+ if (optvallen_ < 1 || optvallen_ > 255 ||
+ *((const unsigned char*) optval_) == 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ identity.assign ((const unsigned char*) optval_, optvallen_);
+ return 0;
+
+ case ZMQ_RATE:
+ if (optvallen_ != sizeof (int64_t) || *((int64_t*) optval_) < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ rate = (uint32_t) *((int64_t*) optval_);
+ return 0;
+
+ case ZMQ_RECOVERY_IVL:
+ if (optvallen_ != sizeof (int64_t) || *((int64_t*) optval_) < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ recovery_ivl = (uint32_t) *((int64_t*) optval_);
+ return 0;
+
+ case ZMQ_RECOVERY_IVL_MSEC:
+ if (optvallen_ != sizeof (int64_t) || *((int64_t*) optval_) < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ recovery_ivl_msec = (int32_t) *((int64_t*) optval_);
+ return 0;
+
+ case ZMQ_MCAST_LOOP:
+ if (optvallen_ != sizeof (int64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ if ((int64_t) *((int64_t*) optval_) == 0)
+ use_multicast_loop = false;
+ else if ((int64_t) *((int64_t*) optval_) == 1)
+ use_multicast_loop = true;
+ else {
+ errno = EINVAL;
+ return -1;
+ }
+ return 0;
+
+ case ZMQ_SNDBUF:
+ if (optvallen_ != sizeof (uint64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ sndbuf = *((uint64_t*) optval_);
+ return 0;
+
+ case ZMQ_RCVBUF:
+ if (optvallen_ != sizeof (uint64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ rcvbuf = *((uint64_t*) optval_);
+ return 0;
+
+ case ZMQ_LINGER:
+ if (optvallen_ != sizeof (int)) {
+ errno = EINVAL;
+ return -1;
+ }
+ linger = *((int*) optval_);
+ return 0;
+
+ case ZMQ_RECONNECT_IVL:
+ if (optvallen_ != sizeof (int)) {
+ errno = EINVAL;
+ return -1;
+ }
+ if (*((int*) optval_) < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ reconnect_ivl = *((int*) optval_);
+ return 0;
+
+ case ZMQ_RECONNECT_IVL_MAX:
+ if (optvallen_ != sizeof (int)) {
+ errno = EINVAL;
+ return -1;
+ }
+ if (*((int*) optval_) < 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ reconnect_ivl_max = *((int*) optval_);
+ return 0;
+
+ case ZMQ_BACKLOG:
+ if (optvallen_ != sizeof (int)) {
+ errno = EINVAL;
+ return -1;
+ }
+ backlog = *((int*) optval_);
+ return 0;
+
+ }
+
+ errno = EINVAL;
+ return -1;
+}
+
+int zmq::options_t::getsockopt (int option_, void *optval_, size_t *optvallen_)
+{
+ switch (option_) {
+
+ case ZMQ_HWM:
+ if (*optvallen_ < sizeof (uint64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((uint64_t*) optval_) = hwm;
+ *optvallen_ = sizeof (uint64_t);
+ return 0;
+
+ case ZMQ_SWAP:
+ if (*optvallen_ < sizeof (int64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int64_t*) optval_) = swap;
+ *optvallen_ = sizeof (int64_t);
+ return 0;
+
+ case ZMQ_AFFINITY:
+ if (*optvallen_ < sizeof (uint64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((uint64_t*) optval_) = affinity;
+ *optvallen_ = sizeof (uint64_t);
+ return 0;
+
+ case ZMQ_IDENTITY:
+ if (*optvallen_ < identity.size ()) {
+ errno = EINVAL;
+ return -1;
+ }
+ memcpy (optval_, identity.data (), identity.size ());
+ *optvallen_ = identity.size ();
+ return 0;
+
+
+ case ZMQ_RATE:
+ if (*optvallen_ < sizeof (int64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int64_t*) optval_) = rate;
+ *optvallen_ = sizeof (int64_t);
+ return 0;
+
+ case ZMQ_RECOVERY_IVL:
+ if (*optvallen_ < sizeof (int64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int64_t*) optval_) = recovery_ivl;
+ *optvallen_ = sizeof (int64_t);
+ return 0;
+
+ case ZMQ_RECOVERY_IVL_MSEC:
+ if (*optvallen_ < sizeof (int64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int64_t*) optval_) = recovery_ivl_msec;
+ *optvallen_ = sizeof (int64_t);
+ return 0;
+
+ case ZMQ_MCAST_LOOP:
+ if (*optvallen_ < sizeof (int64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int64_t*) optval_) = use_multicast_loop ? 1 : 0;
+ *optvallen_ = sizeof (int64_t);
+ return 0;
+
+ case ZMQ_SNDBUF:
+ if (*optvallen_ < sizeof (uint64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((uint64_t*) optval_) = sndbuf;
+ *optvallen_ = sizeof (uint64_t);
+ return 0;
+
+ case ZMQ_RCVBUF:
+ if (*optvallen_ < sizeof (uint64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((uint64_t*) optval_) = rcvbuf;
+ *optvallen_ = sizeof (uint64_t);
+ return 0;
+
+ case ZMQ_TYPE:
+ if (*optvallen_ < sizeof (int)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int*) optval_) = type;
+ *optvallen_ = sizeof (int);
+ return 0;
+
+ case ZMQ_LINGER:
+ if (*optvallen_ < sizeof (int)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int*) optval_) = linger;
+ *optvallen_ = sizeof (int);
+ return 0;
+
+ case ZMQ_RECONNECT_IVL:
+ if (*optvallen_ < sizeof (int)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int*) optval_) = reconnect_ivl;
+ *optvallen_ = sizeof (int);
+ return 0;
+
+ case ZMQ_RECONNECT_IVL_MAX:
+ if (*optvallen_ < sizeof (int)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int*) optval_) = reconnect_ivl_max;
+ *optvallen_ = sizeof (int);
+ return 0;
+
+ case ZMQ_BACKLOG:
+ if (*optvallen_ < sizeof (int)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int*) optval_) = backlog;
+ *optvallen_ = sizeof (int);
+ return 0;
+
+ }
+
+ errno = EINVAL;
+ return -1;
+}
diff --git a/src/0mq/options.hpp b/src/0mq/options.hpp
new file mode 100644
index 0000000..b2e29d0
--- /dev/null
+++ b/src/0mq/options.hpp
@@ -0,0 +1,87 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_OPTIONS_HPP_INCLUDED__
+#define __ZMQ_OPTIONS_HPP_INCLUDED__
+
+#include "stddef.h"
+#include "stdint.hpp"
+#include "blob.hpp"
+
+namespace zmq
+{
+
+ struct options_t
+ {
+ options_t ();
+
+ int setsockopt (int option_, const void *optval_, size_t optvallen_);
+ int getsockopt (int option_, void *optval_, size_t *optvallen_);
+
+ uint64_t hwm;
+ int64_t swap;
+ uint64_t affinity;
+ blob_t identity;
+
+ // Maximum tranfer rate [kb/s]. Default 100kb/s.
+ uint32_t rate;
+
+ // Reliability time interval [s]. Default 10s.
+ uint32_t recovery_ivl;
+ // Reliability time interval [ms]. Default -1 = not used.
+ int32_t recovery_ivl_msec;
+
+ // Enable multicast loopback. Default disabled (false).
+ bool use_multicast_loop;
+
+ uint64_t sndbuf;
+ uint64_t rcvbuf;
+
+ // Socket type.
+ int type;
+
+ // Linger time, in milliseconds.
+ int linger;
+
+ // Minimum interval between attempts to reconnect, in milliseconds.
+ // Default 100ms
+ int reconnect_ivl;
+ // Maximum interval between attempts to reconnect, in milliseconds.
+ // Default 0 (unused)
+ int reconnect_ivl_max;
+
+ // Maximum backlog for pending connections.
+ int backlog;
+
+ // These options are never set by the user directly. Instead they are
+ // provided by the specific socket type.
+ bool requires_in;
+ bool requires_out;
+
+ // If true, when connecting, pipes are created immediately without
+ // waiting for the connection to be established. That way the socket
+ // is not aware of the peer's identity, however, it is able to send
+ // messages straight away.
+ bool immediate_connect;
+ };
+
+}
+
+#endif
diff --git a/src/0mq/own.cpp b/src/0mq/own.cpp
new file mode 100644
index 0000000..57e183a
--- /dev/null
+++ b/src/0mq/own.cpp
@@ -0,0 +1,214 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "own.hpp"
+#include "err.hpp"
+#include "io_thread.hpp"
+
+zmq::own_t::own_t (class ctx_t *parent_, uint32_t tid_) :
+ object_t (parent_, tid_),
+ terminating (false),
+ sent_seqnum (0),
+ processed_seqnum (0),
+ owner (NULL),
+ term_acks (0)
+{
+}
+
+zmq::own_t::own_t (io_thread_t *io_thread_, const options_t &options_) :
+ object_t (io_thread_),
+ options (options_),
+ terminating (false),
+ sent_seqnum (0),
+ processed_seqnum (0),
+ owner (NULL),
+ term_acks (0)
+{
+}
+
+zmq::own_t::~own_t ()
+{
+}
+
+void zmq::own_t::set_owner (own_t *owner_)
+{
+ zmq_assert (!owner);
+ owner = owner_;
+}
+
+void zmq::own_t::inc_seqnum ()
+{
+ // This function may be called from a different thread!
+ sent_seqnum.add (1);
+}
+
+void zmq::own_t::process_seqnum ()
+{
+ // Catch up with counter of processed commands.
+ processed_seqnum++;
+
+ // We may have catched up and still have pending terms acks.
+ check_term_acks ();
+}
+
+void zmq::own_t::launch_child (own_t *object_)
+{
+ // Specify the owner of the object.
+ object_->set_owner (this);
+
+ // Plug the object into the I/O thread.
+ send_plug (object_);
+
+ // Take ownership of the object.
+ send_own (this, object_);
+}
+
+void zmq::own_t::launch_sibling (own_t *object_)
+{
+ // At this point it is important that object is plugged in before its
+ // owner has a chance to terminate it. Thus, 'plug' command is sent before
+ // the 'own' command. Given that the mailbox preserves ordering of
+ // commands, 'term' command from the owner cannot make it to the object
+ // before the already written 'plug' command.
+
+ // Specify the owner of the object.
+ object_->set_owner (owner);
+
+ // Plug the object into its I/O thread.
+ send_plug (object_);
+
+ // Make parent own the object.
+ send_own (owner, object_);
+}
+
+void zmq::own_t::process_term_req (own_t *object_)
+{
+ // When shutting down we can ignore termination requests from owned
+ // objects. The termination request was already sent to the object.
+ if (terminating)
+ return;
+
+ // If I/O object is well and alive let's ask it to terminate.
+ owned_t::iterator it = std::find (owned.begin (), owned.end (), object_);
+
+ // If not found, we assume that termination request was already sent to
+ // the object so we can safely ignore the request.
+ if (it == owned.end ())
+ return;
+
+ owned.erase (it);
+ register_term_acks (1);
+
+ // Note that this object is the root of the (partial shutdown) thus, its
+ // value of linger is used, rather than the value stored by the children.
+ send_term (object_, options.linger);
+}
+
+void zmq::own_t::process_own (own_t *object_)
+{
+ // If the object is already being shut down, new owned objects are
+ // immediately asked to terminate. Note that linger is set to zero.
+ if (terminating) {
+ register_term_acks (1);
+ send_term (object_, 0);
+ return;
+ }
+
+ // Store the reference to the owned object.
+ owned.insert (object_);
+}
+
+void zmq::own_t::terminate ()
+{
+ // If termination is already underway, there's no point
+ // in starting it anew.
+ if (terminating)
+ return;
+
+ // As for the root of the ownership tree, there's noone to terminate it,
+ // so it has to terminate itself.
+ if (!owner) {
+ process_term (options.linger);
+ return;
+ }
+
+ // If I am an owned object, I'll ask my owner to terminate me.
+ send_term_req (owner, this);
+}
+
+void zmq::own_t::process_term (int linger_)
+{
+ // Double termination should never happen.
+ zmq_assert (!terminating);
+
+ // Send termination request to all owned objects.
+ for (owned_t::iterator it = owned.begin (); it != owned.end (); ++it)
+ send_term (*it, linger_);
+ register_term_acks (owned.size ());
+ owned.clear ();
+
+ // Start termination process and check whether by chance we cannot
+ // terminate immediately.
+ terminating = true;
+ check_term_acks ();
+}
+
+void zmq::own_t::register_term_acks (int count_)
+{
+ term_acks += count_;
+}
+
+void zmq::own_t::unregister_term_ack ()
+{
+ zmq_assert (term_acks > 0);
+ term_acks--;
+
+ // This may be a last ack we are waiting for before termination...
+ check_term_acks ();
+}
+
+void zmq::own_t::process_term_ack ()
+{
+ unregister_term_ack ();
+}
+
+void zmq::own_t::check_term_acks ()
+{
+ if (terminating && processed_seqnum == sent_seqnum.get () &&
+ term_acks == 0) {
+
+ // Sanity check. There should be no active children at this point.
+ zmq_assert (owned.empty ());
+
+ // The root object has nobody to confirm the termination to.
+ // Other nodes will confirm the termination to the owner.
+ if (owner)
+ send_term_ack (owner);
+
+ // Deallocate the resources.
+ process_destroy ();
+ }
+}
+
+void zmq::own_t::process_destroy ()
+{
+ delete this;
+}
+
diff --git a/src/0mq/own.hpp b/src/0mq/own.hpp
new file mode 100644
index 0000000..5023a30
--- /dev/null
+++ b/src/0mq/own.hpp
@@ -0,0 +1,140 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_OWN_HPP_INCLUDED__
+#define __ZMQ_OWN_HPP_INCLUDED__
+
+#include <set>
+#include <algorithm>
+
+#include "object.hpp"
+#include "options.hpp"
+#include "atomic_counter.hpp"
+#include "stdint.hpp"
+
+namespace zmq
+{
+
+ // Base class for objects forming a part of ownership hierarchy.
+ // It handles initialisation and destruction of such objects.
+
+ class own_t : public object_t
+ {
+ public:
+
+ // Note that the owner is unspecified in the constructor.
+ // It'll be supplied later on when the object is plugged in.
+
+ // The object is not living within an I/O thread. It has it's own
+ // thread outside of 0MQ infrastructure.
+ own_t (class ctx_t *parent_, uint32_t tid_);
+
+ // The object is living within I/O thread.
+ own_t (class io_thread_t *io_thread_, const options_t &options_);
+
+ // When another owned object wants to send command to this object
+ // it calls this function to let it know it should not shut down
+ // before the command is delivered.
+ void inc_seqnum ();
+
+ // Use following two functions to wait for arbitrary events before
+ // terminating. Just add number of events to wait for using
+ // register_tem_acks functions. When event occurs, call
+ // remove_term_ack. When number of pending acks reaches zero
+ // object will be deallocated.
+ void register_term_acks (int count_);
+ void unregister_term_ack ();
+
+ protected:
+
+ // Launch the supplied object and become its owner.
+ void launch_child (own_t *object_);
+
+ // Launch the supplied object and make it your sibling (make your
+ // owner become its owner as well).
+ void launch_sibling (own_t *object_);
+
+ // Ask owner object to terminate this object. It may take a while
+ // while actual termination is started. This function should not be
+ // called more than once.
+ void terminate ();
+
+ // Derived object destroys own_t. There's no point in allowing
+ // others to invoke the destructor. At the same time, it has to be
+ // virtual so that generic own_t deallocation mechanism destroys
+ // specific type of the owned object correctly.
+ virtual ~own_t ();
+
+ // Term handler is protocted rather than private so that it can
+ // be intercepted by the derived class. This is useful to add custom
+ // steps to the beginning of the termination process.
+ void process_term (int linger_);
+
+ // A place to hook in when phyicallal destruction of the object
+ // is to be delayed.
+ virtual void process_destroy ();
+
+ // Socket options associated with this object.
+ options_t options;
+
+ private:
+
+ // Set owner of the object
+ void set_owner (own_t *owner_);
+
+ // Handlers for incoming commands.
+ void process_own (own_t *object_);
+ void process_term_req (own_t *object_);
+ void process_term_ack ();
+ void process_seqnum ();
+
+ // Check whether all the peding term acks were delivered.
+ // If so, deallocate this object.
+ void check_term_acks ();
+
+ // True if termination was already initiated. If so, we can destroy
+ // the object if there are no more child objects or pending term acks.
+ bool terminating;
+
+ // Sequence number of the last command sent to this object.
+ atomic_counter_t sent_seqnum;
+
+ // Sequence number of the last command processed by this object.
+ uint64_t processed_seqnum;
+
+ // Socket owning this object. It's responsible for shutting down
+ // this object.
+ own_t *owner;
+
+ // List of all objects owned by this socket. We are responsible
+ // for deallocating them before we quit.
+ typedef std::set <own_t*> owned_t;
+ owned_t owned;
+
+ // Number of events we have to get before we can destroy the object.
+ int term_acks;
+
+ own_t (const own_t&);
+ const own_t &operator = (const own_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/pair.cpp b/src/0mq/pair.cpp
new file mode 100644
index 0000000..1acc60f
--- /dev/null
+++ b/src/0mq/pair.cpp
@@ -0,0 +1,180 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "pair.hpp"
+#include "err.hpp"
+#include "pipe.hpp"
+
+zmq::pair_t::pair_t (class ctx_t *parent_, uint32_t tid_) :
+ socket_base_t (parent_, tid_),
+ inpipe (NULL),
+ outpipe (NULL),
+ inpipe_alive (false),
+ outpipe_alive (false),
+ terminating (false)
+{
+ options.type = ZMQ_PAIR;
+ options.requires_in = true;
+ options.requires_out = true;
+}
+
+zmq::pair_t::~pair_t ()
+{
+ zmq_assert (!inpipe);
+ zmq_assert (!outpipe);
+}
+
+void zmq::pair_t::xattach_pipes (reader_t *inpipe_, writer_t *outpipe_,
+ const blob_t &peer_identity_)
+{
+ zmq_assert (!inpipe && !outpipe);
+
+ inpipe = inpipe_;
+ inpipe_alive = true;
+ inpipe->set_event_sink (this);
+
+ outpipe = outpipe_;
+ outpipe_alive = true;
+ outpipe->set_event_sink (this);
+
+ if (terminating) {
+ register_term_acks (2);
+ inpipe_->terminate ();
+ outpipe_->terminate ();
+ }
+}
+
+void zmq::pair_t::terminated (reader_t *pipe_)
+{
+ zmq_assert (pipe_ == inpipe);
+ inpipe = NULL;
+ inpipe_alive = false;
+
+ if (terminating)
+ unregister_term_ack ();
+}
+
+void zmq::pair_t::terminated (writer_t *pipe_)
+{
+ zmq_assert (pipe_ == outpipe);
+ outpipe = NULL;
+ outpipe_alive = false;
+
+ if (terminating)
+ unregister_term_ack ();
+}
+
+void zmq::pair_t::delimited (reader_t *pipe_)
+{
+}
+
+void zmq::pair_t::process_term (int linger_)
+{
+ terminating = true;
+
+ if (inpipe) {
+ register_term_acks (1);
+ inpipe->terminate ();
+ }
+
+ if (outpipe) {
+ register_term_acks (1);
+ outpipe->terminate ();
+ }
+
+ socket_base_t::process_term (linger_);
+}
+
+void zmq::pair_t::activated (class reader_t *pipe_)
+{
+ zmq_assert (!inpipe_alive);
+ inpipe_alive = true;
+}
+
+void zmq::pair_t::activated (class writer_t *pipe_)
+{
+ zmq_assert (!outpipe_alive);
+ outpipe_alive = true;
+}
+
+int zmq::pair_t::xsend (zmq_msg_t *msg_, int flags_)
+{
+ if (outpipe == NULL || !outpipe_alive) {
+ errno = EAGAIN;
+ return -1;
+ }
+
+ if (!outpipe->write (msg_)) {
+ outpipe_alive = false;
+ errno = EAGAIN;
+ return -1;
+ }
+
+ if (!(flags_ & ZMQ_SNDMORE))
+ outpipe->flush ();
+
+ // Detach the original message from the data buffer.
+ int rc = zmq_msg_init (msg_);
+ zmq_assert (rc == 0);
+
+ return 0;
+}
+
+int zmq::pair_t::xrecv (zmq_msg_t *msg_, int flags_)
+{
+ // Deallocate old content of the message.
+ zmq_msg_close (msg_);
+
+ if (!inpipe_alive || !inpipe || !inpipe->read (msg_)) {
+
+ // No message is available.
+ inpipe_alive = false;
+
+ // Initialise the output parameter to be a 0-byte message.
+ zmq_msg_init (msg_);
+ errno = EAGAIN;
+ return -1;
+ }
+ return 0;
+}
+
+bool zmq::pair_t::xhas_in ()
+{
+ if (!inpipe || !inpipe_alive)
+ return false;
+
+ inpipe_alive = inpipe->check_read ();
+ return inpipe_alive;
+}
+
+bool zmq::pair_t::xhas_out ()
+{
+ if (!outpipe || !outpipe_alive)
+ return false;
+
+ zmq_msg_t msg;
+ zmq_msg_init (&msg);
+ outpipe_alive = outpipe->check_write (&msg);
+ zmq_msg_close (&msg);
+ return outpipe_alive;
+}
+
diff --git a/src/0mq/pair.hpp b/src/0mq/pair.hpp
new file mode 100644
index 0000000..54e60b5
--- /dev/null
+++ b/src/0mq/pair.hpp
@@ -0,0 +1,76 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_PAIR_HPP_INCLUDED__
+#define __ZMQ_PAIR_HPP_INCLUDED__
+
+#include "socket_base.hpp"
+#include "pipe.hpp"
+
+namespace zmq
+{
+
+ class pair_t :
+ public socket_base_t,
+ public i_reader_events,
+ public i_writer_events
+ {
+ public:
+
+ pair_t (class ctx_t *parent_, uint32_t tid_);
+ ~pair_t ();
+
+ // Overloads of functions from socket_base_t.
+ void xattach_pipes (class reader_t *inpipe_, class writer_t *outpipe_,
+ const blob_t &peer_identity_);
+ int xsend (zmq_msg_t *msg_, int flags_);
+ int xrecv (zmq_msg_t *msg_, int flags_);
+ bool xhas_in ();
+ bool xhas_out ();
+
+ // i_reader_events interface implementation.
+ void activated (class reader_t *pipe_);
+ void terminated (class reader_t *pipe_);
+ void delimited (class reader_t *pipe_);
+
+ // i_writer_events interface implementation.
+ void activated (class writer_t *pipe_);
+ void terminated (class writer_t *pipe_);
+
+ private:
+
+ // Hook into termination process.
+ void process_term (int linger_);
+
+ class reader_t *inpipe;
+ class writer_t *outpipe;
+
+ bool inpipe_alive;
+ bool outpipe_alive;
+
+ bool terminating;
+
+ pair_t (const pair_t&);
+ const pair_t &operator = (const pair_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/pgm_receiver.cpp b/src/0mq/pgm_receiver.cpp
new file mode 100644
index 0000000..7e7da96
--- /dev/null
+++ b/src/0mq/pgm_receiver.cpp
@@ -0,0 +1,259 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_OPENPGM
+
+#include <new>
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+#include "pgm_receiver.hpp"
+#include "err.hpp"
+#include "stdint.hpp"
+#include "wire.hpp"
+#include "i_inout.hpp"
+
+zmq::pgm_receiver_t::pgm_receiver_t (class io_thread_t *parent_,
+ const options_t &options_) :
+ io_object_t (parent_),
+ has_rx_timer (false),
+ pgm_socket (true, options_),
+ options (options_),
+ inout (NULL),
+ mru_decoder (NULL),
+ pending_bytes (0)
+{
+}
+
+zmq::pgm_receiver_t::~pgm_receiver_t ()
+{
+ // Destructor should not be called before unplug.
+ zmq_assert (peers.empty ());
+}
+
+int zmq::pgm_receiver_t::init (bool udp_encapsulation_, const char *network_)
+{
+ return pgm_socket.init (udp_encapsulation_, network_);
+}
+
+void zmq::pgm_receiver_t::plug (io_thread_t *io_thread_, i_inout *inout_)
+{
+ // Retrieve PGM fds and start polling.
+ fd_t socket_fd = retired_fd;
+ fd_t waiting_pipe_fd = retired_fd;
+ pgm_socket.get_receiver_fds (&socket_fd, &waiting_pipe_fd);
+ socket_handle = add_fd (socket_fd);
+ pipe_handle = add_fd (waiting_pipe_fd);
+ set_pollin (pipe_handle);
+ set_pollin (socket_handle);
+
+ inout = inout_;
+}
+
+void zmq::pgm_receiver_t::unplug ()
+{
+ // Delete decoders.
+ for (peers_t::iterator it = peers.begin (); it != peers.end (); ++it) {
+ if (it->second.decoder != NULL)
+ delete it->second.decoder;
+ }
+ peers.clear ();
+
+ mru_decoder = NULL;
+ pending_bytes = 0;
+
+ if (has_rx_timer) {
+ cancel_timer (rx_timer_id);
+ has_rx_timer = false;
+ }
+
+ rm_fd (socket_handle);
+ rm_fd (pipe_handle);
+
+ inout = NULL;
+}
+
+void zmq::pgm_receiver_t::terminate ()
+{
+ unplug ();
+ delete this;
+}
+
+void zmq::pgm_receiver_t::activate_out ()
+{
+ zmq_assert (false);
+}
+
+void zmq::pgm_receiver_t::activate_in ()
+{
+ // It is possible that the most recently used decoder
+ // processed the whole buffer but failed to write
+ // the last message into the pipe.
+ if (pending_bytes == 0) {
+ if (mru_decoder != NULL)
+ mru_decoder->process_buffer (NULL, 0);
+ return;
+ }
+
+ zmq_assert (mru_decoder != NULL);
+ zmq_assert (pending_ptr != NULL);
+
+ // Ask the decoder to process remaining data.
+ size_t n = mru_decoder->process_buffer (pending_ptr, pending_bytes);
+ pending_bytes -= n;
+
+ if (pending_bytes > 0)
+ return;
+
+ // Resume polling.
+ set_pollin (pipe_handle);
+ set_pollin (socket_handle);
+
+ in_event ();
+}
+
+void zmq::pgm_receiver_t::in_event ()
+{
+ // Read data from the underlying pgm_socket.
+ unsigned char *data = NULL;
+ const pgm_tsi_t *tsi = NULL;
+
+ zmq_assert (pending_bytes == 0);
+
+ if (has_rx_timer) {
+ cancel_timer (rx_timer_id);
+ has_rx_timer = false;
+ }
+
+ // TODO: This loop can effectively block other engines in the same I/O
+ // thread in the case of high load.
+ while (true) {
+
+ // Get new batch of data.
+ // Note the workaround made not to break strict-aliasing rules.
+ void *tmp = NULL;
+ ssize_t received = pgm_socket.receive (&tmp, &tsi);
+ data = (unsigned char*) tmp;
+
+ // No data to process. This may happen if the packet received is
+ // neither ODATA nor ODATA.
+ if (received == 0) {
+ if (errno == ENOMEM || errno == EBUSY) {
+ const long timeout = pgm_socket.get_rx_timeout ();
+ add_timer (timeout, rx_timer_id);
+ has_rx_timer = true;
+ }
+ break;
+ }
+
+ // Find the peer based on its TSI.
+ peers_t::iterator it = peers.find (*tsi);
+
+ // Data loss. Delete decoder and mark the peer as disjoint.
+ if (received == -1) {
+ if (it != peers.end ()) {
+ it->second.joined = false;
+ if (it->second.decoder == mru_decoder)
+ mru_decoder = NULL;
+ if (it->second.decoder != NULL) {
+ delete it->second.decoder;
+ it->second.decoder = NULL;
+ }
+ }
+ break;
+ }
+
+ // New peer. Add it to the list of know but unjoint peers.
+ if (it == peers.end ()) {
+ peer_info_t peer_info = {false, NULL};
+ it = peers.insert (peers_t::value_type (*tsi, peer_info)).first;
+ }
+
+ // Read the offset of the fist message in the current packet.
+ zmq_assert ((size_t) received >= sizeof (uint16_t));
+ uint16_t offset = get_uint16 (data);
+ data += sizeof (uint16_t);
+ received -= sizeof (uint16_t);
+
+ // Join the stream if needed.
+ if (!it->second.joined) {
+
+ // There is no beginning of the message in current packet.
+ // Ignore the data.
+ if (offset == 0xffff)
+ continue;
+
+ zmq_assert (offset <= received);
+ zmq_assert (it->second.decoder == NULL);
+
+ // We have to move data to the begining of the first message.
+ data += offset;
+ received -= offset;
+
+ // Mark the stream as joined.
+ it->second.joined = true;
+
+ // Create and connect decoder for the peer.
+ it->second.decoder = new (std::nothrow) decoder_t (0);
+ alloc_assert (it->second.decoder);
+ it->second.decoder->set_inout (inout);
+ }
+
+ mru_decoder = it->second.decoder;
+
+ // Push all the data to the decoder.
+ ssize_t processed = it->second.decoder->process_buffer (data, received);
+ if (processed < received) {
+ // Save some state so we can resume the decoding process later.
+ pending_bytes = received - processed;
+ pending_ptr = data + processed;
+ // Stop polling.
+ reset_pollin (pipe_handle);
+ reset_pollin (socket_handle);
+
+ // Reset outstanding timer.
+ if (has_rx_timer) {
+ cancel_timer (rx_timer_id);
+ has_rx_timer = false;
+ }
+
+ break;
+ }
+ }
+
+ // Flush any messages decoder may have produced.
+ inout->flush ();
+}
+
+void zmq::pgm_receiver_t::timer_event (int token)
+{
+ zmq_assert (token == rx_timer_id);
+
+ // Timer cancels on return by poller_base.
+ has_rx_timer = false;
+ in_event ();
+}
+
+#endif
+
diff --git a/src/0mq/pgm_receiver.hpp b/src/0mq/pgm_receiver.hpp
new file mode 100644
index 0000000..172557f
--- /dev/null
+++ b/src/0mq/pgm_receiver.hpp
@@ -0,0 +1,129 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_PGM_RECEIVER_HPP_INCLUDED__
+#define __ZMQ_PGM_RECEIVER_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_OPENPGM
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+#include <map>
+#include <algorithm>
+
+#include "io_object.hpp"
+#include "i_engine.hpp"
+#include "options.hpp"
+#include "decoder.hpp"
+#include "pgm_socket.hpp"
+
+namespace zmq
+{
+
+ class pgm_receiver_t : public io_object_t, public i_engine
+ {
+
+ public:
+
+ pgm_receiver_t (class io_thread_t *parent_, const options_t &options_);
+ ~pgm_receiver_t ();
+
+ int init (bool udp_encapsulation_, const char *network_);
+
+ // i_engine interface implementation.
+ void plug (class io_thread_t *io_thread_, struct i_inout *inout_);
+ void unplug ();
+ void terminate ();
+ void activate_in ();
+ void activate_out ();
+
+ // i_poll_events interface implementation.
+ void in_event ();
+ void timer_event (int token);
+
+ private:
+
+ // RX timeout timer ID.
+ enum {rx_timer_id = 0xa1};
+
+ // RX timer is running.
+ bool has_rx_timer;
+
+ // If joined is true we are already getting messages from the peer.
+ // It it's false, we are getting data but still we haven't seen
+ // beginning of a message.
+ struct peer_info_t
+ {
+ bool joined;
+ decoder_t *decoder;
+ };
+
+ struct tsi_comp
+ {
+ bool operator () (const pgm_tsi_t &ltsi,
+ const pgm_tsi_t &rtsi) const
+ {
+ uint32_t ll[2], rl[2];
+ memcpy (ll, &ltsi, sizeof (ll));
+ memcpy (rl, &rtsi, sizeof (rl));
+ return (ll[0] < rl[0]) || (ll[0] == rl[0] && ll[1] < rl[1]);
+ }
+ };
+
+ typedef std::map <pgm_tsi_t, peer_info_t, tsi_comp> peers_t;
+ peers_t peers;
+
+ // PGM socket.
+ pgm_socket_t pgm_socket;
+
+ // Socket options.
+ options_t options;
+
+ // Parent session.
+ i_inout *inout;
+
+ // Most recently used decoder.
+ decoder_t *mru_decoder;
+
+ // Number of bytes not consumed by the decoder due to pipe overflow.
+ size_t pending_bytes;
+
+ // Pointer to data still waiting to be processed by the decoder.
+ unsigned char *pending_ptr;
+
+ // Poll handle associated with PGM socket.
+ handle_t socket_handle;
+
+ // Poll handle associated with engine PGM waiting pipe.
+ handle_t pipe_handle;
+
+ pgm_receiver_t (const pgm_receiver_t&);
+ const pgm_receiver_t &operator = (const pgm_receiver_t&);
+ };
+
+}
+
+#endif
+
+#endif
diff --git a/src/0mq/pgm_sender.cpp b/src/0mq/pgm_sender.cpp
new file mode 100644
index 0000000..7a0c951
--- /dev/null
+++ b/src/0mq/pgm_sender.cpp
@@ -0,0 +1,215 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_OPENPGM
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+#include <stdlib.h>
+
+#include "io_thread.hpp"
+#include "pgm_sender.hpp"
+#include "err.hpp"
+#include "wire.hpp"
+#include "stdint.hpp"
+
+zmq::pgm_sender_t::pgm_sender_t (io_thread_t *parent_,
+ const options_t &options_) :
+ io_object_t (parent_),
+ has_tx_timer (false),
+ has_rx_timer (false),
+ encoder (0),
+ pgm_socket (false, options_),
+ options (options_),
+ out_buffer (NULL),
+ out_buffer_size (0),
+ write_size (0)
+{
+}
+
+int zmq::pgm_sender_t::init (bool udp_encapsulation_, const char *network_)
+{
+ int rc = pgm_socket.init (udp_encapsulation_, network_);
+ if (rc != 0)
+ return rc;
+
+ out_buffer_size = pgm_socket.get_max_tsdu_size ();
+ out_buffer = (unsigned char*) malloc (out_buffer_size);
+ alloc_assert (out_buffer);
+
+ return rc;
+}
+
+void zmq::pgm_sender_t::plug (io_thread_t *io_thread_, i_inout *inout_)
+{
+ // Alocate 2 fds for PGM socket.
+ fd_t downlink_socket_fd = retired_fd;
+ fd_t uplink_socket_fd = retired_fd;
+ fd_t rdata_notify_fd = retired_fd;
+ fd_t pending_notify_fd = retired_fd;
+
+ encoder.set_inout (inout_);
+
+ // Fill fds from PGM transport and add them to the poller.
+ pgm_socket.get_sender_fds (&downlink_socket_fd, &uplink_socket_fd,
+ &rdata_notify_fd, &pending_notify_fd);
+
+ handle = add_fd (downlink_socket_fd);
+ uplink_handle = add_fd (uplink_socket_fd);
+ rdata_notify_handle = add_fd (rdata_notify_fd);
+ pending_notify_handle = add_fd (pending_notify_fd);
+
+ // Set POLLIN. We wont never want to stop polling for uplink = we never
+ // want to stop porocess NAKs.
+ set_pollin (uplink_handle);
+ set_pollin (rdata_notify_handle);
+ set_pollin (pending_notify_handle);
+
+ // Set POLLOUT for downlink_socket_handle.
+ set_pollout (handle);
+}
+
+void zmq::pgm_sender_t::unplug ()
+{
+ if (has_rx_timer) {
+ cancel_timer (rx_timer_id);
+ has_rx_timer = false;
+ }
+
+ if (has_tx_timer) {
+ cancel_timer (tx_timer_id);
+ has_tx_timer = false;
+ }
+
+ rm_fd (handle);
+ rm_fd (uplink_handle);
+ rm_fd (rdata_notify_handle);
+ rm_fd (pending_notify_handle);
+ encoder.set_inout (NULL);
+}
+
+void zmq::pgm_sender_t::terminate ()
+{
+ unplug ();
+ delete this;
+}
+
+void zmq::pgm_sender_t::activate_out ()
+{
+ set_pollout (handle);
+ out_event ();
+}
+
+void zmq::pgm_sender_t::activate_in ()
+{
+ zmq_assert (false);
+}
+
+zmq::pgm_sender_t::~pgm_sender_t ()
+{
+ if (out_buffer) {
+ free (out_buffer);
+ out_buffer = NULL;
+ }
+}
+
+void zmq::pgm_sender_t::in_event ()
+{
+ if (has_rx_timer) {
+ cancel_timer (rx_timer_id);
+ has_rx_timer = false;
+ }
+
+ // In-event on sender side means NAK or SPMR receiving from some peer.
+ pgm_socket.process_upstream ();
+ if (errno == ENOMEM || errno == EBUSY) {
+ const long timeout = pgm_socket.get_rx_timeout ();
+ add_timer (timeout, rx_timer_id);
+ has_rx_timer = true;
+ }
+}
+
+void zmq::pgm_sender_t::out_event ()
+{
+ // POLLOUT event from send socket. If write buffer is empty,
+ // try to read new data from the encoder.
+ if (write_size == 0) {
+
+ // First two bytes (sizeof uint16_t) are used to store message
+ // offset in following steps. Note that by passing our buffer to
+ // the get data function we prevent it from returning its own buffer.
+ unsigned char *bf = out_buffer + sizeof (uint16_t);
+ size_t bfsz = out_buffer_size - sizeof (uint16_t);
+ int offset = -1;
+ encoder.get_data (&bf, &bfsz, &offset);
+
+ // If there are no data to write stop polling for output.
+ if (!bfsz) {
+ reset_pollout (handle);
+ return;
+ }
+
+ // Put offset information in the buffer.
+ write_size = bfsz + sizeof (uint16_t);
+ put_uint16 (out_buffer, offset == -1 ? 0xffff : (uint16_t) offset);
+ }
+
+ if (has_tx_timer) {
+ cancel_timer (tx_timer_id);
+ has_tx_timer = false;
+ }
+
+ // Send the data.
+ size_t nbytes = pgm_socket.send (out_buffer, write_size);
+
+ // We can write either all data or 0 which means rate limit reached.
+ if (nbytes == write_size) {
+ write_size = 0;
+ } else {
+ zmq_assert (nbytes == 0);
+
+ if (errno == ENOMEM) {
+ const long timeout = pgm_socket.get_tx_timeout ();
+ add_timer (timeout, tx_timer_id);
+ has_tx_timer = true;
+ } else
+ zmq_assert (errno == EBUSY);
+ }
+}
+
+void zmq::pgm_sender_t::timer_event (int token)
+{
+ // Timer cancels on return by poller_base.
+ if (token == rx_timer_id) {
+ has_rx_timer = false;
+ in_event ();
+ } else if (token == tx_timer_id) {
+ has_tx_timer = false;
+ out_event ();
+ } else
+ zmq_assert (false);
+}
+
+#endif
+
diff --git a/src/0mq/pgm_sender.hpp b/src/0mq/pgm_sender.hpp
new file mode 100644
index 0000000..4a21b3f
--- /dev/null
+++ b/src/0mq/pgm_sender.hpp
@@ -0,0 +1,105 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_PGM_SENDER_HPP_INCLUDED__
+#define __ZMQ_PGM_SENDER_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_OPENPGM
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+#include "stdint.hpp"
+#include "io_object.hpp"
+#include "i_engine.hpp"
+#include "options.hpp"
+#include "pgm_socket.hpp"
+#include "encoder.hpp"
+
+namespace zmq
+{
+
+ class pgm_sender_t : public io_object_t, public i_engine
+ {
+
+ public:
+
+ pgm_sender_t (class io_thread_t *parent_, const options_t &options_);
+ ~pgm_sender_t ();
+
+ int init (bool udp_encapsulation_, const char *network_);
+
+ // i_engine interface implementation.
+ void plug (class io_thread_t *io_thread_, struct i_inout *inout_);
+ void unplug ();
+ void terminate ();
+ void activate_in ();
+ void activate_out ();
+
+ // i_poll_events interface implementation.
+ void in_event ();
+ void out_event ();
+ void timer_event (int token);
+
+ private:
+
+ // TX and RX timeout timer ID's.
+ enum {tx_timer_id = 0xa0, rx_timer_id = 0xa1};
+
+ // Timers are running.
+ bool has_tx_timer;
+ bool has_rx_timer;
+
+ // Message encoder.
+ encoder_t encoder;
+
+ // PGM socket.
+ pgm_socket_t pgm_socket;
+
+ // Socket options.
+ options_t options;
+
+ // Poll handle associated with PGM socket.
+ handle_t handle;
+ handle_t uplink_handle;
+ handle_t rdata_notify_handle;
+ handle_t pending_notify_handle;
+
+ // Output buffer from pgm_socket.
+ unsigned char *out_buffer;
+
+ // Output buffer size.
+ size_t out_buffer_size;
+
+ // Number of bytes in the buffer to be written to the socket.
+ // If zero, there are no data to be sent.
+ size_t write_size;
+
+ pgm_sender_t (const pgm_sender_t&);
+ const pgm_sender_t &operator = (const pgm_sender_t&);
+ };
+
+}
+#endif
+
+#endif
diff --git a/src/0mq/pgm_socket.cpp b/src/0mq/pgm_socket.cpp
new file mode 100644
index 0000000..29ff3e6
--- /dev/null
+++ b/src/0mq/pgm_socket.cpp
@@ -0,0 +1,705 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+
+#ifdef ZMQ_HAVE_OPENPGM
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+#ifdef ZMQ_HAVE_LINUX
+#include <poll.h>
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+#include <string>
+
+#include "options.hpp"
+#include "pgm_socket.hpp"
+#include "config.hpp"
+#include "err.hpp"
+#include "uuid.hpp"
+#include "stdint.hpp"
+
+#ifndef MSG_ERRQUEUE
+#define MSG_ERRQUEUE 0x2000
+#endif
+
+zmq::pgm_socket_t::pgm_socket_t (bool receiver_, const options_t &options_) :
+ sock (NULL),
+ options (options_),
+ receiver (receiver_),
+ pgm_msgv (NULL),
+ pgm_msgv_len (0),
+ nbytes_rec (0),
+ nbytes_processed (0),
+ pgm_msgv_processed (0)
+{
+}
+
+// Create, bind and connect PGM socket.
+// network_ of the form <interface & multicast group decls>:<IP port>
+// e.g. eth0;239.192.0.1:7500
+// link-local;224.250.0.1,224.250.0.2;224.250.0.3:8000
+// ;[fe80::1%en0]:7500
+int zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_)
+{
+ // Can not open transport before destroying old one.
+ zmq_assert (sock == NULL);
+
+ // Parse port number, start from end for IPv6
+ const char *port_delim = strrchr (network_, ':');
+ if (!port_delim) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ uint16_t port_number = atoi (port_delim + 1);
+
+ char network [256];
+ if (port_delim - network_ >= (int) sizeof (network) - 1) {
+ errno = EINVAL;
+ return -1;
+ }
+ memset (network, '\0', sizeof (network));
+ memcpy (network, network_, port_delim - network_);
+
+ // Validate socket options
+ // Data rate is in [B/s]. options.rate is in [kb/s].
+ if (options.rate <= 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ // Recovery interval [s] or [ms] - based on the user's call
+ if ((options.recovery_ivl <= 0) && (options.recovery_ivl_msec <= 0)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ // Zero counter used in msgrecv.
+ nbytes_rec = 0;
+ nbytes_processed = 0;
+ pgm_msgv_processed = 0;
+
+ pgm_error_t *pgm_error = NULL;
+ struct pgm_addrinfo_t hints, *res = NULL;
+ sa_family_t sa_family;
+
+ memset (&hints, 0, sizeof (hints));
+ hints.ai_family = AF_UNSPEC;
+ if (!pgm_getaddrinfo (network, NULL, &res, &pgm_error)) {
+
+ // Invalid parameters don't set pgm_error_t.
+ zmq_assert (pgm_error != NULL);
+ if (pgm_error->domain == PGM_ERROR_DOMAIN_IF && (
+
+ // NB: cannot catch EAI_BADFLAGS.
+ pgm_error->code != PGM_ERROR_SERVICE &&
+ pgm_error->code != PGM_ERROR_SOCKTNOSUPPORT))
+
+ // User, host, or network configuration or transient error.
+ goto err_abort;
+
+ // Fatal OpenPGM internal error.
+ zmq_assert (false);
+ }
+
+ zmq_assert (res != NULL);
+
+ // Pick up detected IP family.
+ sa_family = res->ai_send_addrs[0].gsr_group.ss_family;
+
+ // Create IP/PGM or UDP/PGM socket.
+ if (udp_encapsulation_) {
+ if (!pgm_socket (&sock, sa_family, SOCK_SEQPACKET, IPPROTO_UDP,
+ &pgm_error)) {
+
+ // Invalid parameters don't set pgm_error_t.
+ zmq_assert (pgm_error != NULL);
+ if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET && (
+ pgm_error->code != PGM_ERROR_BADF &&
+ pgm_error->code != PGM_ERROR_FAULT &&
+ pgm_error->code != PGM_ERROR_NOPROTOOPT &&
+ pgm_error->code != PGM_ERROR_FAILED))
+
+ // User, host, or network configuration or transient error.
+ goto err_abort;
+
+ // Fatal OpenPGM internal error.
+ zmq_assert (false);
+ }
+
+ // All options are of data type int
+ const int encapsulation_port = port_number;
+ if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_UDP_ENCAP_UCAST_PORT,
+ &encapsulation_port, sizeof (encapsulation_port)))
+ goto err_abort;
+ if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_UDP_ENCAP_MCAST_PORT,
+ &encapsulation_port, sizeof (encapsulation_port)))
+ goto err_abort;
+ }
+ else {
+ if (!pgm_socket (&sock, sa_family, SOCK_SEQPACKET, IPPROTO_PGM,
+ &pgm_error)) {
+
+ // Invalid parameters don't set pgm_error_t.
+ zmq_assert (pgm_error != NULL);
+ if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET && (
+ pgm_error->code != PGM_ERROR_BADF &&
+ pgm_error->code != PGM_ERROR_FAULT &&
+ pgm_error->code != PGM_ERROR_NOPROTOOPT &&
+ pgm_error->code != PGM_ERROR_FAILED))
+
+ // User, host, or network configuration or transient error.
+ goto err_abort;
+
+ // Fatal OpenPGM internal error.
+ zmq_assert (false);
+ }
+ }
+
+ {
+ const int rcvbuf = (int) options.rcvbuf,
+ sndbuf = (int) options.sndbuf,
+ max_tpdu = (int) pgm_max_tpdu;
+ if (rcvbuf) {
+ if (!pgm_setsockopt (sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf,
+ sizeof (rcvbuf)))
+ goto err_abort;
+ }
+ if (sndbuf) {
+ if (!pgm_setsockopt (sock, SOL_SOCKET, SO_SNDBUF, &sndbuf,
+ sizeof (sndbuf)))
+ goto err_abort;
+ }
+
+ // Set maximum transport protocol data unit size (TPDU).
+ if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MTU, &max_tpdu,
+ sizeof (max_tpdu)))
+ goto err_abort;
+ }
+
+ if (receiver) {
+ const int recv_only = 1,
+ rxw_max_tpdu = (int) pgm_max_tpdu,
+ rxw_sqns = compute_sqns (rxw_max_tpdu),
+ peer_expiry = pgm_secs (300),
+ spmr_expiry = pgm_msecs (25),
+ nak_bo_ivl = pgm_msecs (50),
+ nak_rpt_ivl = pgm_msecs (200),
+ nak_rdata_ivl = pgm_msecs (200),
+ nak_data_retries = 50,
+ nak_ncf_retries = 50;
+
+ if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_RECV_ONLY, &recv_only,
+ sizeof (recv_only)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_RXW_SQNS, &rxw_sqns,
+ sizeof (rxw_sqns)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_PEER_EXPIRY, &peer_expiry,
+ sizeof (peer_expiry)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_SPMR_EXPIRY, &spmr_expiry,
+ sizeof (spmr_expiry)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_BO_IVL, &nak_bo_ivl,
+ sizeof (nak_bo_ivl)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RPT_IVL, &nak_rpt_ivl,
+ sizeof (nak_rpt_ivl)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RDATA_IVL,
+ &nak_rdata_ivl, sizeof (nak_rdata_ivl)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_DATA_RETRIES,
+ &nak_data_retries, sizeof (nak_data_retries)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_NCF_RETRIES,
+ &nak_ncf_retries, sizeof (nak_ncf_retries)))
+ goto err_abort;
+ } else {
+ const int send_only = 1,
+ max_rte = (int) ((options.rate * 1000) / 8),
+ txw_max_tpdu = (int) pgm_max_tpdu,
+ txw_sqns = compute_sqns (txw_max_tpdu),
+ ambient_spm = pgm_secs (30),
+ heartbeat_spm[] = { pgm_msecs (100),
+ pgm_msecs (100),
+ pgm_msecs (100),
+ pgm_msecs (100),
+ pgm_msecs (1300),
+ pgm_secs (7),
+ pgm_secs (16),
+ pgm_secs (25),
+ pgm_secs (30) };
+
+ if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_SEND_ONLY,
+ &send_only, sizeof (send_only)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_ODATA_MAX_RTE,
+ &max_rte, sizeof (max_rte)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_TXW_SQNS,
+ &txw_sqns, sizeof (txw_sqns)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_AMBIENT_SPM,
+ &ambient_spm, sizeof (ambient_spm)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_HEARTBEAT_SPM,
+ &heartbeat_spm, sizeof (heartbeat_spm)))
+ goto err_abort;
+ }
+
+ // PGM transport GSI.
+ struct pgm_sockaddr_t addr;
+
+ memset (&addr, 0, sizeof(addr));
+ addr.sa_port = port_number;
+ addr.sa_addr.sport = DEFAULT_DATA_SOURCE_PORT;
+
+ if (options.identity.size () > 0) {
+
+ // Create gsi from identity.
+ if (!pgm_gsi_create_from_data (&addr.sa_addr.gsi,
+ options.identity.data (), options.identity.size ()))
+ goto err_abort;
+ } else {
+
+ // Generate random gsi.
+ std::string gsi_base = uuid_t ().to_string ();
+ if (!pgm_gsi_create_from_string (&addr.sa_addr.gsi,
+ gsi_base.c_str (), -1))
+ goto err_abort;
+ }
+
+ // Bind a transport to the specified network devices.
+ struct pgm_interface_req_t if_req;
+ memset (&if_req, 0, sizeof(if_req));
+ if_req.ir_interface = res->ai_recv_addrs[0].gsr_interface;
+ if_req.ir_scope_id = 0;
+ if (AF_INET6 == sa_family) {
+ struct sockaddr_in6 sa6;
+ memcpy (&sa6, &res->ai_recv_addrs[0].gsr_group, sizeof (sa6));
+ if_req.ir_scope_id = sa6.sin6_scope_id;
+ }
+ if (!pgm_bind3 (sock, &addr, sizeof (addr), &if_req, sizeof (if_req),
+ &if_req, sizeof (if_req), &pgm_error)) {
+
+ // Invalid parameters don't set pgm_error_t.
+ zmq_assert (pgm_error != NULL);
+ if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
+ pgm_error->domain == PGM_ERROR_DOMAIN_IF) && (
+ pgm_error->code != PGM_ERROR_INVAL &&
+ pgm_error->code != PGM_ERROR_BADF &&
+ pgm_error->code != PGM_ERROR_FAULT))
+
+ // User, host, or network configuration or transient error.
+ goto err_abort;
+
+ // Fatal OpenPGM internal error.
+ zmq_assert (false);
+ }
+
+ // Join IP multicast groups.
+ for (unsigned i = 0; i < res->ai_recv_addrs_len; i++) {
+ if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_JOIN_GROUP,
+ &res->ai_recv_addrs [i], sizeof (struct group_req)))
+ goto err_abort;
+ }
+ if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_SEND_GROUP,
+ &res->ai_send_addrs [0], sizeof (struct group_req)))
+ goto err_abort;
+
+ pgm_freeaddrinfo (res);
+ res = NULL;
+
+ // Set IP level parameters.
+ {
+ const int nonblocking = 1,
+ multicast_loop = options.use_multicast_loop ? 1 : 0,
+ multicast_hops = 16,
+
+ // Expedited Forwarding PHB for network elements, no ECN.
+ dscp = 0x2e << 2;
+
+ if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MULTICAST_LOOP,
+ &multicast_loop, sizeof (multicast_loop)) ||
+ !pgm_setsockopt (sock, IPPROTO_PGM, PGM_MULTICAST_HOPS,
+ &multicast_hops, sizeof (multicast_hops)))
+ goto err_abort;
+ if (AF_INET6 != sa_family && !pgm_setsockopt (sock,
+ IPPROTO_PGM, PGM_TOS, &dscp, sizeof (dscp)))
+ goto err_abort;
+ if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_NOBLOCK,
+ &nonblocking, sizeof (nonblocking)))
+ goto err_abort;
+ }
+
+ // Connect PGM transport to start state machine.
+ if (!pgm_connect (sock, &pgm_error)) {
+
+ // Invalid parameters don't set pgm_error_t.
+ zmq_assert (pgm_error != NULL);
+ goto err_abort;
+ }
+
+ // For receiver transport preallocate pgm_msgv array.
+ if (receiver) {
+ zmq_assert (in_batch_size > 0);
+ size_t max_tsdu_size = get_max_tsdu_size ();
+ pgm_msgv_len = (int) in_batch_size / max_tsdu_size;
+ if ((int) in_batch_size % max_tsdu_size)
+ pgm_msgv_len++;
+ zmq_assert (pgm_msgv_len);
+
+ pgm_msgv = (pgm_msgv_t*) malloc (sizeof (pgm_msgv_t) * pgm_msgv_len);
+ alloc_assert (pgm_msgv);
+ }
+
+ return 0;
+
+err_abort:
+ if (sock != NULL) {
+ pgm_close (sock, FALSE);
+ sock = NULL;
+ }
+ if (res != NULL) {
+ pgm_freeaddrinfo (res);
+ res = NULL;
+ }
+ if (pgm_error != NULL) {
+ pgm_error_free (pgm_error);
+ pgm_error = NULL;
+ }
+ errno = EINVAL;
+ return -1;
+}
+
+zmq::pgm_socket_t::~pgm_socket_t ()
+{
+ if (pgm_msgv)
+ free (pgm_msgv);
+ if (sock)
+ pgm_close (sock, TRUE);
+}
+
+// Get receiver fds. receive_fd_ is signaled for incoming packets,
+// waiting_pipe_fd_ is signaled for state driven events and data.
+void zmq::pgm_socket_t::get_receiver_fds (fd_t *receive_fd_,
+ fd_t *waiting_pipe_fd_)
+{
+ socklen_t socklen;
+ bool rc;
+
+ zmq_assert (receive_fd_);
+ zmq_assert (waiting_pipe_fd_);
+
+ socklen = sizeof (*receive_fd_);
+ rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_RECV_SOCK, receive_fd_,
+ &socklen);
+ zmq_assert (rc);
+ zmq_assert (socklen == sizeof (*receive_fd_));
+
+ socklen = sizeof (*waiting_pipe_fd_);
+ rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_PENDING_SOCK, waiting_pipe_fd_,
+ &socklen);
+ zmq_assert (rc);
+ zmq_assert (socklen == sizeof (*waiting_pipe_fd_));
+}
+
+// Get fds and store them into user allocated memory.
+// send_fd is for non-blocking send wire notifications.
+// receive_fd_ is for incoming back-channel protocol packets.
+// rdata_notify_fd_ is raised for waiting repair transmissions.
+// pending_notify_fd_ is for state driven events.
+void zmq::pgm_socket_t::get_sender_fds (fd_t *send_fd_, fd_t *receive_fd_,
+ fd_t *rdata_notify_fd_, fd_t *pending_notify_fd_)
+{
+ socklen_t socklen;
+ bool rc;
+
+ zmq_assert (send_fd_);
+ zmq_assert (receive_fd_);
+ zmq_assert (rdata_notify_fd_);
+ zmq_assert (pending_notify_fd_);
+
+ socklen = sizeof (*send_fd_);
+ rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_SEND_SOCK, send_fd_, &socklen);
+ zmq_assert (rc);
+ zmq_assert (socklen == sizeof (*receive_fd_));
+
+ socklen = sizeof (*receive_fd_);
+ rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_RECV_SOCK, receive_fd_,
+ &socklen);
+ zmq_assert (rc);
+ zmq_assert (socklen == sizeof (*receive_fd_));
+
+ socklen = sizeof (*rdata_notify_fd_);
+ rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_REPAIR_SOCK, rdata_notify_fd_,
+ &socklen);
+ zmq_assert (rc);
+ zmq_assert (socklen == sizeof (*rdata_notify_fd_));
+
+ socklen = sizeof (*pending_notify_fd_);
+ rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_PENDING_SOCK,
+ pending_notify_fd_, &socklen);
+ zmq_assert (rc);
+ zmq_assert (socklen == sizeof (*pending_notify_fd_));
+}
+
+// Send one APDU, transmit window owned memory.
+// data_len_ must be less than one TPDU.
+size_t zmq::pgm_socket_t::send (unsigned char *data_, size_t data_len_)
+{
+ size_t nbytes = 0;
+
+ const int status = pgm_send (sock, data_, data_len_, &nbytes);
+
+ // We have to write all data as one packet.
+ if (nbytes > 0) {
+ zmq_assert (status == PGM_IO_STATUS_NORMAL);
+ zmq_assert ((ssize_t) nbytes == (ssize_t) data_len_);
+ } else {
+ zmq_assert (status == PGM_IO_STATUS_RATE_LIMITED ||
+ status == PGM_IO_STATUS_WOULD_BLOCK);
+
+ if (status == PGM_IO_STATUS_RATE_LIMITED)
+ errno = ENOMEM;
+ else
+ errno = EBUSY;
+ }
+
+ // Save return value.
+ last_tx_status = status;
+
+ return nbytes;
+}
+
+long zmq::pgm_socket_t::get_rx_timeout ()
+{
+ if (last_rx_status != PGM_IO_STATUS_RATE_LIMITED &&
+ last_rx_status != PGM_IO_STATUS_TIMER_PENDING)
+ return -1;
+
+ struct timeval tv;
+ socklen_t optlen = sizeof (tv);
+ const bool rc = pgm_getsockopt (sock, IPPROTO_PGM,
+ last_rx_status == PGM_IO_STATUS_RATE_LIMITED ? PGM_RATE_REMAIN :
+ PGM_TIME_REMAIN, &tv, &optlen);
+ zmq_assert (rc);
+
+ const long timeout = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
+
+ return timeout;
+}
+
+long zmq::pgm_socket_t::get_tx_timeout ()
+{
+ if (last_tx_status != PGM_IO_STATUS_RATE_LIMITED)
+ return -1;
+
+ struct timeval tv;
+ socklen_t optlen = sizeof (tv);
+ const bool rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_RATE_REMAIN, &tv,
+ &optlen);
+ zmq_assert (rc);
+
+ const long timeout = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
+
+ return timeout;
+}
+
+// Return max TSDU size without fragmentation from current PGM transport.
+size_t zmq::pgm_socket_t::get_max_tsdu_size ()
+{
+ int max_tsdu = 0;
+ socklen_t optlen = sizeof (max_tsdu);
+
+ bool rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_MSS, &max_tsdu, &optlen);
+ zmq_assert (rc);
+ zmq_assert (optlen == sizeof (max_tsdu));
+ return (size_t) max_tsdu;
+}
+
+// pgm_recvmsgv is called to fill the pgm_msgv array up to pgm_msgv_len.
+// In subsequent calls data from pgm_msgv structure are returned.
+ssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_)
+{
+ size_t raw_data_len = 0;
+
+ // We just sent all data from pgm_transport_recvmsgv up
+ // and have to return 0 that another engine in this thread is scheduled.
+ if (nbytes_rec == nbytes_processed && nbytes_rec > 0) {
+
+ // Reset all the counters.
+ nbytes_rec = 0;
+ nbytes_processed = 0;
+ pgm_msgv_processed = 0;
+ errno = EAGAIN;
+ return 0;
+ }
+
+ // If we have are going first time or if we have processed all pgm_msgv_t
+ // structure previously read from the pgm socket.
+ if (nbytes_rec == nbytes_processed) {
+
+ // Check program flow.
+ zmq_assert (pgm_msgv_processed == 0);
+ zmq_assert (nbytes_processed == 0);
+ zmq_assert (nbytes_rec == 0);
+
+ // Receive a vector of Application Protocol Domain Unit's (APDUs)
+ // from the transport.
+ pgm_error_t *pgm_error = NULL;
+
+ const int status = pgm_recvmsgv (sock, pgm_msgv,
+ pgm_msgv_len, MSG_ERRQUEUE, &nbytes_rec, &pgm_error);
+
+ // Invalid parameters.
+ zmq_assert (status != PGM_IO_STATUS_ERROR);
+
+ last_rx_status = status;
+
+ // In a case when no ODATA/RDATA fired POLLIN event (SPM...)
+ // pgm_recvmsg returns PGM_IO_STATUS_TIMER_PENDING.
+ if (status == PGM_IO_STATUS_TIMER_PENDING) {
+
+ zmq_assert (nbytes_rec == 0);
+
+ // In case if no RDATA/ODATA caused POLLIN 0 is
+ // returned.
+ nbytes_rec = 0;
+ errno = EBUSY;
+ return 0;
+ }
+
+ // Send SPMR, NAK, ACK is rate limited.
+ if (status == PGM_IO_STATUS_RATE_LIMITED) {
+
+ zmq_assert (nbytes_rec == 0);
+
+ // In case if no RDATA/ODATA caused POLLIN 0 is returned.
+ nbytes_rec = 0;
+ errno = ENOMEM;
+ return 0;
+ }
+
+ // No peers and hence no incoming packets.
+ if (status == PGM_IO_STATUS_WOULD_BLOCK) {
+
+ zmq_assert (nbytes_rec == 0);
+
+ // In case if no RDATA/ODATA caused POLLIN 0 is returned.
+ nbytes_rec = 0;
+ errno = EAGAIN;
+ return 0;
+ }
+
+ // Data loss.
+ if (status == PGM_IO_STATUS_RESET) {
+
+ struct pgm_sk_buff_t* skb = pgm_msgv [0].msgv_skb [0];
+
+ // Save lost data TSI.
+ *tsi_ = &skb->tsi;
+ nbytes_rec = 0;
+
+ // In case of dala loss -1 is returned.
+ errno = EINVAL;
+ pgm_free_skb (skb);
+ return -1;
+ }
+
+ zmq_assert (status == PGM_IO_STATUS_NORMAL);
+ }
+ else
+ {
+ zmq_assert (pgm_msgv_processed <= pgm_msgv_len);
+ }
+
+ // Zero byte payloads are valid in PGM, but not 0MQ protocol.
+ zmq_assert (nbytes_rec > 0);
+
+ // Only one APDU per pgm_msgv_t structure is allowed.
+ zmq_assert (pgm_msgv [pgm_msgv_processed].msgv_len == 1);
+
+ struct pgm_sk_buff_t* skb =
+ pgm_msgv [pgm_msgv_processed].msgv_skb [0];
+
+ // Take pointers from pgm_msgv_t structure.
+ *raw_data_ = skb->data;
+ raw_data_len = skb->len;
+
+ // Save current TSI.
+ *tsi_ = &skb->tsi;
+
+ // Move the the next pgm_msgv_t structure.
+ pgm_msgv_processed++;
+ zmq_assert (pgm_msgv_processed <= pgm_msgv_len);
+ nbytes_processed +=raw_data_len;
+
+ return raw_data_len;
+}
+
+void zmq::pgm_socket_t::process_upstream ()
+{
+ pgm_msgv_t dummy_msg;
+
+ size_t dummy_bytes = 0;
+ pgm_error_t *pgm_error = NULL;
+
+ const int status = pgm_recvmsgv (sock, &dummy_msg,
+ 1, MSG_ERRQUEUE, &dummy_bytes, &pgm_error);
+
+ // Invalid parameters.
+ zmq_assert (status != PGM_IO_STATUS_ERROR);
+
+ // No data should be returned.
+ zmq_assert (dummy_bytes == 0 && (status == PGM_IO_STATUS_TIMER_PENDING ||
+ status == PGM_IO_STATUS_RATE_LIMITED ||
+ status == PGM_IO_STATUS_WOULD_BLOCK));
+
+ last_rx_status = status;
+
+ if (status == PGM_IO_STATUS_TIMER_PENDING)
+ errno = EBUSY;
+ else if (status == PGM_IO_STATUS_RATE_LIMITED)
+ errno = ENOMEM;
+ else
+ errno = EAGAIN;
+}
+
+int zmq::pgm_socket_t::compute_sqns (int tpdu_)
+{
+ // Convert rate into B/ms.
+ uint64_t rate = ((uint64_t) options.rate) / 8;
+
+ // Get recovery interval in milliseconds.
+ uint64_t interval = options.recovery_ivl_msec >= 0 ?
+ options.recovery_ivl_msec :
+ options.recovery_ivl * 1000;
+
+ // Compute the size of the buffer in bytes.
+ uint64_t size = interval * rate;
+
+ // Translate the size into number of packets.
+ uint64_t sqns = size / tpdu_;
+
+ // Buffer should be able to contain at least one packet.
+ if (sqns == 0)
+ sqns = 1;
+
+ return (int) sqns;
+}
+
+#endif
+
diff --git a/src/0mq/pgm_socket.hpp b/src/0mq/pgm_socket.hpp
new file mode 100644
index 0000000..5ba8387
--- /dev/null
+++ b/src/0mq/pgm_socket.hpp
@@ -0,0 +1,119 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __PGM_SOCKET_HPP_INCLUDED__
+#define __PGM_SOCKET_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_OPENPGM
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+#define __PGM_WININT_H__
+#include <pgm/pgm.h>
+
+#ifdef ZMQ_HAVE_OSX
+#include <pgm/in.h>
+#endif
+
+#include "fd.hpp"
+#include "options.hpp"
+
+namespace zmq
+{
+ // Encapsulates PGM socket.
+ class pgm_socket_t
+ {
+
+ public:
+
+ // If receiver_ is true PGM transport is not generating SPM packets.
+ pgm_socket_t (bool receiver_, const options_t &options_);
+
+ // Closes the transport.
+ ~pgm_socket_t ();
+
+ // Initialize PGM network structures (GSI, GSRs).
+ int init (bool udp_encapsulation_, const char *network_);
+
+ // Get receiver fds and store them into user allocated memory.
+ void get_receiver_fds (fd_t *receive_fd_, fd_t *waiting_pipe_fd_);
+
+ // Get sender and receiver fds and store it to user allocated
+ // memory. Receive fd is used to process NAKs from peers.
+ void get_sender_fds (fd_t *send_fd_, fd_t *receive_fd_,
+ fd_t *rdata_notify_fd_, fd_t *pending_notify_fd_);
+
+ // Send data as one APDU, transmit window owned memory.
+ size_t send (unsigned char *data_, size_t data_len_);
+
+ // Returns max tsdu size without fragmentation.
+ size_t get_max_tsdu_size ();
+
+ // Receive data from pgm socket.
+ ssize_t receive (void **data_, const pgm_tsi_t **tsi_);
+
+ long get_rx_timeout ();
+ long get_tx_timeout ();
+
+ // POLLIN on sender side should mean NAK or SPMR receiving.
+ // process_upstream function is used to handle such a situation.
+ void process_upstream ();
+
+ private:
+
+ // Compute size of the buffer based on rate and recovery interval.
+ int compute_sqns (int tpdu_);
+
+ // OpenPGM transport.
+ pgm_sock_t* sock;
+
+ int last_rx_status, last_tx_status;
+
+ // Associated socket options.
+ options_t options;
+
+ // true when pgm_socket should create receiving side.
+ bool receiver;
+
+ // Array of pgm_msgv_t structures to store received data
+ // from the socket (pgm_transport_recvmsgv).
+ pgm_msgv_t *pgm_msgv;
+
+ // Size of pgm_msgv array.
+ size_t pgm_msgv_len;
+
+ // How many bytes were read from pgm socket.
+ size_t nbytes_rec;
+
+ // How many bytes were processed from last pgm socket read.
+ size_t nbytes_processed;
+
+ // How many messages from pgm_msgv were already sent up.
+ size_t pgm_msgv_processed;
+ };
+}
+#endif
+
+#endif
+
diff --git a/src/0mq/pipe.cpp b/src/0mq/pipe.cpp
new file mode 100644
index 0000000..8dcf577
--- /dev/null
+++ b/src/0mq/pipe.cpp
@@ -0,0 +1,409 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <new>
+
+#include "../include/zmq.h"
+
+#include "pipe.hpp"
+#include "likely.hpp"
+
+zmq::reader_t::reader_t (object_t *parent_, pipe_t *pipe_,
+ uint64_t lwm_) :
+ object_t (parent_),
+ active (true),
+ pipe (pipe_),
+ writer (NULL),
+ lwm (lwm_),
+ msgs_read (0),
+ sink (NULL),
+ terminating (false)
+{
+ // Note that writer is not set here. Writer will inform reader about its
+ // address once it is created (via set_writer method).
+}
+
+void zmq::reader_t::set_writer (writer_t *writer_)
+{
+ zmq_assert (!writer);
+ writer = writer_;
+}
+
+zmq::reader_t::~reader_t ()
+{
+ // Pipe as such is owned and deallocated by reader object.
+ // The point is that reader processes the last step of terminal
+ // handshaking (term_ack).
+ zmq_assert (pipe);
+
+ // First delete all the unread messages in the pipe. We have to do it by
+ // hand because zmq_msg_t is a POD, not a class, so there's no associated
+ // destructor.
+ zmq_msg_t msg;
+ while (pipe->read (&msg))
+ zmq_msg_close (&msg);
+
+ delete pipe;
+}
+
+void zmq::reader_t::set_event_sink (i_reader_events *sink_)
+{
+ zmq_assert (!sink);
+ sink = sink_;
+}
+
+bool zmq::reader_t::is_delimiter (zmq_msg_t &msg_)
+{
+ unsigned char *offset = 0;
+
+ return msg_.content == (void*) (offset + ZMQ_DELIMITER);
+}
+
+bool zmq::reader_t::check_read ()
+{
+ if (!active)
+ return false;
+
+ // Check if there's an item in the pipe.
+ if (!pipe->check_read ()) {
+ active = false;
+ return false;
+ }
+
+ // If the next item in the pipe is message delimiter,
+ // initiate its termination.
+ if (pipe->probe (is_delimiter)) {
+ zmq_msg_t msg;
+ bool ok = pipe->read (&msg);
+ zmq_assert (ok);
+ if (sink)
+ sink->delimited (this);
+ terminate ();
+ return false;
+ }
+
+ return true;
+}
+
+bool zmq::reader_t::read (zmq_msg_t *msg_)
+{
+ if (!active)
+ return false;
+
+ if (!pipe->read (msg_)) {
+ active = false;
+ return false;
+ }
+
+ // If delimiter was read, start termination process of the pipe.
+ unsigned char *offset = 0;
+ if (msg_->content == (void*) (offset + ZMQ_DELIMITER)) {
+ if (sink)
+ sink->delimited (this);
+ terminate ();
+ return false;
+ }
+
+ if (!(msg_->flags & ZMQ_MSG_MORE))
+ msgs_read++;
+
+ if (lwm > 0 && msgs_read % lwm == 0)
+ send_activate_writer (writer, msgs_read);
+
+ return true;
+}
+
+void zmq::reader_t::terminate ()
+{
+ // If termination was already started by the peer, do nothing.
+ if (terminating)
+ return;
+
+ active = false;
+ terminating = true;
+ send_pipe_term (writer);
+}
+
+void zmq::reader_t::process_activate_reader ()
+{
+ // Forward the event to the sink (either socket or session).
+ active = true;
+ sink->activated (this);
+}
+
+void zmq::reader_t::process_pipe_term_ack ()
+{
+ // At this point writer may already be deallocated.
+ // For safety's sake drop the reference to it.
+ writer = NULL;
+
+ // Notify owner about the termination.
+ zmq_assert (sink);
+ sink->terminated (this);
+
+ // Deallocate resources.
+ delete this;
+}
+
+zmq::writer_t::writer_t (object_t *parent_, pipe_t *pipe_, reader_t *reader_,
+ uint64_t hwm_, int64_t swap_size_) :
+ object_t (parent_),
+ active (true),
+ pipe (pipe_),
+ reader (reader_),
+ hwm (hwm_),
+ msgs_read (0),
+ msgs_written (0),
+ swap (NULL),
+ sink (NULL),
+ swapping (false),
+ pending_delimiter (false),
+ terminating (false)
+{
+ // Inform reader about the writer.
+ reader->set_writer (this);
+
+ // Open the swap file, if required.
+ if (swap_size_ > 0) {
+ swap = new (std::nothrow) swap_t (swap_size_);
+ alloc_assert (swap);
+ int rc = swap->init ();
+ zmq_assert (rc == 0);
+ }
+}
+
+zmq::writer_t::~writer_t ()
+{
+ if (swap)
+ delete swap;
+}
+
+void zmq::writer_t::set_event_sink (i_writer_events *sink_)
+{
+ zmq_assert (!sink);
+ sink = sink_;
+}
+
+bool zmq::writer_t::check_write (zmq_msg_t *msg_)
+{
+ // We've already checked and there's no space free for the new message.
+ // There's no point in checking once again.
+ if (unlikely (!active))
+ return false;
+
+ if (unlikely (swapping)) {
+ if (unlikely (!swap->fits (msg_))) {
+ active = false;
+ return false;
+ }
+ }
+ else {
+ if (unlikely (pipe_full ())) {
+ if (swap)
+ swapping = true;
+ else {
+ active = false;
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+bool zmq::writer_t::write (zmq_msg_t *msg_)
+{
+ if (unlikely (!check_write (msg_)))
+ return false;
+
+ if (unlikely (swapping)) {
+ bool stored = swap->store (msg_);
+ zmq_assert (stored);
+ if (!(msg_->flags & ZMQ_MSG_MORE))
+ swap->commit ();
+ return true;
+ }
+
+ pipe->write (*msg_, msg_->flags & ZMQ_MSG_MORE);
+ if (!(msg_->flags & ZMQ_MSG_MORE))
+ msgs_written++;
+
+ return true;
+}
+
+void zmq::writer_t::rollback ()
+{
+ // Remove incomplete message from the swap.
+ if (unlikely (swapping)) {
+ swap->rollback ();
+ return;
+ }
+
+ // Remove incomplete message from the pipe.
+ zmq_msg_t msg;
+ while (pipe->unwrite (&msg)) {
+ zmq_assert (msg.flags & ZMQ_MSG_MORE);
+ zmq_msg_close (&msg);
+ }
+}
+
+void zmq::writer_t::flush ()
+{
+ // In the swapping mode, flushing is automatically handled by swap object.
+ if (!swapping && !pipe->flush ())
+ send_activate_reader (reader);
+}
+
+void zmq::writer_t::terminate ()
+{
+ // Prevent double termination.
+ if (terminating)
+ return;
+ terminating = true;
+
+ // Mark the pipe as not available for writing.
+ active = false;
+
+ // Rollback any unfinished messages.
+ rollback ();
+
+ if (swapping) {
+ pending_delimiter = true;
+ return;
+ }
+
+ // Push delimiter into the pipe. Trick the compiler to belive that
+ // the tag is a valid pointer. Note that watermarks are not checked
+ // thus the delimiter can be written even though the pipe is full.
+ zmq_msg_t msg;
+ const unsigned char *offset = 0;
+ msg.content = (void*) (offset + ZMQ_DELIMITER);
+ msg.flags = 0;
+ pipe->write (msg, false);
+ flush ();
+}
+
+void zmq::writer_t::process_activate_writer (uint64_t msgs_read_)
+{
+ // Store the reader's message sequence number.
+ msgs_read = msgs_read_;
+
+ // If we are in the swapping mode, we have some messages in the swap.
+ // Given that pipe is now ready for writing we can move part of the
+ // swap into the pipe.
+ if (swapping) {
+ zmq_msg_t msg;
+ while (!pipe_full () && !swap->empty ()) {
+ swap->fetch(&msg);
+ pipe->write (msg, msg.flags & ZMQ_MSG_MORE);
+ if (!(msg.flags & ZMQ_MSG_MORE))
+ msgs_written++;
+ }
+ if (!pipe->flush ())
+ send_activate_reader (reader);
+
+ // There are no more messages in the swap. We can switch into
+ // standard in-memory mode.
+ if (swap->empty ()) {
+ swapping = false;
+
+ // Push delimiter into the pipe. Trick the compiler to belive that
+ // the tag is a valid pointer. Note that watermarks are not checked
+ // thus the delimiter can be written even though the pipe is full.
+ if (pending_delimiter) {
+ zmq_msg_t msg;
+ const unsigned char *offset = 0;
+ msg.content = (void*) (offset + ZMQ_DELIMITER);
+ msg.flags = 0;
+ pipe->write (msg, false);
+ flush ();
+ return;
+ }
+ }
+ }
+
+ // If the writer was non-active before, let's make it active
+ // (available for writing messages to).
+ if (!active && !terminating) {
+ active = true;
+ zmq_assert (sink);
+ sink->activated (this);
+ }
+}
+
+void zmq::writer_t::process_pipe_term ()
+{
+ send_pipe_term_ack (reader);
+
+ // The above command allows reader to deallocate itself and the pipe.
+ // For safety's sake we'll drop the pointers here.
+ reader = NULL;
+ pipe = NULL;
+
+ // Notify owner about the termination.
+ zmq_assert (sink);
+ sink->terminated (this);
+
+ // Deallocate the resources.
+ delete this;
+}
+
+bool zmq::writer_t::pipe_full ()
+{
+ return hwm > 0 && msgs_written - msgs_read == hwm;
+}
+
+void zmq::create_pipe (object_t *reader_parent_, object_t *writer_parent_,
+ uint64_t hwm_, int64_t swap_size_, reader_t **reader_, writer_t **writer_)
+{
+ // First compute the low water mark. Following point should be taken
+ // into consideration:
+ //
+ // 1. LWM has to be less than HWM.
+ // 2. LWM cannot be set to very low value (such as zero) as after filling
+ // the queue it would start to refill only after all the messages are
+ // read from it and thus unnecessarily hold the progress back.
+ // 3. LWM cannot be set to very high value (such as HWM-1) as it would
+ // result in lock-step filling of the queue - if a single message is
+ // read from a full queue, writer thread is resumed to write exactly one
+ // message to the queue and go back to sleep immediately. This would
+ // result in low performance.
+ //
+ // Given the 3. it would be good to keep HWM and LWM as far apart as
+ // possible to reduce the thread switching overhead to almost zero,
+ // say HWM-LWM should be max_wm_delta.
+ //
+ // That done, we still we have to account for the cases where
+ // HWM < max_wm_delta thus driving LWM to negative numbers.
+ // Let's make LWM 1/2 of HWM in such cases.
+ uint64_t lwm = (hwm_ > max_wm_delta * 2) ?
+ hwm_ - max_wm_delta : (hwm_ + 1) / 2;
+
+ // Create all three objects pipe consists of: the pipe per se, reader and
+ // writer. The pipe will be handled by reader and writer, its never passed
+ // to the user. Reader and writer are returned to the user.
+ pipe_t *pipe = new (std::nothrow) pipe_t ();
+ alloc_assert (pipe);
+ *reader_ = new (std::nothrow) reader_t (reader_parent_, pipe, lwm);
+ alloc_assert (*reader_);
+ *writer_ = new (std::nothrow) writer_t (writer_parent_, pipe, *reader_,
+ hwm_, swap_size_);
+ alloc_assert (*writer_);
+}
diff --git a/src/0mq/pipe.hpp b/src/0mq/pipe.hpp
new file mode 100644
index 0000000..b4a0ffa
--- /dev/null
+++ b/src/0mq/pipe.hpp
@@ -0,0 +1,214 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_PIPE_HPP_INCLUDED__
+#define __ZMQ_PIPE_HPP_INCLUDED__
+
+#include "../include/zmq.h"
+
+#include "stdint.hpp"
+#include "array.hpp"
+#include "ypipe.hpp"
+#include "swap.hpp"
+#include "config.hpp"
+#include "object.hpp"
+
+namespace zmq
+{
+
+ // Creates a pipe. Returns pointer to reader and writer objects.
+ void create_pipe (object_t *reader_parent_, object_t *writer_parent_,
+ uint64_t hwm_, int64_t swap_size_, class reader_t **reader_,
+ class writer_t **writer_);
+
+ // The shutdown mechanism for pipe works as follows: Either endpoint
+ // (or even both of them) can ask pipe to terminate by calling 'terminate'
+ // method. Pipe then terminates in asynchronous manner. When the part of
+ // the shutdown tied to the endpoint is done it triggers 'terminated'
+ // event. When endpoint processes the event and returns, associated
+ // reader/writer object is deallocated.
+
+ typedef ypipe_t <zmq_msg_t, message_pipe_granularity> pipe_t;
+
+ struct i_reader_events
+ {
+ virtual ~i_reader_events () {}
+
+ virtual void terminated (class reader_t *pipe_) = 0;
+ virtual void activated (class reader_t *pipe_) = 0;
+ virtual void delimited (class reader_t *pipe_) = 0;
+ };
+
+ class reader_t : public object_t, public array_item_t
+ {
+ friend void create_pipe (object_t*, object_t*, uint64_t,
+ int64_t, reader_t**, writer_t**);
+ friend class writer_t;
+
+ public:
+
+ // Specifies the object to get events from the reader.
+ void set_event_sink (i_reader_events *endpoint_);
+
+ // Returns true if there is at least one message to read in the pipe.
+ bool check_read ();
+
+ // Reads a message to the underlying pipe.
+ bool read (zmq_msg_t *msg_);
+
+ // Ask pipe to terminate.
+ void terminate ();
+
+ private:
+
+ reader_t (class object_t *parent_, pipe_t *pipe_, uint64_t lwm_);
+ ~reader_t ();
+
+ // To be called only by writer itself!
+ void set_writer (class writer_t *writer_);
+
+ // Command handlers.
+ void process_activate_reader ();
+ void process_pipe_term_ack ();
+
+ // Returns true if the message is delimiter; false otherwise.
+ static bool is_delimiter (zmq_msg_t &msg_);
+
+ // True, if pipe can be read from.
+ bool active;
+
+ // The underlying pipe.
+ pipe_t *pipe;
+
+ // Pipe writer associated with the other side of the pipe.
+ class writer_t *writer;
+
+ // Low watermark for in-memory storage (in bytes).
+ uint64_t lwm;
+
+ // Number of messages read so far.
+ uint64_t msgs_read;
+
+ // Sink for the events (either the socket of the session).
+ i_reader_events *sink;
+
+ // True is 'terminate' method was called or delimiter
+ // was read from the pipe.
+ bool terminating;
+
+ reader_t (const reader_t&);
+ const reader_t &operator = (const reader_t&);
+ };
+
+ struct i_writer_events
+ {
+ virtual ~i_writer_events () {}
+
+ virtual void terminated (class writer_t *pipe_) = 0;
+ virtual void activated (class writer_t *pipe_) = 0;
+ };
+
+ class writer_t : public object_t, public array_item_t
+ {
+ friend void create_pipe (object_t*, object_t*, uint64_t,
+ int64_t, reader_t**, writer_t**);
+
+ public:
+
+ // Specifies the object to get events from the writer.
+ void set_event_sink (i_writer_events *endpoint_);
+
+ // Checks whether messages can be written to the pipe.
+ // If writing the message would cause high watermark and (optionally)
+ // if the swap is full, the function returns false.
+ bool check_write (zmq_msg_t *msg_);
+
+ // Writes a message to the underlying pipe. Returns false if the
+ // message cannot be written because high watermark was reached.
+ bool write (zmq_msg_t *msg_);
+
+ // Remove unfinished part of a message from the pipe.
+ void rollback ();
+
+ // Flush the messages downsteam.
+ void flush ();
+
+ // Ask pipe to terminate.
+ void terminate ();
+
+ private:
+
+ writer_t (class object_t *parent_, pipe_t *pipe_, reader_t *reader_,
+ uint64_t hwm_, int64_t swap_size_);
+ ~writer_t ();
+
+ // Command handlers.
+ void process_activate_writer (uint64_t msgs_read_);
+ void process_pipe_term ();
+
+ // Tests whether underlying pipe is already full. The swap is not
+ // taken into account.
+ bool pipe_full ();
+
+ // True, if this object can be written to. Undelying ypipe may be full
+ // but as long as there's swap space available, this flag is true.
+ bool active;
+
+ // The underlying pipe.
+ pipe_t *pipe;
+
+ // Pipe reader associated with the other side of the pipe.
+ reader_t *reader;
+
+ // High watermark for in-memory storage (in bytes).
+ uint64_t hwm;
+
+ // Last confirmed number of messages read from the pipe.
+ // The actual number can be higher.
+ uint64_t msgs_read;
+
+ // Number of messages we have written so far.
+ uint64_t msgs_written;
+
+ // Pointer to the message swap. If NULL, messages are always
+ // kept in main memory.
+ swap_t *swap;
+
+ // Sink for the events (either the socket or the session).
+ i_writer_events *sink;
+
+ // If true, swap is active. New messages are to be written to the swap.
+ bool swapping;
+
+ // If true, there's a delimiter to be written to the pipe after the
+ // swap is empied.
+ bool pending_delimiter;
+
+ // True is 'terminate' method was called of 'pipe_term' command
+ // arrived from the reader.
+ bool terminating;
+
+ writer_t (const writer_t&);
+ const writer_t &operator = (const writer_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/platform.hpp b/src/0mq/platform.hpp
new file mode 100644
index 0000000..f9672ca
--- /dev/null
+++ b/src/0mq/platform.hpp
@@ -0,0 +1,243 @@
+/* src/platform.hpp.in. Generated from configure.in by autoheader. */
+
+/* Define to 1 if you have the <alloca.h> header file. */
+#define HAVE_ALLOCA_H
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#define HAVE_ARPA_INET_H
+
+/* Define to 1 if you have the `clock_gettime' function. */
+#define HAVE_CLOCK_GETTIME
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define HAVE_ERRNO_H
+
+/* Define to 1 if you have the `freeifaddrs' function. */
+#define HAVE_FREEIFADDRS
+
+/* Define to 1 if you have the `getifaddrs' function. */
+#define HAVE_GETIFADDRS
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#define HAVE_GETTIMEOFDAY
+
+/* Define to 1 if you have the <ifaddrs.h> header file. */
+#define HAVE_IFADDRS_H
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H
+
+/* Define to 1 if you have the `crypto' library (-lcrypto). */
+#undef HAVE_LIBCRYPTO
+
+/* Define to 1 if you have the `dcekt' library (-ldcekt). */
+#undef HAVE_LIBDCEKT
+
+/* Define to 1 if you have the `iphlpapi' library (-liphlpapi). */
+#undef HAVE_LIBIPHLPAPI
+
+/* Define to 1 if you have the `nsl' library (-lnsl). */
+#undef HAVE_LIBNSL
+
+/* Define to 1 if you have the `pthread' library (-lpthread). */
+#define HAVE_LIBPTHREAD
+
+/* Define to 1 if you have the `rpcrt4' library (-lrpcrt4). */
+#undef HAVE_LIBRPCRT4
+
+/* Define to 1 if you have the `rt' library (-lrt). */
+#define HAVE_LIBRT
+
+/* Define to 1 if you have the `socket' library (-lsocket). */
+#define HAVE_LIBSOCKET
+
+/* Define to 1 if you have the `uuid' library (-luuid). */
+#define HAVE_LIBUUID
+
+/* Define to 1 if you have the `ws2_32' library (-lws2_32). */
+#undef HAVE_LIBWS2_32
+
+/* Define to 1 if you have the <limits.h> header file. */
+#define HAVE_LIMITS_H
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H
+
+/* Define to 1 if you have the `memset' function. */
+#define HAVE_MEMSET
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define HAVE_NETINET_IN_H
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#define HAVE_NETINET_TCP_H
+
+/* Define to 1 if you have the `perror' function. */
+#define HAVE_PERROR
+
+/* Define to 1 if you have the `socket' function. */
+#define HAVE_SOCKET
+
+/* Whether SOCK_CLOEXEC is defined and functioning. */
+#undef HAVE_SOCK_CLOEXEC
+
+/* Define to 1 if stdbool.h conforms to C99. */
+#define HAVE_STDBOOL_H
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define HAVE_STDDEF_H
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define HAVE_SYS_SOCKET_H
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define HAVE_SYS_TIME_H
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H
+
+/* Define to 1 if you have the <time.h> header file. */
+#define HAVE_TIME_H
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H
+
+/* Define to 1 if you have the <windows.h> header file. */
+#undef HAVE_WINDOWS_H
+
+/* Define to 1 if the system has the type `_Bool'. */
+#undef HAVE__BOOL
+
+/* Define to the sub-directory in which libtool stores uninstalled libraries.
+ */
+#undef LT_OBJDIR
+
+/* Define to 1 if your C compiler doesn't accept -c and -o together. */
+#undef NO_MINUS_C_MINUS_O
+
+/* Name of package */
+#define PACKAGE "HDSync"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "http://syncstarter.org/hdsync"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "HDSync"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "HDSync"
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL "http://syncstarter.org"
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#undef RETSIGTYPE
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define TIME_WITH_SYS_TIME
+
+/* Version number of package */
+#undef VERSION
+
+/* Force to use mutexes */
+#undef ZMQ_FORCE_MUTEXES
+
+/* Have AIX OS */
+#undef ZMQ_HAVE_AIX
+
+/* Have Android OS */
+#undef ZMQ_HAVE_ANDROID
+
+/* Have Cygwin */
+#undef ZMQ_HAVE_CYGWIN
+
+/* Have FreeBSD OS */
+#undef ZMQ_HAVE_FREEBSD
+
+/* Have HPUX OS */
+#undef ZMQ_HAVE_HPUX
+
+/* Have ifaddrs.h header. */
+#undef ZMQ_HAVE_IFADDRS
+
+/* Have Linux OS */
+#define ZMQ_HAVE_LINUX
+
+/* Have MinGW32 */
+#undef ZMQ_HAVE_MINGW32
+
+/* Have NetBSD OS */
+#undef ZMQ_HAVE_NETBSD
+
+/* Have OpenBSD OS */
+#undef ZMQ_HAVE_OPENBSD
+
+/* Have OpenPGM extension */
+#define ZMQ_HAVE_OPENPGM
+
+/* Have DarwinOSX OS */
+#undef ZMQ_HAVE_OSX
+
+/* Have QNX Neutrino OS */
+#undef ZMQ_HAVE_QNXNTO
+
+/* Have Solaris OS */
+#undef ZMQ_HAVE_SOLARIS
+
+/* Have Windows OS */
+#undef ZMQ_HAVE_WINDOWS
+
+/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>,
+ <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
+ #define below would cause a syntax error. */
+#undef _UINT32_T
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+#undef inline
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+#undef size_t
+
+/* Define to `int' if <sys/types.h> does not define. */
+#undef ssize_t
+
+/* Define to the type of an unsigned integer type of width exactly 32 bits if
+ such a type exists and the standard includes do not define it. */
+#undef uint32_t
+
+/* Define to empty if the keyword `volatile' does not work. Warning: valid
+ code using `volatile' can become incorrect without. Disable with care. */
+#undef volatile
diff --git a/src/0mq/poll.cpp b/src/0mq/poll.cpp
new file mode 100644
index 0000000..6a84d2e
--- /dev/null
+++ b/src/0mq/poll.cpp
@@ -0,0 +1,180 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
+ defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
+ defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
+ defined ZMQ_HAVE_NETBSD
+
+#include <sys/types.h>
+#include <sys/time.h>
+#include <poll.h>
+#include <algorithm>
+
+#include "poll.hpp"
+#include "err.hpp"
+#include "config.hpp"
+#include "i_poll_events.hpp"
+
+zmq::poll_t::poll_t () :
+ retired (false),
+ stopping (false)
+{
+}
+
+zmq::poll_t::~poll_t ()
+{
+ worker.stop ();
+}
+
+zmq::poll_t::handle_t zmq::poll_t::add_fd (fd_t fd_, i_poll_events *events_)
+{
+ // If the file descriptor table is too small expand it.
+ fd_table_t::size_type sz = fd_table.size ();
+ if (sz <= (fd_table_t::size_type) fd_) {
+ fd_table.resize (fd_ + 1);
+ while (sz != (fd_table_t::size_type) (fd_ + 1)) {
+ fd_table [sz].index = retired_fd;
+ ++sz;
+ }
+ }
+
+ pollfd pfd = {fd_, 0, 0};
+ pollset.push_back (pfd);
+ assert (fd_table [fd_].index == retired_fd);
+
+ fd_table [fd_].index = pollset.size() - 1;
+ fd_table [fd_].events = events_;
+
+ // Increase the load metric of the thread.
+ adjust_load (1);
+
+ return fd_;
+}
+
+void zmq::poll_t::rm_fd (handle_t handle_)
+{
+ fd_t index = fd_table [handle_].index;
+ assert (index != retired_fd);
+
+ // Mark the fd as unused.
+ pollset [index].fd = retired_fd;
+ fd_table [handle_].index = retired_fd;
+ retired = true;
+
+ // Decrease the load metric of the thread.
+ adjust_load (-1);
+}
+
+void zmq::poll_t::set_pollin (handle_t handle_)
+{
+ int index = fd_table [handle_].index;
+ pollset [index].events |= POLLIN;
+}
+
+void zmq::poll_t::reset_pollin (handle_t handle_)
+{
+ int index = fd_table [handle_].index;
+ pollset [index].events &= ~((short) POLLIN);
+}
+
+void zmq::poll_t::set_pollout (handle_t handle_)
+{
+ int index = fd_table [handle_].index;
+ pollset [index].events |= POLLOUT;
+}
+
+void zmq::poll_t::reset_pollout (handle_t handle_)
+{
+ int index = fd_table [handle_].index;
+ pollset [index].events &= ~((short) POLLOUT);
+}
+
+void zmq::poll_t::start ()
+{
+ worker.start (worker_routine, this);
+}
+
+void zmq::poll_t::stop ()
+{
+ stopping = true;
+}
+
+void zmq::poll_t::loop ()
+{
+ while (!stopping) {
+
+ // Execute any due timers.
+ int timeout = (int) execute_timers ();
+
+ // Wait for events.
+ int rc = poll (&pollset [0], pollset.size (), timeout ? timeout : -1);
+ if (rc == -1 && errno == EINTR)
+ continue;
+ errno_assert (rc != -1);
+
+
+ // If there are no events (i.e. it's a timeout) there's no point
+ // in checking the pollset.
+ if (rc == 0)
+ continue;
+
+ for (pollset_t::size_type i = 0; i != pollset.size (); i++) {
+
+ zmq_assert (!(pollset [i].revents & POLLNVAL));
+ if (pollset [i].fd == retired_fd)
+ continue;
+ if (pollset [i].revents & (POLLERR | POLLHUP))
+ fd_table [pollset [i].fd].events->in_event ();
+ if (pollset [i].fd == retired_fd)
+ continue;
+ if (pollset [i].revents & POLLOUT)
+ fd_table [pollset [i].fd].events->out_event ();
+ if (pollset [i].fd == retired_fd)
+ continue;
+ if (pollset [i].revents & POLLIN)
+ fd_table [pollset [i].fd].events->in_event ();
+ }
+
+ // Clean up the pollset and update the fd_table accordingly.
+ if (retired) {
+ pollset_t::size_type i = 0;
+ while (i < pollset.size ()) {
+ if (pollset [i].fd == retired_fd)
+ pollset.erase (pollset.begin () + i);
+ else {
+ fd_table [pollset [i].fd].index = i;
+ i ++;
+ }
+ }
+ retired = false;
+ }
+ }
+}
+
+void zmq::poll_t::worker_routine (void *arg_)
+{
+ ((poll_t*) arg_)->loop ();
+}
+
+#endif
diff --git a/src/0mq/poll.hpp b/src/0mq/poll.hpp
new file mode 100644
index 0000000..3a18d03
--- /dev/null
+++ b/src/0mq/poll.hpp
@@ -0,0 +1,104 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_POLL_HPP_INCLUDED__
+#define __ZMQ_POLL_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
+ defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
+ defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
+ defined ZMQ_HAVE_NETBSD
+
+#include <poll.h>
+#include <stddef.h>
+#include <vector>
+
+#include "fd.hpp"
+#include "thread.hpp"
+#include "poller_base.hpp"
+
+namespace zmq
+{
+
+ // Implements socket polling mechanism using the POSIX.1-2001
+ // poll() system call.
+
+ class poll_t : public poller_base_t
+ {
+ public:
+
+ typedef fd_t handle_t;
+
+ poll_t ();
+ ~poll_t ();
+
+ // "poller" concept.
+ handle_t add_fd (fd_t fd_, struct i_poll_events *events_);
+ void rm_fd (handle_t handle_);
+ void set_pollin (handle_t handle_);
+ void reset_pollin (handle_t handle_);
+ void set_pollout (handle_t handle_);
+ void reset_pollout (handle_t handle_);
+ void start ();
+ void stop ();
+
+ private:
+
+ // Main worker thread routine.
+ static void worker_routine (void *arg_);
+
+ // Main event loop.
+ void loop ();
+
+ struct fd_entry_t
+ {
+ fd_t index;
+ struct i_poll_events *events;
+ };
+
+ // This table stores data for registered descriptors.
+ typedef std::vector <fd_entry_t> fd_table_t;
+ fd_table_t fd_table;
+
+ // Pollset to pass to the poll function.
+ typedef std::vector <pollfd> pollset_t;
+ pollset_t pollset;
+
+ // If true, there's at least one retired event source.
+ bool retired;
+
+ // If true, thread is in the process of shutting down.
+ bool stopping;
+
+ // Handle of the physical thread doing the I/O work.
+ thread_t worker;
+
+ poll_t (const poll_t&);
+ const poll_t &operator = (const poll_t&);
+ };
+
+}
+
+#endif
+
+#endif
diff --git a/src/0mq/poller.hpp b/src/0mq/poller.hpp
new file mode 100644
index 0000000..10fafb9
--- /dev/null
+++ b/src/0mq/poller.hpp
@@ -0,0 +1,73 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_POLLER_HPP_INCLUDED__
+#define __ZMQ_POLLER_HPP_INCLUDED__
+
+#include "epoll.hpp"
+#include "poll.hpp"
+#include "select.hpp"
+#include "devpoll.hpp"
+#include "kqueue.hpp"
+
+namespace zmq
+{
+
+#if defined ZMQ_FORCE_SELECT
+ typedef select_t poller_t;
+#elif defined ZMQ_FORCE_POLL
+ typedef poll_t poller_t;
+#elif defined ZMQ_FORCE_EPOLL
+ typedef epoll_t poller_t;
+#elif defined ZMQ_FORCE_DEVPOLL
+ typedef devpoll_t poller_t;
+#elif defined ZMQ_FORCE_KQUEUE
+ typedef kqueue_t poller_t;
+#elif defined ZMQ_HAVE_LINUX
+ typedef epoll_t poller_t;
+#elif defined ZMQ_HAVE_WINDOWS
+ typedef select_t poller_t;
+#elif defined ZMQ_HAVE_FREEBSD
+ typedef kqueue_t poller_t;
+#elif defined ZMQ_HAVE_OPENBSD
+ typedef kqueue_t poller_t;
+#elif defined ZMQ_HAVE_NETBSD
+ typedef kqueue_t poller_t;
+#elif defined ZMQ_HAVE_SOLARIS
+ typedef devpoll_t poller_t;
+#elif defined ZMQ_HAVE_OSX
+ typedef kqueue_t poller_t;
+#elif defined ZMQ_HAVE_QNXNTO
+ typedef poll_t poller_t;
+#elif defined ZMQ_HAVE_AIX
+ typedef poll_t poller_t;
+#elif defined ZMQ_HAVE_HPUX
+ typedef devpoll_t poller_t;
+#elif defined ZMQ_HAVE_OPENVMS
+ typedef select_t poller_t;
+#elif defined ZMQ_HAVE_CYGWIN
+ typedef select_t poller_t;
+#else
+#error Unsupported platform
+#endif
+
+}
+
+#endif
diff --git a/src/0mq/poller_base.cpp b/src/0mq/poller_base.cpp
new file mode 100644
index 0000000..d5fb985
--- /dev/null
+++ b/src/0mq/poller_base.cpp
@@ -0,0 +1,99 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "poller_base.hpp"
+#include "i_poll_events.hpp"
+#include "err.hpp"
+
+zmq::poller_base_t::poller_base_t ()
+{
+}
+
+zmq::poller_base_t::~poller_base_t ()
+{
+ // Make sure there is no more load on the shutdown.
+ zmq_assert (get_load () == 0);
+}
+
+int zmq::poller_base_t::get_load ()
+{
+ return load.get ();
+}
+
+void zmq::poller_base_t::adjust_load (int amount_)
+{
+ if (amount_ > 0)
+ load.add (amount_);
+ else if (amount_ < 0)
+ load.sub (-amount_);
+}
+
+void zmq::poller_base_t::add_timer (int timeout_, i_poll_events *sink_, int id_)
+{
+ uint64_t expiration = clock.now_ms () + timeout_;
+ timer_info_t info = {sink_, id_};
+ timers.insert (timers_t::value_type (expiration, info));
+}
+
+void zmq::poller_base_t::cancel_timer (i_poll_events *sink_, int id_)
+{
+ // Complexity of this operation is O(n). We assume it is rarely used.
+ for (timers_t::iterator it = timers.begin (); it != timers.end (); ++it)
+ if (it->second.sink == sink_ && it->second.id == id_) {
+ timers.erase (it);
+ return;
+ }
+
+ // Timer not found.
+ zmq_assert (false);
+}
+
+uint64_t zmq::poller_base_t::execute_timers ()
+{
+ // Fast track.
+ if (timers.empty ())
+ return 0;
+
+ // Get the current time.
+ uint64_t current = clock.now_ms ();
+
+ // Execute the timers that are already due.
+ timers_t::iterator it = timers.begin ();
+ while (it != timers.end ()) {
+
+ // If we have to wait to execute the item, same will be true about
+ // all the following items (multimap is sorted). Thus we can stop
+ // checking the subsequent timers and return the time to wait for
+ // the next timer (at least 1ms).
+ if (it->first > current)
+ return it->first - current;
+
+ // Trigger the timer.
+ it->second.sink->timer_event (it->second.id);
+
+ // Remove it from the list of active timers.
+ timers_t::iterator o = it;
+ ++it;
+ timers.erase (o);
+ }
+
+ // There are no more timers.
+ return 0;
+}
diff --git a/src/0mq/poller_base.hpp b/src/0mq/poller_base.hpp
new file mode 100644
index 0000000..44fe9f1
--- /dev/null
+++ b/src/0mq/poller_base.hpp
@@ -0,0 +1,84 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_POLLER_BASE_HPP_INCLUDED__
+#define __ZMQ_POLLER_BASE_HPP_INCLUDED__
+
+#include <map>
+
+#include "clock.hpp"
+#include "atomic_counter.hpp"
+
+namespace zmq
+{
+
+ class poller_base_t
+ {
+ public:
+
+ poller_base_t ();
+ virtual ~poller_base_t ();
+
+ // Returns load of the poller. Note that this function can be
+ // invoked from a different thread!
+ int get_load ();
+
+ // Add a timeout to expire in timeout_ milliseconds. After the
+ // expiration timer_event on sink_ object will be called with
+ // argument set to id_.
+ void add_timer (int timeout_, struct i_poll_events *sink_, int id_);
+
+ // Cancel the timer created by sink_ object with ID equal to id_.
+ void cancel_timer (struct i_poll_events *sink_, int id_);
+
+ protected:
+
+ // Called by individual poller implementations to manage the load.
+ void adjust_load (int amount_);
+
+ // Executes any timers that are due. Returns number of milliseconds
+ // to wait to match the next timer or 0 meaning "no timers".
+ uint64_t execute_timers ();
+
+ private:
+
+ // Clock instance private to this I/O thread.
+ clock_t clock;
+
+ // List of active timers.
+ struct timer_info_t
+ {
+ struct i_poll_events *sink;
+ int id;
+ };
+ typedef std::multimap <uint64_t, timer_info_t> timers_t;
+ timers_t timers;
+
+ // Load of the poller. Currently the number of file descriptors
+ // registered.
+ atomic_counter_t load;
+
+ poller_base_t (const poller_base_t&);
+ const poller_base_t &operator = (const poller_base_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/pub.cpp b/src/0mq/pub.cpp
new file mode 100644
index 0000000..74f07fc
--- /dev/null
+++ b/src/0mq/pub.cpp
@@ -0,0 +1,31 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "pub.hpp"
+
+zmq::pub_t::pub_t (class ctx_t *parent_, uint32_t tid_) :
+ xpub_t (parent_, tid_)
+{
+ options.type = ZMQ_PUB;
+}
+
+zmq::pub_t::~pub_t ()
+{
+}
diff --git a/src/0mq/pub.hpp b/src/0mq/pub.hpp
new file mode 100644
index 0000000..e69af3c
--- /dev/null
+++ b/src/0mq/pub.hpp
@@ -0,0 +1,44 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_PUB_HPP_INCLUDED__
+#define __ZMQ_PUB_HPP_INCLUDED__
+
+#include "xpub.hpp"
+
+namespace zmq
+{
+
+ class pub_t : public xpub_t
+ {
+ public:
+
+ pub_t (class ctx_t *parent_, uint32_t tid_);
+ ~pub_t ();
+
+ private:
+
+ pub_t (const pub_t&);
+ const pub_t &operator = (const pub_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/pull.cpp b/src/0mq/pull.cpp
new file mode 100644
index 0000000..a8c2466
--- /dev/null
+++ b/src/0mq/pull.cpp
@@ -0,0 +1,61 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "pull.hpp"
+#include "err.hpp"
+
+zmq::pull_t::pull_t (class ctx_t *parent_, uint32_t tid_) :
+ socket_base_t (parent_, tid_),
+ fq (this)
+{
+ options.type = ZMQ_PULL;
+ options.requires_in = true;
+ options.requires_out = false;
+}
+
+zmq::pull_t::~pull_t ()
+{
+}
+
+void zmq::pull_t::xattach_pipes (class reader_t *inpipe_,
+ class writer_t *outpipe_, const blob_t &peer_identity_)
+{
+ zmq_assert (inpipe_ && !outpipe_);
+ fq.attach (inpipe_);
+}
+
+void zmq::pull_t::process_term (int linger_)
+{
+ fq.terminate ();
+ socket_base_t::process_term (linger_);
+}
+
+int zmq::pull_t::xrecv (zmq_msg_t *msg_, int flags_)
+{
+ return fq.recv (msg_, flags_);
+}
+
+bool zmq::pull_t::xhas_in ()
+{
+ return fq.has_in ();
+}
+
diff --git a/src/0mq/pull.hpp b/src/0mq/pull.hpp
new file mode 100644
index 0000000..95084ba
--- /dev/null
+++ b/src/0mq/pull.hpp
@@ -0,0 +1,60 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_PULL_HPP_INCLUDED__
+#define __ZMQ_PULL_HPP_INCLUDED__
+
+#include "socket_base.hpp"
+#include "fq.hpp"
+
+namespace zmq
+{
+
+ class pull_t : public socket_base_t
+ {
+ public:
+
+ pull_t (class ctx_t *parent_, uint32_t tid_);
+ ~pull_t ();
+
+ protected:
+
+ // Overloads of functions from socket_base_t.
+ void xattach_pipes (class reader_t *inpipe_, class writer_t *outpipe_,
+ const blob_t &peer_identity_);
+ int xrecv (zmq_msg_t *msg_, int flags_);
+ bool xhas_in ();
+
+ private:
+
+ // Hook into the termination process.
+ void process_term (int linger_);
+
+ // Fair queueing object for inbound pipes.
+ fq_t fq;
+
+ pull_t (const pull_t&);
+ const pull_t &operator = (const pull_t&);
+
+ };
+
+}
+
+#endif
diff --git a/src/0mq/push.cpp b/src/0mq/push.cpp
new file mode 100644
index 0000000..072994f
--- /dev/null
+++ b/src/0mq/push.cpp
@@ -0,0 +1,62 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "push.hpp"
+#include "err.hpp"
+#include "pipe.hpp"
+
+zmq::push_t::push_t (class ctx_t *parent_, uint32_t tid_) :
+ socket_base_t (parent_, tid_),
+ lb (this)
+{
+ options.type = ZMQ_PUSH;
+ options.requires_in = false;
+ options.requires_out = true;
+}
+
+zmq::push_t::~push_t ()
+{
+}
+
+void zmq::push_t::xattach_pipes (class reader_t *inpipe_,
+ class writer_t *outpipe_, const blob_t &peer_identity_)
+{
+ zmq_assert (!inpipe_ && outpipe_);
+ lb.attach (outpipe_);
+}
+
+void zmq::push_t::process_term (int linger_)
+{
+ lb.terminate ();
+ socket_base_t::process_term (linger_);
+}
+
+int zmq::push_t::xsend (zmq_msg_t *msg_, int flags_)
+{
+ return lb.send (msg_, flags_);
+}
+
+bool zmq::push_t::xhas_out ()
+{
+ return lb.has_out ();
+}
+
diff --git a/src/0mq/push.hpp b/src/0mq/push.hpp
new file mode 100644
index 0000000..f04b25f
--- /dev/null
+++ b/src/0mq/push.hpp
@@ -0,0 +1,59 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_PUSH_HPP_INCLUDED__
+#define __ZMQ_PUSH_HPP_INCLUDED__
+
+#include "socket_base.hpp"
+#include "lb.hpp"
+
+namespace zmq
+{
+
+ class push_t : public socket_base_t
+ {
+ public:
+
+ push_t (class ctx_t *parent_, uint32_t tid_);
+ ~push_t ();
+
+ protected:
+
+ // Overloads of functions from socket_base_t.
+ void xattach_pipes (class reader_t *inpipe_, class writer_t *outpipe_,
+ const blob_t &peer_identity_);
+ int xsend (zmq_msg_t *msg_, int flags_);
+ bool xhas_out ();
+
+ private:
+
+ // Hook into the termination process.
+ void process_term (int linger_);
+
+ // Load balancer managing the outbound pipes.
+ lb_t lb;
+
+ push_t (const push_t&);
+ const push_t &operator = (const push_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/reaper.cpp b/src/0mq/reaper.cpp
new file mode 100644
index 0000000..f94f7c1
--- /dev/null
+++ b/src/0mq/reaper.cpp
@@ -0,0 +1,121 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "reaper.hpp"
+#include "socket_base.hpp"
+#include "err.hpp"
+
+zmq::reaper_t::reaper_t (class ctx_t *ctx_, uint32_t tid_) :
+ object_t (ctx_, tid_),
+ sockets (0),
+ terminating (false)
+{
+ poller = new (std::nothrow) poller_t;
+ alloc_assert (poller);
+
+ mailbox_handle = poller->add_fd (mailbox.get_fd (), this);
+ poller->set_pollin (mailbox_handle);
+}
+
+zmq::reaper_t::~reaper_t ()
+{
+ delete poller;
+}
+
+zmq::mailbox_t *zmq::reaper_t::get_mailbox ()
+{
+ return &mailbox;
+}
+
+void zmq::reaper_t::start ()
+{
+ // Start the thread.
+ poller->start ();
+}
+
+void zmq::reaper_t::stop ()
+{
+ send_stop ();
+}
+
+void zmq::reaper_t::in_event ()
+{
+ while (true) {
+
+ // Get the next command. If there is none, exit.
+ command_t cmd;
+ int rc = mailbox.recv (&cmd, 0);
+ if (rc != 0 && errno == EINTR)
+ continue;
+ if (rc != 0 && errno == EAGAIN)
+ break;
+ errno_assert (rc == 0);
+
+ // Process the command.
+ cmd.destination->process_command (cmd);
+ }
+}
+
+void zmq::reaper_t::out_event ()
+{
+ zmq_assert (false);
+}
+
+void zmq::reaper_t::timer_event (int id_)
+{
+ zmq_assert (false);
+}
+
+void zmq::reaper_t::process_stop ()
+{
+ terminating = true;
+
+ // If there are no sockets beig reaped finish immediately.
+ if (!sockets) {
+ send_done ();
+ poller->rm_fd (mailbox_handle);
+ poller->stop ();
+ }
+}
+
+void zmq::reaper_t::process_reap (socket_base_t *socket_)
+{
+ // Add the socket to the poller.
+ socket_->start_reaping (poller);
+
+ // Start termination of associated I/O object hierarchy.
+ socket_->terminate ();
+ socket_->check_destroy ();
+
+ ++sockets;
+}
+
+void zmq::reaper_t::process_reaped ()
+{
+ --sockets;
+
+ // If reaped was already asked to terminate and there are no more sockets,
+ // finish immediately.
+ if (!sockets && terminating) {
+ send_done ();
+ poller->rm_fd (mailbox_handle);
+ poller->stop ();
+ }
+}
diff --git a/src/0mq/reaper.hpp b/src/0mq/reaper.hpp
new file mode 100644
index 0000000..edcc319
--- /dev/null
+++ b/src/0mq/reaper.hpp
@@ -0,0 +1,77 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_REAPER_HPP_INCLUDED__
+#define __ZMQ_REAPER_HPP_INCLUDED__
+
+#include "object.hpp"
+#include "mailbox.hpp"
+#include "poller.hpp"
+#include "i_poll_events.hpp"
+
+namespace zmq
+{
+
+ class reaper_t : public object_t, public i_poll_events
+ {
+ public:
+
+ reaper_t (class ctx_t *ctx_, uint32_t tid_);
+ ~reaper_t ();
+
+ mailbox_t *get_mailbox ();
+
+ void start ();
+ void stop ();
+
+ // i_poll_events implementation.
+ void in_event ();
+ void out_event ();
+ void timer_event (int id_);
+
+ private:
+
+ // Command handlers.
+ void process_stop ();
+ void process_reap (class socket_base_t *socket_);
+ void process_reaped ();
+
+ // Reaper thread accesses incoming commands via this mailbox.
+ mailbox_t mailbox;
+
+ // Handle associated with mailbox' file descriptor.
+ poller_t::handle_t mailbox_handle;
+
+ // I/O multiplexing is performed using a poller object.
+ poller_t *poller;
+
+ // Number of sockets being reaped at the moment.
+ int sockets;
+
+ // If true, we were already asked to terminate.
+ bool terminating;
+
+ reaper_t (const reaper_t&);
+ const reaper_t &operator = (const reaper_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/rep.cpp b/src/0mq/rep.cpp
new file mode 100644
index 0000000..58c810b
--- /dev/null
+++ b/src/0mq/rep.cpp
@@ -0,0 +1,131 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "rep.hpp"
+#include "err.hpp"
+
+zmq::rep_t::rep_t (class ctx_t *parent_, uint32_t tid_) :
+ xrep_t (parent_, tid_),
+ sending_reply (false),
+ request_begins (true)
+{
+ options.type = ZMQ_REP;
+}
+
+zmq::rep_t::~rep_t ()
+{
+}
+
+int zmq::rep_t::xsend (zmq_msg_t *msg_, int flags_)
+{
+ // If we are in the middle of receiving a request, we cannot send reply.
+ if (!sending_reply) {
+ errno = EFSM;
+ return -1;
+ }
+
+ bool more = (msg_->flags & ZMQ_MSG_MORE);
+
+ // Push message to the reply pipe.
+ int rc = xrep_t::xsend (msg_, flags_);
+ if (rc != 0)
+ return rc;
+
+ // If the reply is complete flip the FSM back to request receiving state.
+ if (!more)
+ sending_reply = false;
+
+ return 0;
+}
+
+int zmq::rep_t::xrecv (zmq_msg_t *msg_, int flags_)
+{
+ // If we are in middle of sending a reply, we cannot receive next request.
+ if (sending_reply) {
+ errno = EFSM;
+ return -1;
+ }
+
+ if (request_begins) {
+
+ // Copy the backtrace stack to the reply pipe.
+ bool bottom = false;
+ while (!bottom) {
+
+ // TODO: What if request can be read but reply pipe is not
+ // ready for writing?
+
+ // Get next part of the backtrace stack.
+ int rc = xrep_t::xrecv (msg_, flags_);
+ if (rc != 0)
+ return rc;
+
+ if ((msg_->flags & ZMQ_MSG_MORE)) {
+ // Empty message part delimits the traceback stack.
+ bottom = (zmq_msg_size (msg_) == 0);
+
+ // Push it to the reply pipe.
+ rc = xrep_t::xsend (msg_, flags_);
+ errno_assert (rc == 0);
+ }
+ else {
+ // If the traceback stack is malformed, discard anything
+ // already sent to pipe (we're at end of invalid message).
+ rc = xrep_t::rollback ();
+ zmq_assert (rc == 0);
+ }
+ }
+
+ request_begins = false;
+ }
+
+ // Now the routing info is safely stored. Get the first part
+ // of the message payload and exit.
+ int rc = xrep_t::xrecv (msg_, flags_);
+ if (rc != 0)
+ return rc;
+
+ // If whole request is read, flip the FSM to reply-sending state.
+ if (!(msg_->flags & ZMQ_MSG_MORE)) {
+ sending_reply = true;
+ request_begins = true;
+ }
+
+ return 0;
+}
+
+bool zmq::rep_t::xhas_in ()
+{
+ if (sending_reply)
+ return false;
+
+ return xrep_t::xhas_in ();
+}
+
+bool zmq::rep_t::xhas_out ()
+{
+ if (!sending_reply)
+ return false;
+
+ return xrep_t::xhas_out ();
+}
+
diff --git a/src/0mq/rep.hpp b/src/0mq/rep.hpp
new file mode 100644
index 0000000..d0dd9c8
--- /dev/null
+++ b/src/0mq/rep.hpp
@@ -0,0 +1,59 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_REP_HPP_INCLUDED__
+#define __ZMQ_REP_HPP_INCLUDED__
+
+#include "xrep.hpp"
+
+namespace zmq
+{
+
+ class rep_t : public xrep_t
+ {
+ public:
+
+ rep_t (class ctx_t *parent_, uint32_t tid_);
+ ~rep_t ();
+
+ // Overloads of functions from socket_base_t.
+ int xsend (zmq_msg_t *msg_, int flags_);
+ int xrecv (zmq_msg_t *msg_, int flags_);
+ bool xhas_in ();
+ bool xhas_out ();
+
+ private:
+
+ // If true, we are in process of sending the reply. If false we are
+ // in process of receiving a request.
+ bool sending_reply;
+
+ // If true, we are starting to receive a request. The beginning
+ // of the request is the backtrace stack.
+ bool request_begins;
+
+ rep_t (const rep_t&);
+ const rep_t &operator = (const rep_t&);
+
+ };
+
+}
+
+#endif
diff --git a/src/0mq/req.cpp b/src/0mq/req.cpp
new file mode 100644
index 0000000..6a6b6a8
--- /dev/null
+++ b/src/0mq/req.cpp
@@ -0,0 +1,125 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "req.hpp"
+#include "err.hpp"
+
+zmq::req_t::req_t (class ctx_t *parent_, uint32_t tid_) :
+ xreq_t (parent_, tid_),
+ receiving_reply (false),
+ message_begins (true)
+{
+ options.type = ZMQ_REQ;
+}
+
+zmq::req_t::~req_t ()
+{
+}
+
+int zmq::req_t::xsend (zmq_msg_t *msg_, int flags_)
+{
+ // If we've sent a request and we still haven't got the reply,
+ // we can't send another request.
+ if (receiving_reply) {
+ errno = EFSM;
+ return -1;
+ }
+
+ // First part of the request is empty message part (stack bottom).
+ if (message_begins) {
+ zmq_msg_t prefix;
+ int rc = zmq_msg_init (&prefix);
+ zmq_assert (rc == 0);
+ prefix.flags |= ZMQ_MSG_MORE;
+ rc = xreq_t::xsend (&prefix, flags_);
+ if (rc != 0)
+ return rc;
+ message_begins = false;
+ }
+
+ bool more = msg_->flags & ZMQ_MSG_MORE;
+
+ int rc = xreq_t::xsend (msg_, flags_);
+ if (rc != 0)
+ return rc;
+
+ // If the request was fully sent, flip the FSM into reply-receiving state.
+ if (!more) {
+ receiving_reply = true;
+ message_begins = true;
+ }
+
+ return 0;
+}
+
+int zmq::req_t::xrecv (zmq_msg_t *msg_, int flags_)
+{
+ // If request wasn't send, we can't wait for reply.
+ if (!receiving_reply) {
+ errno = EFSM;
+ return -1;
+ }
+
+ // First part of the reply should be empty message part (stack bottom).
+ if (message_begins) {
+ int rc = xreq_t::xrecv (msg_, flags_);
+ if (rc != 0)
+ return rc;
+
+ // TODO: this should also close the connection with the peer
+ if (!(msg_->flags & ZMQ_MSG_MORE) || zmq_msg_size (msg_) != 0) {
+ errno = EAGAIN;
+ return -1;
+ }
+ message_begins = false;
+ }
+
+ int rc = xreq_t::xrecv (msg_, flags_);
+ if (rc != 0)
+ return rc;
+
+ // If the reply is fully received, flip the FSM into request-sending state.
+ if (!(msg_->flags & ZMQ_MSG_MORE)) {
+ receiving_reply = false;
+ message_begins = true;
+ }
+
+ return 0;
+}
+
+bool zmq::req_t::xhas_in ()
+{
+ if (!receiving_reply)
+ return false;
+
+ return xreq_t::xhas_in ();
+}
+
+bool zmq::req_t::xhas_out ()
+{
+ if (receiving_reply)
+ return false;
+
+ return xreq_t::xhas_out ();
+}
+
+
diff --git a/src/0mq/req.hpp b/src/0mq/req.hpp
new file mode 100644
index 0000000..3138498
--- /dev/null
+++ b/src/0mq/req.hpp
@@ -0,0 +1,58 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_REQ_HPP_INCLUDED__
+#define __ZMQ_REQ_HPP_INCLUDED__
+
+#include "xreq.hpp"
+
+namespace zmq
+{
+
+ class req_t : public xreq_t
+ {
+ public:
+
+ req_t (class ctx_t *parent_, uint32_t tid_);
+ ~req_t ();
+
+ // Overloads of functions from socket_base_t.
+ int xsend (zmq_msg_t *msg_, int flags_);
+ int xrecv (zmq_msg_t *msg_, int flags_);
+ bool xhas_in ();
+ bool xhas_out ();
+
+ private:
+
+ // If true, request was already sent and reply wasn't received yet or
+ // was raceived partially.
+ bool receiving_reply;
+
+ // If true, we are starting to send/recv a message. The first part
+ // of the message must be empty message part (backtrace stack bottom).
+ bool message_begins;
+
+ req_t (const req_t&);
+ const req_t &operator = (const req_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/select.cpp b/src/0mq/select.cpp
new file mode 100644
index 0000000..78fb6f6
--- /dev/null
+++ b/src/0mq/select.cpp
@@ -0,0 +1,212 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+#if defined ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+#include <string.h>
+#include <algorithm>
+
+#if defined ZMQ_HAVE_HPUX
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#elif defined ZMQ_HAVE_OPENVMS
+#include <sys/types.h>
+#include <sys/time.h>
+#elif !defined ZMQ_HAVE_WINDOWS
+#include <sys/select.h>
+#endif
+
+#include "select.hpp"
+#include "err.hpp"
+#include "config.hpp"
+#include "i_poll_events.hpp"
+
+zmq::select_t::select_t () :
+ maxfd (retired_fd),
+ retired (false),
+ stopping (false)
+{
+ // Clear file descriptor sets.
+ FD_ZERO (&source_set_in);
+ FD_ZERO (&source_set_out);
+ FD_ZERO (&source_set_err);
+}
+
+zmq::select_t::~select_t ()
+{
+ worker.stop ();
+}
+
+zmq::select_t::handle_t zmq::select_t::add_fd (fd_t fd_, i_poll_events *events_)
+{
+ // Store the file descriptor.
+ fd_entry_t entry = {fd_, events_};
+ fds.push_back (entry);
+
+ // Ensure we do not attempt to select () on more than FD_SETSIZE
+ // file descriptors.
+ zmq_assert (fds.size () <= FD_SETSIZE);
+
+ // Start polling on errors.
+ FD_SET (fd_, &source_set_err);
+
+ // Adjust maxfd if necessary.
+ if (fd_ > maxfd)
+ maxfd = fd_;
+
+ // Increase the load metric of the thread.
+ adjust_load (1);
+
+ return fd_;
+}
+
+void zmq::select_t::rm_fd (handle_t handle_)
+{
+ // Mark the descriptor as retired.
+ fd_set_t::iterator it;
+ for (it = fds.begin (); it != fds.end (); ++it)
+ if (it->fd == handle_)
+ break;
+ zmq_assert (it != fds.end ());
+ it->fd = retired_fd;
+ retired = true;
+
+ // Stop polling on the descriptor.
+ FD_CLR (handle_, &source_set_in);
+ FD_CLR (handle_, &source_set_out);
+ FD_CLR (handle_, &source_set_err);
+
+ // Discard all events generated on this file descriptor.
+ FD_CLR (handle_, &readfds);
+ FD_CLR (handle_, &writefds);
+ FD_CLR (handle_, &exceptfds);
+
+ // Adjust the maxfd attribute if we have removed the
+ // highest-numbered file descriptor.
+ if (handle_ == maxfd) {
+ maxfd = retired_fd;
+ for (fd_set_t::iterator it = fds.begin (); it != fds.end (); ++it)
+ if (it->fd > maxfd)
+ maxfd = it->fd;
+ }
+
+ // Decrease the load metric of the thread.
+ adjust_load (-1);
+}
+
+void zmq::select_t::set_pollin (handle_t handle_)
+{
+ FD_SET (handle_, &source_set_in);
+}
+
+void zmq::select_t::reset_pollin (handle_t handle_)
+{
+ FD_CLR (handle_, &source_set_in);
+}
+
+void zmq::select_t::set_pollout (handle_t handle_)
+{
+ FD_SET (handle_, &source_set_out);
+}
+
+void zmq::select_t::reset_pollout (handle_t handle_)
+{
+ FD_CLR (handle_, &source_set_out);
+}
+
+void zmq::select_t::start ()
+{
+ worker.start (worker_routine, this);
+}
+
+void zmq::select_t::stop ()
+{
+ stopping = true;
+}
+
+void zmq::select_t::loop ()
+{
+ while (!stopping) {
+
+ // Execute any due timers.
+ int timeout = (int) execute_timers ();
+
+ // Intialise the pollsets.
+ memcpy (&readfds, &source_set_in, sizeof source_set_in);
+ memcpy (&writefds, &source_set_out, sizeof source_set_out);
+ memcpy (&exceptfds, &source_set_err, sizeof source_set_err);
+
+ // Wait for events.
+ struct timeval tv = {(long) (timeout / 1000),
+ (long) (timeout % 1000 * 1000)};
+ int rc = select (maxfd + 1, &readfds, &writefds, &exceptfds,
+ timeout ? &tv : NULL);
+
+#ifdef ZMQ_HAVE_WINDOWS
+ wsa_assert (rc != SOCKET_ERROR);
+#else
+ if (rc == -1 && errno == EINTR)
+ continue;
+ errno_assert (rc != -1);
+#endif
+
+ // If there are no events (i.e. it's a timeout) there's no point
+ // in checking the pollset.
+ if (rc == 0)
+ continue;
+
+ for (fd_set_t::size_type i = 0; i < fds.size (); i ++) {
+ if (fds [i].fd == retired_fd)
+ continue;
+ if (FD_ISSET (fds [i].fd, &exceptfds))
+ fds [i].events->in_event ();
+ if (fds [i].fd == retired_fd)
+ continue;
+ if (FD_ISSET (fds [i].fd, &writefds))
+ fds [i].events->out_event ();
+ if (fds [i].fd == retired_fd)
+ continue;
+ if (FD_ISSET (fds [i].fd, &readfds))
+ fds [i].events->in_event ();
+ }
+
+ // Destroy retired event sources.
+ if (retired) {
+ fds.erase (std::remove_if (fds.begin (), fds.end (),
+ zmq::select_t::is_retired_fd), fds.end ());
+ retired = false;
+ }
+ }
+}
+
+void zmq::select_t::worker_routine (void *arg_)
+{
+ ((select_t*) arg_)->loop ();
+}
+
+bool zmq::select_t::is_retired_fd (const fd_entry_t &entry)
+{
+ return (entry.fd == retired_fd);
+}
+
diff --git a/src/0mq/select.hpp b/src/0mq/select.hpp
new file mode 100644
index 0000000..c88dd71
--- /dev/null
+++ b/src/0mq/select.hpp
@@ -0,0 +1,116 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_SELECT_HPP_INCLUDED__
+#define __ZMQ_SELECT_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#include <stddef.h>
+#include <vector>
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "winsock2.h"
+#elif defined ZMQ_HAVE_OPENVMS
+#include <sys/types.h>
+#include <sys/time.h>
+#else
+#include <sys/select.h>
+#endif
+
+#include "fd.hpp"
+#include "thread.hpp"
+#include "poller_base.hpp"
+
+namespace zmq
+{
+
+ // Implements socket polling mechanism using POSIX.1-2001 select()
+ // function.
+
+ class select_t : public poller_base_t
+ {
+ public:
+
+ typedef fd_t handle_t;
+
+ select_t ();
+ ~select_t ();
+
+ // "poller" concept.
+ handle_t add_fd (fd_t fd_, struct i_poll_events *events_);
+ void rm_fd (handle_t handle_);
+ void set_pollin (handle_t handle_);
+ void reset_pollin (handle_t handle_);
+ void set_pollout (handle_t handle_);
+ void reset_pollout (handle_t handle_);
+ void start ();
+ void stop ();
+
+ private:
+
+ // Main worker thread routine.
+ static void worker_routine (void *arg_);
+
+ // Main event loop.
+ void loop ();
+
+ struct fd_entry_t
+ {
+ fd_t fd;
+ struct i_poll_events *events;
+ };
+
+ // Checks if an fd_entry_t is retired.
+ static bool is_retired_fd (const fd_entry_t &entry);
+
+ // Set of file descriptors that are used to retreive
+ // information for fd_set.
+ typedef std::vector <fd_entry_t> fd_set_t;
+ fd_set_t fds;
+
+ fd_set source_set_in;
+ fd_set source_set_out;
+ fd_set source_set_err;
+
+ fd_set readfds;
+ fd_set writefds;
+ fd_set exceptfds;
+
+ // Maximum file descriptor.
+ fd_t maxfd;
+
+ // If true, at least one file descriptor has retired.
+ bool retired;
+
+ // If true, thread is shutting down.
+ bool stopping;
+
+ // Handle of the physical thread doing the I/O work.
+ thread_t worker;
+
+ select_t (const select_t&);
+ const select_t &operator = (const select_t&);
+ };
+
+}
+
+#endif
+
diff --git a/src/0mq/semaphore.hpp b/src/0mq/semaphore.hpp
new file mode 100644
index 0000000..edc0683
--- /dev/null
+++ b/src/0mq/semaphore.hpp
@@ -0,0 +1,189 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_SEMAPHORE_HPP_INCLUDED__
+#define __ZMQ_SEMAPHORE_HPP_INCLUDED__
+
+#include "platform.hpp"
+#include "err.hpp"
+
+#if defined ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#elif defined ZMQ_HAVE_OPENVMS
+#include <pthread.h>
+#else
+#include <semaphore.h>
+#endif
+
+namespace zmq
+{
+ // Simple semaphore. Only single thread may be waiting at any given time.
+ // Also, the semaphore may not be posted before the previous post
+ // was matched by corresponding wait and the waiting thread was
+ // released.
+
+#if defined ZMQ_HAVE_WINDOWS
+
+ // On Windows platform simple semaphore is implemeted using event object.
+
+ class semaphore_t
+ {
+ public:
+
+ // Initialise the semaphore.
+ inline semaphore_t ()
+ {
+ ev = CreateEvent (NULL, FALSE, FALSE, NULL);
+ win_assert (ev != NULL);
+ }
+
+ // Destroy the semaphore.
+ inline ~semaphore_t ()
+ {
+ int rc = CloseHandle (ev);
+ win_assert (rc != 0);
+ }
+
+ // Wait for the semaphore.
+ inline void wait ()
+ {
+ DWORD rc = WaitForSingleObject (ev, INFINITE);
+ win_assert (rc != WAIT_FAILED);
+ }
+
+ // Post the semaphore.
+ inline void post ()
+ {
+ int rc = SetEvent (ev);
+ win_assert (rc != 0);
+ }
+
+ private:
+
+ HANDLE ev;
+
+ semaphore_t (const semaphore_t&);
+ const semaphore_t &operator = (const semaphore_t&);
+ };
+
+#elif defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_OPENVMS
+
+ // On platforms that allow for double locking of a mutex from the same
+ // thread, simple semaphore is implemented using mutex, as it is more
+ // efficient than full-blown semaphore.
+
+ // Note that OS-level semaphore is not implemented on OSX, so the below
+ // code is not only optimisation, it's necessary to make 0MQ work on OSX.
+
+ class semaphore_t
+ {
+ public:
+
+ // Initialise the semaphore.
+ inline semaphore_t ()
+ {
+ int rc = pthread_mutex_init (&mutex, NULL);
+ posix_assert (rc);
+ rc = pthread_mutex_lock (&mutex);
+ posix_assert (rc);
+ }
+
+ // Destroy the semaphore.
+ inline ~semaphore_t ()
+ {
+ int rc = pthread_mutex_unlock (&mutex);
+ posix_assert (rc);
+ rc = pthread_mutex_destroy (&mutex);
+ posix_assert (rc);
+ }
+
+ // Wait for the semaphore.
+ inline void wait ()
+ {
+ int rc = pthread_mutex_lock (&mutex);
+ posix_assert (rc);
+ }
+
+ // Post the semaphore.
+ inline void post ()
+ {
+ int rc = pthread_mutex_unlock (&mutex);
+ posix_assert (rc);
+ }
+
+ private:
+
+ pthread_mutex_t mutex;
+
+ semaphore_t (const semaphore_t&);
+ const semaphore_t &operator = (const semaphore_t&);
+ };
+
+#else
+
+ // Default implementation maps simple semaphore to POSIX semaphore.
+
+ class semaphore_t
+ {
+ public:
+
+ // Initialise the semaphore.
+ inline semaphore_t ()
+ {
+ int rc = sem_init (&sem, 0, 0);
+ errno_assert (rc != -1);
+ }
+
+ // Destroy the semaphore.
+ inline ~semaphore_t ()
+ {
+ int rc = sem_destroy (&sem);
+ errno_assert (rc != -1);
+ }
+
+ // Wait for the semaphore.
+ inline void wait ()
+ {
+ int rc = sem_wait (&sem);
+ errno_assert (rc != -1);
+ }
+
+ // Post the semaphore.
+ inline void post ()
+ {
+ int rc = sem_post (&sem);
+ errno_assert (rc != -1);
+ }
+
+ private:
+
+ // Underlying system semaphore object.
+ sem_t sem;
+
+ semaphore_t (const semaphore_t&);
+ const semaphore_t &operator = (const semaphore_t&);
+ };
+
+#endif
+
+}
+
+#endif
+
diff --git a/src/0mq/session.cpp b/src/0mq/session.cpp
new file mode 100644
index 0000000..33c25d9
--- /dev/null
+++ b/src/0mq/session.cpp
@@ -0,0 +1,347 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "session.hpp"
+#include "socket_base.hpp"
+#include "i_engine.hpp"
+#include "err.hpp"
+#include "pipe.hpp"
+#include "likely.hpp"
+
+zmq::session_t::session_t (class io_thread_t *io_thread_,
+ class socket_base_t *socket_, const options_t &options_) :
+ own_t (io_thread_, options_),
+ io_object_t (io_thread_),
+ in_pipe (NULL),
+ incomplete_in (false),
+ out_pipe (NULL),
+ engine (NULL),
+ socket (socket_),
+ io_thread (io_thread_),
+ pipes_attached (false),
+ delimiter_processed (false),
+ force_terminate (false),
+ has_linger_timer (false),
+ state (active)
+{
+}
+
+zmq::session_t::~session_t ()
+{
+ zmq_assert (!in_pipe);
+ zmq_assert (!out_pipe);
+
+ if (engine)
+ engine->terminate ();
+}
+
+void zmq::session_t::proceed_with_term ()
+{
+ if (state == terminating)
+ return;
+
+ zmq_assert (state == pending);
+ state = terminating;
+
+ // If there's still a pending linger timer, remove it.
+ if (has_linger_timer) {
+ cancel_timer (linger_timer_id);
+ has_linger_timer = false;
+ }
+
+ if (in_pipe) {
+ register_term_acks (1);
+ in_pipe->terminate ();
+ }
+ if (out_pipe) {
+ register_term_acks (1);
+ out_pipe->terminate ();
+ }
+
+ // The session has already waited for the linger period. We don't want
+ // the child objects to linger any more thus linger is set to zero.
+ own_t::process_term (0);
+}
+
+bool zmq::session_t::read (::zmq_msg_t *msg_)
+{
+ if (!in_pipe)
+ return false;
+
+ if (!in_pipe->read (msg_))
+ return false;
+
+ incomplete_in = msg_->flags & ZMQ_MSG_MORE;
+ return true;
+}
+
+bool zmq::session_t::write (::zmq_msg_t *msg_)
+{
+ if (out_pipe && out_pipe->write (msg_)) {
+ zmq_msg_init (msg_);
+ return true;
+ }
+
+ return false;
+}
+
+void zmq::session_t::flush ()
+{
+ if (out_pipe)
+ out_pipe->flush ();
+}
+
+void zmq::session_t::clean_pipes ()
+{
+ // Get rid of half-processed messages in the out pipe. Flush any
+ // unflushed messages upstream.
+ if (out_pipe) {
+ out_pipe->rollback ();
+ out_pipe->flush ();
+ }
+
+ // Remove any half-read message from the in pipe.
+ if (in_pipe) {
+ while (incomplete_in) {
+ zmq_msg_t msg;
+ zmq_msg_init (&msg);
+ if (!read (&msg)) {
+ zmq_assert (!incomplete_in);
+ break;
+ }
+ zmq_msg_close (&msg);
+ }
+ }
+}
+
+void zmq::session_t::attach_pipes (class reader_t *inpipe_,
+ class writer_t *outpipe_, const blob_t &peer_identity_)
+{
+ zmq_assert (!pipes_attached);
+ pipes_attached = true;
+
+ if (inpipe_) {
+ zmq_assert (!in_pipe);
+ in_pipe = inpipe_;
+ in_pipe->set_event_sink (this);
+ }
+
+ if (outpipe_) {
+ zmq_assert (!out_pipe);
+ out_pipe = outpipe_;
+ out_pipe->set_event_sink (this);
+ }
+
+ // If we are already terminating, terminate the pipes straight away.
+ if (state == terminating) {
+ if (in_pipe) {
+ in_pipe->terminate ();
+ register_term_acks (1);
+ }
+ if (out_pipe) {
+ out_pipe->terminate ();
+ register_term_acks (1);
+ }
+ }
+}
+
+void zmq::session_t::delimited (reader_t *pipe_)
+{
+ zmq_assert (in_pipe == pipe_);
+ zmq_assert (!delimiter_processed);
+ delimiter_processed = true;
+
+ // If we are in process of being closed, but still waiting for all
+ // pending messeges being sent, we can terminate here.
+ if (state == pending)
+ proceed_with_term ();
+}
+
+void zmq::session_t::terminated (reader_t *pipe_)
+{
+ zmq_assert (in_pipe == pipe_);
+ in_pipe = NULL;
+ if (state == terminating)
+ unregister_term_ack ();
+}
+
+void zmq::session_t::terminated (writer_t *pipe_)
+{
+ zmq_assert (out_pipe == pipe_);
+ out_pipe = NULL;
+ if (state == terminating)
+ unregister_term_ack ();
+}
+
+void zmq::session_t::activated (reader_t *pipe_)
+{
+ zmq_assert (in_pipe == pipe_);
+
+ if (likely (engine != NULL))
+ engine->activate_out ();
+ else
+ in_pipe->check_read ();
+}
+
+void zmq::session_t::activated (writer_t *pipe_)
+{
+ zmq_assert (out_pipe == pipe_);
+ if (engine)
+ engine->activate_in ();
+}
+
+void zmq::session_t::process_plug ()
+{
+}
+
+void zmq::session_t::process_attach (i_engine *engine_,
+ const blob_t &peer_identity_)
+{
+ // If some other object (e.g. init) notifies us that the connection failed
+ // we need to start the reconnection process.
+ if (!engine_) {
+ zmq_assert (!engine);
+ detached ();
+ return;
+ }
+
+ // If we are already terminating, we destroy the engine straight away.
+ // Note that we don't have to unplug it before deleting as it's not
+ // yet plugged to the session.
+ if (state == terminating) {
+ delete engine_;
+ return;
+ }
+
+ // If the session already has an engine attached, destroy new one.
+ // Note new engine is not plugged in yet, we don't have to unplug it.
+ if (engine) {
+ log ("DPID: duplicate peer identity - disconnecting peer");
+ delete engine_;
+ return;
+ }
+
+ // Check whether the required pipes already exist. If not so, we'll
+ // create them and bind them to the socket object.
+ if (!pipes_attached) {
+ zmq_assert (!in_pipe && !out_pipe);
+ pipes_attached = true;
+ reader_t *socket_reader = NULL;
+ writer_t *socket_writer = NULL;
+
+ // Create the pipes, as required.
+ if (options.requires_in) {
+ create_pipe (socket, this, options.hwm, options.swap, &socket_reader,
+ &out_pipe);
+ out_pipe->set_event_sink (this);
+ }
+ if (options.requires_out) {
+ create_pipe (this, socket, options.hwm, options.swap, &in_pipe,
+ &socket_writer);
+ in_pipe->set_event_sink (this);
+ }
+
+ // Bind the pipes to the socket object.
+ if (socket_reader || socket_writer)
+ send_bind (socket, socket_reader, socket_writer, peer_identity_);
+ }
+
+ // Plug in the engine.
+ engine = engine_;
+ engine->plug (io_thread, this);
+
+ // Trigger the notfication about the attachment.
+ attached (peer_identity_);
+}
+
+void zmq::session_t::detach ()
+{
+ // Engine is dead. Let's forget about it.
+ engine = NULL;
+
+ // Remove any half-done messages from the pipes.
+ clean_pipes ();
+
+ // Send the event to the derived class.
+ detached ();
+
+ // Just in case, there's only a delimiter in the inbound pipe.
+ if (in_pipe)
+ in_pipe->check_read ();
+}
+
+void zmq::session_t::process_term (int linger_)
+{
+ zmq_assert (state == active);
+ state = pending;
+
+ // If linger is set to zero, we can terminate the session straight away
+ // not waiting for the pending messages to be sent.
+ if (linger_ == 0) {
+ proceed_with_term ();
+ return;
+ }
+
+ // If there's finite linger value, set up a timer.
+ if (linger_ > 0) {
+ zmq_assert (!has_linger_timer);
+ add_timer (linger_, linger_timer_id);
+ has_linger_timer = true;
+ }
+
+ // If there's no engine and there's only delimiter in the pipe it wouldn't
+ // be ever read. Thus we check for it explicitly.
+ if (in_pipe)
+ in_pipe->check_read ();
+
+ // If there's no in pipe there are no pending messages to send.
+ // We can proceed with the shutdown straight away. Also, if there is
+ // inbound pipe, but the delimiter was already processed, we can
+ // terminate immediately. Alternatively, if the derived session type have
+ // called 'terminate' we'll finish straight away.
+ if (!options.requires_out || delimiter_processed || force_terminate ||
+ (!options.immediate_connect && !in_pipe))
+ proceed_with_term ();
+}
+
+void zmq::session_t::timer_event (int id_)
+{
+ // Linger period expired. We can proceed with termination even though
+ // there are still pending messages to be sent.
+ zmq_assert (id_ == linger_timer_id);
+ has_linger_timer = false;
+ proceed_with_term ();
+}
+
+bool zmq::session_t::register_session (const blob_t &name_, session_t *session_)
+{
+ return socket->register_session (name_, session_);
+}
+
+void zmq::session_t::unregister_session (const blob_t &name_)
+{
+ socket->unregister_session (name_);
+}
+
+void zmq::session_t::terminate ()
+{
+ force_terminate = true;
+ own_t::terminate ();
+}
diff --git a/src/0mq/session.hpp b/src/0mq/session.hpp
new file mode 100644
index 0000000..499c074
--- /dev/null
+++ b/src/0mq/session.hpp
@@ -0,0 +1,150 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_SESSION_HPP_INCLUDED__
+#define __ZMQ_SESSION_HPP_INCLUDED__
+
+#include "own.hpp"
+#include "i_inout.hpp"
+#include "io_object.hpp"
+#include "blob.hpp"
+#include "pipe.hpp"
+
+namespace zmq
+{
+
+ class session_t :
+ public own_t,
+ public io_object_t,
+ public i_inout,
+ public i_reader_events,
+ public i_writer_events
+ {
+ public:
+
+ session_t (class io_thread_t *io_thread_,
+ class socket_base_t *socket_, const options_t &options_);
+
+ // i_inout interface implementation. Note that detach method is not
+ // implemented by generic session. Different session types may handle
+ // engine disconnection in different ways.
+ bool read (::zmq_msg_t *msg_);
+ bool write (::zmq_msg_t *msg_);
+ void flush ();
+ void detach ();
+
+ void attach_pipes (class reader_t *inpipe_, class writer_t *outpipe_,
+ const blob_t &peer_identity_);
+
+ // i_reader_events interface implementation.
+ void activated (class reader_t *pipe_);
+ void terminated (class reader_t *pipe_);
+ void delimited (class reader_t *pipe_);
+
+ // i_writer_events interface implementation.
+ void activated (class writer_t *pipe_);
+ void terminated (class writer_t *pipe_);
+
+ protected:
+
+ // This function allows to shut down the session even though
+ // there are pending messages in the inbound pipe.
+ void terminate ();
+
+ // Two events for the derived session type. Attached is triggered
+ // when session is attached to a peer, detached is triggered at the
+ // beginning of the termination process when session is about to
+ // be detached from the peer.
+ virtual void attached (const blob_t &peer_identity_) = 0;
+ virtual void detached () = 0;
+
+ // Allows derives session types to (un)register session names.
+ bool register_session (const blob_t &name_, class session_t *session_);
+ void unregister_session (const blob_t &name_);
+
+ ~session_t ();
+
+ private:
+
+ // Handlers for incoming commands.
+ void process_plug ();
+ void process_attach (struct i_engine *engine_,
+ const blob_t &peer_identity_);
+ void process_term (int linger_);
+
+ // i_poll_events handlers.
+ void timer_event (int id_);
+
+ // Remove any half processed messages. Flush unflushed messages.
+ // Call this function when engine disconnect to get rid of leftovers.
+ void clean_pipes ();
+
+ // Call this function to move on with the delayed process_term.
+ void proceed_with_term ();
+
+ // Inbound pipe, i.e. one the session is getting messages from.
+ class reader_t *in_pipe;
+
+ // This flag is true if the remainder of the message being processed
+ // is still in the in pipe.
+ bool incomplete_in;
+
+ // Outbound pipe, i.e. one the socket is sending messages to.
+ class writer_t *out_pipe;
+
+ // The protocol I/O engine connected to the session.
+ struct i_engine *engine;
+
+ // The socket the session belongs to.
+ class socket_base_t *socket;
+
+ // I/O thread the session is living in. It will be used to plug in
+ // the engines into the same thread.
+ class io_thread_t *io_thread;
+
+ // If true, pipes were already attached to this session.
+ bool pipes_attached;
+
+ // If true, delimiter was already read from the inbound pipe.
+ bool delimiter_processed;
+
+ // If true, we should terminate the session even though there are
+ // pending messages in the inbound pipe.
+ bool force_terminate;
+
+ // ID of the linger timer
+ enum {linger_timer_id = 0x20};
+
+ // True is linger timer is running.
+ bool has_linger_timer;
+
+ enum {
+ active,
+ pending,
+ terminating
+ } state;
+
+ session_t (const session_t&);
+ const session_t &operator = (const session_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/signaler.cpp b/src/0mq/signaler.cpp
new file mode 100644
index 0000000..7b66ea7
--- /dev/null
+++ b/src/0mq/signaler.cpp
@@ -0,0 +1,344 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+
+#if defined ZMQ_FORCE_SELECT
+#define ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
+#elif defined ZMQ_FORCE_POLL
+#define ZMQ_SIGNALER_WAIT_BASED_ON_POLL
+#elif defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
+ defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
+ defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
+ defined ZMQ_HAVE_NETBSD
+#define ZMQ_SIGNALER_WAIT_BASED_ON_POLL
+#elif defined ZMQ_HAVE_WINDOWS || defined ZMQ_HAVE_OPENVMS
+#define ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
+#endif
+
+// On AIX, poll.h has to be included before zmq.h to get consistent
+// definition of pollfd structure (AIX uses 'reqevents' and 'retnevents'
+// instead of 'events' and 'revents' and defines macros to map from POSIX-y
+// names to AIX-specific names).
+#if defined ZMQ_SIGNALER_WAIT_BASED_ON_POLL
+#include <poll.h>
+#elif defined ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
+#if defined ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#elif defined ZMQ_HAVE_HPUX
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#elif defined ZMQ_HAVE_OPENVMS
+#include <sys/types.h>
+#include <sys/time.h>
+#else
+#include <sys/select.h>
+#endif
+#endif
+
+#include "signaler.hpp"
+#include "likely.hpp"
+#include "err.hpp"
+#include "fd.hpp"
+#include "ip.hpp"
+
+#if defined ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#else
+#include <unistd.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <netinet/tcp.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#endif
+
+zmq::signaler_t::signaler_t ()
+{
+ // Create the socketpair for signaling.
+ int rc = make_fdpair (&r, &w);
+ errno_assert (rc == 0);
+
+ // Set both fds to non-blocking mode.
+#if defined ZMQ_HAVE_WINDOWS
+ unsigned long argp = 1;
+ rc = ioctlsocket (w, FIONBIO, &argp);
+ wsa_assert (rc != SOCKET_ERROR);
+ rc = ioctlsocket (r, FIONBIO, &argp);
+ wsa_assert (rc != SOCKET_ERROR);
+#else
+ int flags = fcntl (w, F_GETFL, 0);
+ errno_assert (flags >= 0);
+ rc = fcntl (w, F_SETFL, flags | O_NONBLOCK);
+ errno_assert (rc == 0);
+ flags = fcntl (r, F_GETFL, 0);
+ errno_assert (flags >= 0);
+ rc = fcntl (r, F_SETFL, flags | O_NONBLOCK);
+ errno_assert (rc == 0);
+#endif
+}
+
+zmq::signaler_t::~signaler_t ()
+{
+#if defined ZMQ_HAVE_WINDOWS
+ int rc = closesocket (w);
+ wsa_assert (rc != SOCKET_ERROR);
+ rc = closesocket (r);
+ wsa_assert (rc != SOCKET_ERROR);
+#else
+ close (w);
+ close (r);
+#endif
+}
+
+zmq::fd_t zmq::signaler_t::get_fd ()
+{
+ return r;
+}
+
+void zmq::signaler_t::send ()
+{
+#if defined ZMQ_HAVE_WINDOWS
+ unsigned char dummy = 0;
+ int nbytes = ::send (w, (char*) &dummy, sizeof (dummy), 0);
+ wsa_assert (nbytes != SOCKET_ERROR);
+ zmq_assert (nbytes == sizeof (dummy));
+#else
+ unsigned char dummy = 0;
+ while (true) {
+ ssize_t nbytes = ::send (w, &dummy, sizeof (dummy), 0);
+ if (unlikely (nbytes == -1 && errno == EINTR))
+ continue;
+ zmq_assert (nbytes == sizeof (dummy));
+ break;
+ }
+#endif
+}
+
+int zmq::signaler_t::wait (int timeout_)
+{
+#ifdef ZMQ_SIGNALER_WAIT_BASED_ON_POLL
+
+ struct pollfd pfd;
+ pfd.fd = r;
+ pfd.events = POLLIN;
+ int rc = poll (&pfd, 1, timeout_);
+ if (unlikely (rc < 0)) {
+ zmq_assert (errno == EINTR);
+ return -1;
+ }
+ else if (unlikely (rc == 0)) {
+ errno = EAGAIN;
+ return -1;
+ }
+ zmq_assert (rc == 1);
+ zmq_assert (pfd.revents & POLLIN);
+ return 0;
+
+#elif defined ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
+
+ fd_set fds;
+ FD_ZERO (&fds);
+ FD_SET (r, &fds);
+ struct timeval timeout;
+ if (timeout_ >= 0) {
+ timeout.tv_sec = timeout_ / 1000;
+ timeout.tv_usec = timeout_ % 1000 * 1000;
+ }
+#ifdef ZMQ_HAVE_WINDOWS
+ int rc = select (0, &fds, NULL, NULL,
+ timeout_ >= 0 ? &timeout : NULL);
+ wsa_assert (rc != SOCKET_ERROR);
+#else
+ int rc = select (r + 1, &fds, NULL, NULL,
+ timeout_ >= 0 ? &timeout : NULL);
+ if (unlikely (rc < 0)) {
+ zmq_assert (errno == EINTR);
+ return -1;
+ }
+#endif
+ if (unlikely (rc == 0)) {
+ errno = EAGAIN;
+ return -1;
+ }
+ zmq_assert (rc == 1);
+ return 0;
+
+#else
+#error
+#endif
+}
+
+void zmq::signaler_t::recv ()
+{
+ // Attempt to read a signal.
+ unsigned char dummy;
+#ifdef ZMQ_HAVE_WINDOWS
+ int nbytes = ::recv (r, (char*) &dummy, sizeof (dummy), 0);
+ wsa_assert (nbytes != SOCKET_ERROR);
+#else
+ ssize_t nbytes = ::recv (r, &dummy, sizeof (dummy), 0);
+ errno_assert (nbytes >= 0);
+#endif
+ zmq_assert (nbytes == sizeof (dummy));
+ zmq_assert (dummy == 0);
+}
+
+int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_)
+{
+#if defined ZMQ_HAVE_WINDOWS
+
+ // Windows has no 'socketpair' function. CreatePipe is no good as pipe
+ // handles cannot be polled on. Here we create the socketpair by hand.
+ *w_ = INVALID_SOCKET;
+ *r_ = INVALID_SOCKET;
+
+ // Create listening socket.
+ SOCKET listener;
+ listener = open_socket (AF_INET, SOCK_STREAM, 0);
+ wsa_assert (listener != INVALID_SOCKET);
+
+ // Set SO_REUSEADDR and TCP_NODELAY on listening socket.
+ BOOL so_reuseaddr = 1;
+ int rc = setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
+ (char *)&so_reuseaddr, sizeof (so_reuseaddr));
+ wsa_assert (rc != SOCKET_ERROR);
+ BOOL tcp_nodelay = 1;
+ rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY,
+ (char *)&tcp_nodelay, sizeof (tcp_nodelay));
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Bind listening socket to any free local port.
+ struct sockaddr_in addr;
+ memset (&addr, 0, sizeof (addr));
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+ addr.sin_port = 0;
+ rc = bind (listener, (const struct sockaddr*) &addr, sizeof (addr));
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Retrieve local port listener is bound to (into addr).
+ int addrlen = sizeof (addr);
+ rc = getsockname (listener, (struct sockaddr*) &addr, &addrlen);
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Listen for incomming connections.
+ rc = listen (listener, 1);
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Create the writer socket.
+ *w_ = WSASocket (AF_INET, SOCK_STREAM, 0, NULL, 0, 0);
+ wsa_assert (*w_ != INVALID_SOCKET);
+
+ // Set TCP_NODELAY on writer socket.
+ rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY,
+ (char *)&tcp_nodelay, sizeof (tcp_nodelay));
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Connect writer to the listener.
+ rc = connect (*w_, (sockaddr *) &addr, sizeof (addr));
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Accept connection from writer.
+ *r_ = accept (listener, NULL, NULL);
+ wsa_assert (*r_ != INVALID_SOCKET);
+
+ // We don't need the listening socket anymore. Close it.
+ rc = closesocket (listener);
+ wsa_assert (rc != SOCKET_ERROR);
+
+ return 0;
+
+#elif defined ZMQ_HAVE_OPENVMS
+
+ // Whilst OpenVMS supports socketpair - it maps to AF_INET only. Further,
+ // it does not set the socket options TCP_NODELAY and TCP_NODELACK which
+ // can lead to performance problems.
+ //
+ // The bug will be fixed in V5.6 ECO4 and beyond. In the meantime, we'll
+ // create the socket pair manually.
+ sockaddr_in lcladdr;
+ memset (&lcladdr, 0, sizeof (lcladdr));
+ lcladdr.sin_family = AF_INET;
+ lcladdr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+ lcladdr.sin_port = 0;
+
+ int listener = open_socket (AF_INET, SOCK_STREAM, 0);
+ errno_assert (listener != -1);
+
+ int on = 1;
+ int rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, &on, sizeof (on));
+ errno_assert (rc != -1);
+
+ rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELACK, &on, sizeof (on));
+ errno_assert (rc != -1);
+
+ rc = bind(listener, (struct sockaddr*) &lcladdr, sizeof (lcladdr));
+ errno_assert (rc != -1);
+
+ socklen_t lcladdr_len = sizeof (lcladdr);
+
+ rc = getsockname (listener, (struct sockaddr*) &lcladdr, &lcladdr_len);
+ errno_assert (rc != -1);
+
+ rc = listen (listener, 1);
+ errno_assert (rc != -1);
+
+ *w_ = open_socket (AF_INET, SOCK_STREAM, 0);
+ errno_assert (*w_ != -1);
+
+ rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, &on, sizeof (on));
+ errno_assert (rc != -1);
+
+ rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELACK, &on, sizeof (on));
+ errno_assert (rc != -1);
+
+ rc = connect (*w_, (struct sockaddr*) &lcladdr, sizeof (lcladdr));
+ errno_assert (rc != -1);
+
+ *r_ = accept (listener, NULL, NULL);
+ errno_assert (*r_ != -1);
+
+ close (listener);
+
+ return 0;
+
+#else // All other implementations support socketpair()
+
+ int sv [2];
+ int rc = socketpair (AF_UNIX, SOCK_STREAM, 0, sv);
+ errno_assert (rc == 0);
+ *w_ = sv [0];
+ *r_ = sv [1];
+ return 0;
+
+#endif
+}
+
+#if defined ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
+#undef ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
+#endif
+#if defined ZMQ_SIGNALER_WAIT_BASED_ON_POLL
+#undef ZMQ_SIGNALER_WAIT_BASED_ON_POLL
+#endif
+
diff --git a/src/0mq/signaler.hpp b/src/0mq/signaler.hpp
new file mode 100644
index 0000000..2ebff41
--- /dev/null
+++ b/src/0mq/signaler.hpp
@@ -0,0 +1,63 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_SIGNALER_HPP_INCLUDED__
+#define __ZMQ_SIGNALER_HPP_INCLUDED__
+
+#include "fd.hpp"
+
+namespace zmq
+{
+
+ // This is a cross-platform equivalent to signal_fd. However, as opposed
+ // to signal_fd there can be at most one signal in the signaler at any
+ // given moment. Attempt to send a signal before receiving the previous
+ // one will result in undefined behaviour.
+
+ class signaler_t
+ {
+ public:
+
+ signaler_t ();
+ ~signaler_t ();
+
+ fd_t get_fd ();
+ void send ();
+ int wait (int timeout_);
+ void recv ();
+
+ private:
+
+ // Creates a pair of filedescriptors that will be used
+ // to pass the signals.
+ static int make_fdpair (fd_t *r_, fd_t *w_);
+
+ // Write & read end of the socketpair.
+ fd_t w;
+ fd_t r;
+
+ // Disable copying of signaler_t object.
+ signaler_t (const signaler_t&);
+ const signaler_t &operator = (const signaler_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/socket_base.cpp b/src/0mq/socket_base.cpp
new file mode 100644
index 0000000..335a858
--- /dev/null
+++ b/src/0mq/socket_base.cpp
@@ -0,0 +1,861 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <new>
+#include <string>
+#include <algorithm>
+
+#include "../include/zmq.h"
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#if defined _MSC_VER
+#include <intrin.h>
+#endif
+#else
+#include <unistd.h>
+#endif
+
+#include "socket_base.hpp"
+#include "zmq_listener.hpp"
+#include "zmq_connecter.hpp"
+#include "io_thread.hpp"
+#include "connect_session.hpp"
+#include "config.hpp"
+#include "clock.hpp"
+#include "pipe.hpp"
+#include "err.hpp"
+#include "ctx.hpp"
+#include "platform.hpp"
+#include "likely.hpp"
+#include "uuid.hpp"
+
+#include "pair.hpp"
+#include "pub.hpp"
+#include "sub.hpp"
+#include "req.hpp"
+#include "rep.hpp"
+#include "pull.hpp"
+#include "push.hpp"
+#include "xreq.hpp"
+#include "xrep.hpp"
+#include "xpub.hpp"
+#include "xsub.hpp"
+
+bool zmq::socket_base_t::check_tag ()
+{
+ return tag == 0xbaddecaf;
+}
+
+zmq::socket_base_t *zmq::socket_base_t::create (int type_, class ctx_t *parent_,
+ uint32_t tid_)
+{
+ socket_base_t *s = NULL;
+ switch (type_) {
+
+ case ZMQ_PAIR:
+ s = new (std::nothrow) pair_t (parent_, tid_);
+ break;
+ case ZMQ_PUB:
+ s = new (std::nothrow) pub_t (parent_, tid_);
+ break;
+ case ZMQ_SUB:
+ s = new (std::nothrow) sub_t (parent_, tid_);
+ break;
+ case ZMQ_REQ:
+ s = new (std::nothrow) req_t (parent_, tid_);
+ break;
+ case ZMQ_REP:
+ s = new (std::nothrow) rep_t (parent_, tid_);
+ break;
+ case ZMQ_XREQ:
+ s = new (std::nothrow) xreq_t (parent_, tid_);
+ break;
+ case ZMQ_XREP:
+ s = new (std::nothrow) xrep_t (parent_, tid_);
+ break;
+ case ZMQ_PULL:
+ s = new (std::nothrow) pull_t (parent_, tid_);
+ break;
+ case ZMQ_PUSH:
+ s = new (std::nothrow) push_t (parent_, tid_);
+ break;
+ case ZMQ_XPUB:
+ s = new (std::nothrow) xpub_t (parent_, tid_);
+ break;
+ case ZMQ_XSUB:
+ s = new (std::nothrow) xsub_t (parent_, tid_);
+ break;
+ default:
+ errno = EINVAL;
+ return NULL;
+ }
+ alloc_assert (s);
+ return s;
+}
+
+zmq::socket_base_t::socket_base_t (ctx_t *parent_, uint32_t tid_) :
+ own_t (parent_, tid_),
+ tag (0xbaddecaf),
+ ctx_terminated (false),
+ destroyed (false),
+ last_tsc (0),
+ ticks (0),
+ rcvmore (false)
+{
+}
+
+zmq::socket_base_t::~socket_base_t ()
+{
+ zmq_assert (destroyed);
+
+ // Check whether there are no session leaks.
+ sessions_sync.lock ();
+ zmq_assert (sessions.empty ());
+ sessions_sync.unlock ();
+
+ // Mark the socket as dead.
+ tag = 0xdeadbeef;
+}
+
+zmq::mailbox_t *zmq::socket_base_t::get_mailbox ()
+{
+ return &mailbox;
+}
+
+void zmq::socket_base_t::stop ()
+{
+ // Called by ctx when it is terminated (zmq_term).
+ // 'stop' command is sent from the threads that called zmq_term to
+ // the thread owning the socket. This way, blocking call in the
+ // owner thread can be interrupted.
+ send_stop ();
+}
+
+int zmq::socket_base_t::parse_uri (const char *uri_,
+ std::string &protocol_, std::string &address_)
+{
+ zmq_assert (uri_ != NULL);
+
+ std::string uri (uri_);
+ std::string::size_type pos = uri.find ("://");
+ if (pos == std::string::npos) {
+ errno = EINVAL;
+ return -1;
+ }
+ protocol_ = uri.substr (0, pos);
+ address_ = uri.substr (pos + 3);
+ if (protocol_.empty () || address_.empty ()) {
+ errno = EINVAL;
+ return -1;
+ }
+ return 0;
+}
+
+int zmq::socket_base_t::check_protocol (const std::string &protocol_)
+{
+ // First check out whether the protcol is something we are aware of.
+ if (protocol_ != "inproc" && protocol_ != "ipc" && protocol_ != "tcp" &&
+ protocol_ != "pgm" && protocol_ != "epgm" && protocol_ != "sys") {
+ errno = EPROTONOSUPPORT;
+ return -1;
+ }
+
+ // If 0MQ is not compiled with OpenPGM, pgm and epgm transports
+ // are not avaialble.
+#if !defined ZMQ_HAVE_OPENPGM
+ if (protocol_ == "pgm" || protocol_ == "epgm") {
+ errno = EPROTONOSUPPORT;
+ return -1;
+ }
+#endif
+
+ // IPC transport is not available on Windows and OpenVMS.
+#if defined ZMQ_HAVE_WINDOWS || defined ZMQ_HAVE_OPENVMS
+ if (protocol_ == "ipc") {
+ // Unknown protocol.
+ errno = EPROTONOSUPPORT;
+ return -1;
+ }
+#endif
+
+ // Check whether socket type and transport protocol match.
+ // Specifically, multicast protocols can't be combined with
+ // bi-directional messaging patterns (socket types).
+ if ((protocol_ == "pgm" || protocol_ == "epgm") &&
+ options.type != ZMQ_PUB && options.type != ZMQ_SUB &&
+ options.type != ZMQ_XPUB && options.type != ZMQ_XSUB) {
+ errno = ENOCOMPATPROTO;
+ return -1;
+ }
+
+ // Protocol is available.
+ return 0;
+}
+
+void zmq::socket_base_t::attach_pipes (class reader_t *inpipe_,
+ class writer_t *outpipe_, const blob_t &peer_identity_)
+{
+ // If the peer haven't specified it's identity, let's generate one.
+ if (peer_identity_.size ()) {
+ xattach_pipes (inpipe_, outpipe_, peer_identity_);
+ }
+ else {
+ blob_t identity (1, 0);
+ identity.append (uuid_t ().to_blob (), uuid_t::uuid_blob_len);
+ xattach_pipes (inpipe_, outpipe_, identity);
+ }
+}
+
+int zmq::socket_base_t::setsockopt (int option_, const void *optval_,
+ size_t optvallen_)
+{
+ if (unlikely (ctx_terminated)) {
+ errno = ETERM;
+ return -1;
+ }
+
+ // First, check whether specific socket type overloads the option.
+ int rc = xsetsockopt (option_, optval_, optvallen_);
+ if (rc == 0 || errno != EINVAL)
+ return rc;
+
+ // If the socket type doesn't support the option, pass it to
+ // the generic option parser.
+ return options.setsockopt (option_, optval_, optvallen_);
+}
+
+int zmq::socket_base_t::getsockopt (int option_, void *optval_,
+ size_t *optvallen_)
+{
+ if (unlikely (ctx_terminated)) {
+ errno = ETERM;
+ return -1;
+ }
+
+ if (option_ == ZMQ_RCVMORE) {
+ if (*optvallen_ < sizeof (int64_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((int64_t*) optval_) = rcvmore ? 1 : 0;
+ *optvallen_ = sizeof (int64_t);
+ return 0;
+ }
+
+ if (option_ == ZMQ_FD) {
+ if (*optvallen_ < sizeof (fd_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ *((fd_t*) optval_) = mailbox.get_fd ();
+ *optvallen_ = sizeof (fd_t);
+ return 0;
+ }
+
+ if (option_ == ZMQ_EVENTS) {
+ if (*optvallen_ < sizeof (uint32_t)) {
+ errno = EINVAL;
+ return -1;
+ }
+ int rc = process_commands (0, false);
+ if (rc != 0 && (errno == EINTR || errno == ETERM))
+ return -1;
+ errno_assert (rc == 0);
+ *((uint32_t*) optval_) = 0;
+ if (has_out ())
+ *((uint32_t*) optval_) |= ZMQ_POLLOUT;
+ if (has_in ())
+ *((uint32_t*) optval_) |= ZMQ_POLLIN;
+ *optvallen_ = sizeof (uint32_t);
+ return 0;
+ }
+
+ return options.getsockopt (option_, optval_, optvallen_);
+}
+
+int zmq::socket_base_t::bind (const char *addr_)
+{
+ if (unlikely (ctx_terminated)) {
+ errno = ETERM;
+ return -1;
+ }
+
+ // Parse addr_ string.
+ std::string protocol;
+ std::string address;
+ int rc = parse_uri (addr_, protocol, address);
+ if (rc != 0)
+ return -1;
+
+ rc = check_protocol (protocol);
+ if (rc != 0)
+ return -1;
+
+ if (protocol == "inproc" || protocol == "sys") {
+ endpoint_t endpoint = {this, options};
+ return register_endpoint (addr_, endpoint);
+ }
+
+ if (protocol == "tcp" || protocol == "ipc") {
+
+ // Choose I/O thread to run the listerner in.
+ io_thread_t *io_thread = choose_io_thread (options.affinity);
+ if (!io_thread) {
+ errno = EMTHREAD;
+ return -1;
+ }
+
+ // Create and run the listener.
+ zmq_listener_t *listener = new (std::nothrow) zmq_listener_t (
+ io_thread, this, options);
+ alloc_assert (listener);
+ int rc = listener->set_address (protocol.c_str(), address.c_str ());
+ if (rc != 0) {
+ delete listener;
+ return -1;
+ }
+ launch_child (listener);
+
+ return 0;
+ }
+
+ if (protocol == "pgm" || protocol == "epgm") {
+
+ // For convenience's sake, bind can be used interchageable with
+ // connect for PGM and EPGM transports.
+ return connect (addr_);
+ }
+
+ zmq_assert (false);
+ return -1;
+}
+
+int zmq::socket_base_t::connect (const char *addr_)
+{
+ if (unlikely (ctx_terminated)) {
+ errno = ETERM;
+ return -1;
+ }
+
+ // Parse addr_ string.
+ std::string protocol;
+ std::string address;
+ int rc = parse_uri (addr_, protocol, address);
+ if (rc != 0)
+ return -1;
+
+ // Checks that protocol is valid and supported on this system
+ rc = check_protocol (protocol);
+ if (rc != 0)
+ return -1;
+
+ // Parsed address for validation
+ sockaddr_storage addr;
+ socklen_t addr_len;
+
+ if (protocol == "tcp")
+ rc = resolve_ip_hostname (&addr, &addr_len, address.c_str ());
+ else
+ if (protocol == "ipc")
+ rc = resolve_local_path (&addr, &addr_len, address.c_str ());
+ if (rc != 0)
+ return -1;
+
+ if (protocol == "inproc" || protocol == "sys") {
+
+ // TODO: inproc connect is specific with respect to creating pipes
+ // as there's no 'reconnect' functionality implemented. Once that
+ // is in place we should follow generic pipe creation algorithm.
+
+ // Find the peer endpoint.
+ endpoint_t peer = find_endpoint (addr_);
+ if (!peer.socket)
+ return -1;
+
+ reader_t *inpipe_reader = NULL;
+ writer_t *inpipe_writer = NULL;
+ reader_t *outpipe_reader = NULL;
+ writer_t *outpipe_writer = NULL;
+
+ // The total HWM for an inproc connection should be the sum of
+ // the binder's HWM and the connector's HWM. (Similarly for the
+ // SWAP.)
+ int64_t hwm;
+ if (options.hwm == 0 || peer.options.hwm == 0)
+ hwm = 0;
+ else
+ hwm = options.hwm + peer.options.hwm;
+ int64_t swap;
+ if (options.swap == 0 && peer.options.swap == 0)
+ swap = 0;
+ else
+ swap = options.swap + peer.options.swap;
+
+ // Create inbound pipe, if required.
+ if (options.requires_in)
+ create_pipe (this, peer.socket, hwm, swap,
+ &inpipe_reader, &inpipe_writer);
+
+ // Create outbound pipe, if required.
+ if (options.requires_out)
+ create_pipe (peer.socket, this, hwm, swap,
+ &outpipe_reader, &outpipe_writer);
+
+ // Attach the pipes to this socket object.
+ attach_pipes (inpipe_reader, outpipe_writer, peer.options.identity);
+
+ // Attach the pipes to the peer socket. Note that peer's seqnum
+ // was incremented in find_endpoint function. We don't need it
+ // increased here.
+ send_bind (peer.socket, outpipe_reader, inpipe_writer,
+ options.identity, false);
+
+ return 0;
+ }
+
+ // Choose the I/O thread to run the session in.
+ io_thread_t *io_thread = choose_io_thread (options.affinity);
+ if (!io_thread) {
+ errno = EMTHREAD;
+ return -1;
+ }
+
+ // Create session.
+ connect_session_t *session = new (std::nothrow) connect_session_t (
+ io_thread, this, options, protocol.c_str (), address.c_str ());
+ alloc_assert (session);
+
+ // If 'immediate connect' feature is required, we'll create the pipes
+ // to the session straight away. Otherwise, they'll be created by the
+ // session once the connection is established.
+ if (options.immediate_connect) {
+
+ reader_t *inpipe_reader = NULL;
+ writer_t *inpipe_writer = NULL;
+ reader_t *outpipe_reader = NULL;
+ writer_t *outpipe_writer = NULL;
+
+ // Create inbound pipe, if required.
+ if (options.requires_in)
+ create_pipe (this, session, options.hwm, options.swap,
+ &inpipe_reader, &inpipe_writer);
+
+ // Create outbound pipe, if required.
+ if (options.requires_out)
+ create_pipe (session, this, options.hwm, options.swap,
+ &outpipe_reader, &outpipe_writer);
+
+ // Attach the pipes to the socket object.
+ attach_pipes (inpipe_reader, outpipe_writer, blob_t ());
+
+ // Attach the pipes to the session object.
+ session->attach_pipes (outpipe_reader, inpipe_writer, blob_t ());
+ }
+
+ // Activate the session. Make it a child of this socket.
+ launch_child (session);
+
+ return 0;
+}
+
+int zmq::socket_base_t::send (::zmq_msg_t *msg_, int flags_)
+{
+ // Check whether the library haven't been shut down yet.
+ if (unlikely (ctx_terminated)) {
+ errno = ETERM;
+ return -1;
+ }
+
+ // Check whether message passed to the function is valid.
+ if (unlikely ((msg_->flags | ZMQ_MSG_MASK) != 0xff)) {
+ errno = EFAULT;
+ return -1;
+ }
+
+ // Process pending commands, if any.
+ int rc = process_commands (0, true);
+ if (unlikely (rc != 0))
+ return -1;
+
+ // At this point we impose the MORE flag on the message.
+ if (flags_ & ZMQ_SNDMORE)
+ msg_->flags |= ZMQ_MSG_MORE;
+
+ // Try to send the message.
+ rc = xsend (msg_, flags_);
+ if (rc == 0)
+ return 0;
+ if (unlikely (errno != EAGAIN))
+ return -1;
+
+ // In case of non-blocking send we'll simply propagate
+ // the error - including EAGAIN - upwards.
+ if (flags_ & ZMQ_NOBLOCK)
+ return -1;
+
+ // Compute the time when the timeout should occur.
+ // If the timeout is infite, don't care.
+ clock_t clock ;
+ int timeout = -1;
+ uint64_t end = timeout < 0 ? 0 : (clock.now_ms () + timeout);
+
+ // Oops, we couldn't send the message. Wait for the next
+ // command, process it and try to send the message again.
+ while (true) {
+ if (unlikely (process_commands (timeout, false) != 0))
+ return -1;
+ rc = xsend (msg_, flags_);
+ if (rc == 0)
+ break;
+ if (unlikely (errno != EAGAIN))
+ return -1;
+ if (timeout > 0) {
+ timeout = (int) (end - clock.now_ms ());
+ if (timeout <= 0) {
+ errno = EAGAIN;
+ return -1;
+ }
+ }
+ }
+ return 0;
+}
+
+int zmq::socket_base_t::recv (::zmq_msg_t *msg_, int flags_)
+{
+ // Check whether the library haven't been shut down yet.
+ if (unlikely (ctx_terminated)) {
+ errno = ETERM;
+ return -1;
+ }
+
+ // Check whether message passed to the function is valid.
+ if (unlikely ((msg_->flags | ZMQ_MSG_MASK) != 0xff)) {
+ errno = EFAULT;
+ return -1;
+ }
+
+ // Get the message.
+ int rc = xrecv (msg_, flags_);
+ if (unlikely (rc != 0 && errno != EAGAIN))
+ return -1;
+ int err = errno;
+
+ // Once every inbound_poll_rate messages check for signals and process
+ // incoming commands. This happens only if we are not polling altogether
+ // because there are messages available all the time. If poll occurs,
+ // ticks is set to zero and thus we avoid this code.
+ //
+ // Note that 'recv' uses different command throttling algorithm (the one
+ // described above) from the one used by 'send'. This is because counting
+ // ticks is more efficient than doing RDTSC all the time.
+ if (++ticks == inbound_poll_rate) {
+ if (unlikely (process_commands (0, false) != 0))
+ return -1;
+ ticks = 0;
+ }
+
+ // If we have the message, return immediately.
+ if (rc == 0) {
+ rcvmore = msg_->flags & ZMQ_MSG_MORE;
+ if (rcvmore)
+ msg_->flags &= ~ZMQ_MSG_MORE;
+ return 0;
+ }
+
+ // If we don't have the message, restore the original cause of the problem.
+ errno = err;
+
+ // If the message cannot be fetched immediately, there are two scenarios.
+ // For non-blocking recv, commands are processed in case there's an
+ // activate_reader command already waiting int a command pipe.
+ // If it's not, return EAGAIN.
+ if (flags_ & ZMQ_NOBLOCK) {
+ if (errno != EAGAIN)
+ return -1;
+ if (unlikely (process_commands (0, false) != 0))
+ return -1;
+ ticks = 0;
+
+ rc = xrecv (msg_, flags_);
+ if (rc == 0) {
+ rcvmore = msg_->flags & ZMQ_MSG_MORE;
+ if (rcvmore)
+ msg_->flags &= ~ZMQ_MSG_MORE;
+ }
+ return rc;
+ }
+
+ // Compute the time when the timeout should occur.
+ // If the timeout is infite, don't care.
+ clock_t clock ;
+ int timeout = -1;
+ uint64_t end = timeout < 0 ? 0 : (clock.now_ms () + timeout);
+
+ // In blocking scenario, commands are processed over and over again until
+ // we are able to fetch a message.
+ bool block = (ticks != 0);
+ while (true) {
+ if (unlikely (process_commands (block ? timeout : 0, false) != 0))
+ return -1;
+ rc = xrecv (msg_, flags_);
+ if (rc == 0) {
+ ticks = 0;
+ break;
+ }
+ if (unlikely (errno != EAGAIN))
+ return -1;
+ block = true;
+ if (timeout > 0) {
+ timeout = (int) (end - clock.now_ms ());
+ if (timeout <= 0) {
+ errno = EAGAIN;
+ return -1;
+ }
+ }
+ }
+
+ rcvmore = msg_->flags & ZMQ_MSG_MORE;
+ if (rcvmore)
+ msg_->flags &= ~ZMQ_MSG_MORE;
+ return 0;
+}
+
+int zmq::socket_base_t::close ()
+{
+ // Transfer the ownership of the socket from this application thread
+ // to the reaper thread which will take care of the rest of shutdown
+ // process.
+ send_reap (this);
+
+ return 0;
+}
+
+bool zmq::socket_base_t::has_in ()
+{
+ return xhas_in ();
+}
+
+bool zmq::socket_base_t::has_out ()
+{
+ return xhas_out ();
+}
+
+bool zmq::socket_base_t::register_session (const blob_t &name_,
+ session_t *session_)
+{
+ sessions_sync.lock ();
+ bool registered = sessions.insert (
+ sessions_t::value_type (name_, session_)).second;
+ sessions_sync.unlock ();
+ return registered;
+}
+
+void zmq::socket_base_t::unregister_session (const blob_t &name_)
+{
+ sessions_sync.lock ();
+ sessions_t::iterator it = sessions.find (name_);
+ zmq_assert (it != sessions.end ());
+ sessions.erase (it);
+ sessions_sync.unlock ();
+}
+
+zmq::session_t *zmq::socket_base_t::find_session (const blob_t &name_)
+{
+ sessions_sync.lock ();
+ sessions_t::iterator it = sessions.find (name_);
+ if (it == sessions.end ()) {
+ sessions_sync.unlock ();
+ return NULL;
+ }
+ session_t *session = it->second;
+
+ // Prepare the session for subsequent attach command.
+ session->inc_seqnum ();
+
+ sessions_sync.unlock ();
+ return session;
+}
+
+void zmq::socket_base_t::start_reaping (poller_t *poller_)
+{
+ poller = poller_;
+ handle = poller->add_fd (mailbox.get_fd (), this);
+ poller->set_pollin (handle);
+}
+
+int zmq::socket_base_t::process_commands (int timeout_, bool throttle_)
+{
+ int rc;
+ command_t cmd;
+ if (timeout_ != 0) {
+
+ // If we are asked to wait, simply ask mailbox to wait.
+ rc = mailbox.recv (&cmd, timeout_);
+ }
+ else {
+
+ // If we are asked not to wait, check whether we haven't processed
+ // commands recently, so that we can throttle the new commands.
+
+ // Get the CPU's tick counter. If 0, the counter is not available.
+ uint64_t tsc = zmq::clock_t::rdtsc ();
+
+ // Optimised version of command processing - it doesn't have to check
+ // for incoming commands each time. It does so only if certain time
+ // elapsed since last command processing. Command delay varies
+ // depending on CPU speed: It's ~1ms on 3GHz CPU, ~2ms on 1.5GHz CPU
+ // etc. The optimisation makes sense only on platforms where getting
+ // a timestamp is a very cheap operation (tens of nanoseconds).
+ if (tsc && throttle_) {
+
+ // Check whether TSC haven't jumped backwards (in case of migration
+ // between CPU cores) and whether certain time have elapsed since
+ // last command processing. If it didn't do nothing.
+ if (tsc >= last_tsc && tsc - last_tsc <= max_command_delay)
+ return 0;
+ last_tsc = tsc;
+ }
+
+ // Check whether there are any commands pending for this thread.
+ rc = mailbox.recv (&cmd, 0);
+ }
+
+ // Process all the commands available at the moment.
+ while (true) {
+ if (rc == -1 && errno == EAGAIN)
+ break;
+ if (rc == -1 && errno == EINTR)
+ return -1;
+ errno_assert (rc == 0);
+ cmd.destination->process_command (cmd);
+ rc = mailbox.recv (&cmd, 0);
+ }
+
+ if (ctx_terminated) {
+ errno = ETERM;
+ return -1;
+ }
+
+ return 0;
+}
+
+void zmq::socket_base_t::process_stop ()
+{
+ // Here, someone have called zmq_term while the socket was still alive.
+ // We'll remember the fact so that any blocking call is interrupted and any
+ // further attempt to use the socket will return ETERM. The user is still
+ // responsible for calling zmq_close on the socket though!
+ ctx_terminated = true;
+}
+
+void zmq::socket_base_t::process_bind (reader_t *in_pipe_, writer_t *out_pipe_,
+ const blob_t &peer_identity_)
+{
+ attach_pipes (in_pipe_, out_pipe_, peer_identity_);
+}
+
+void zmq::socket_base_t::process_unplug ()
+{
+}
+
+void zmq::socket_base_t::process_term (int linger_)
+{
+ // Unregister all inproc endpoints associated with this socket.
+ // Doing this we make sure that no new pipes from other sockets (inproc)
+ // will be initiated.
+ unregister_endpoints (this);
+
+ // Continue the termination process immediately.
+ own_t::process_term (linger_);
+}
+
+void zmq::socket_base_t::process_destroy ()
+{
+ destroyed = true;
+}
+
+int zmq::socket_base_t::xsetsockopt (int option_, const void *optval_,
+ size_t optvallen_)
+{
+ errno = EINVAL;
+ return -1;
+}
+
+bool zmq::socket_base_t::xhas_out ()
+{
+ return false;
+}
+
+int zmq::socket_base_t::xsend (zmq_msg_t *msg_, int options_)
+{
+ errno = ENOTSUP;
+ return -1;
+}
+
+bool zmq::socket_base_t::xhas_in ()
+{
+ return false;
+}
+
+int zmq::socket_base_t::xrecv (zmq_msg_t *msg_, int options_)
+{
+ errno = ENOTSUP;
+ return -1;
+}
+
+void zmq::socket_base_t::in_event ()
+{
+ // Process any commands from other threads/sockets that may be available
+ // at the moment. Ultimately, socket will be destroyed.
+ process_commands (false, false);
+ check_destroy ();
+}
+
+void zmq::socket_base_t::out_event ()
+{
+ zmq_assert (false);
+}
+
+void zmq::socket_base_t::timer_event (int id_)
+{
+ zmq_assert (false);
+}
+
+void zmq::socket_base_t::check_destroy ()
+{
+ // If the object was already marked as destroyed, finish the deallocation.
+ if (destroyed) {
+
+ // Remove the socket from the reaper's poller.
+ poller->rm_fd (handle);
+
+ // Remove the socket from the context.
+ destroy_socket (this);
+
+ // Notify the reaper about the fact.
+ send_reaped ();
+
+ // Deallocate.
+ own_t::process_destroy ();
+ }
+}
diff --git a/src/0mq/socket_base.hpp b/src/0mq/socket_base.hpp
new file mode 100644
index 0000000..145211b
--- /dev/null
+++ b/src/0mq/socket_base.hpp
@@ -0,0 +1,207 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_SOCKET_BASE_HPP_INCLUDED__
+#define __ZMQ_SOCKET_BASE_HPP_INCLUDED__
+
+#include <map>
+#include <vector>
+
+#include "../include/zmq.h"
+
+#include "own.hpp"
+#include "array.hpp"
+#include "mutex.hpp"
+#include "stdint.hpp"
+#include "poller.hpp"
+#include "atomic_counter.hpp"
+#include "i_poll_events.hpp"
+#include "mailbox.hpp"
+#include "stdint.hpp"
+#include "blob.hpp"
+#include "own.hpp"
+
+namespace zmq
+{
+
+ class socket_base_t :
+ public own_t,
+ public array_item_t,
+ public i_poll_events
+ {
+ friend class reaper_t;
+
+ public:
+
+ // Returns false if object is not a socket.
+ bool check_tag ();
+
+ // Create a socket of a specified type.
+ static socket_base_t *create (int type_, class ctx_t *parent_,
+ uint32_t tid_);
+
+ // Returns the mailbox associated with this socket.
+ mailbox_t *get_mailbox ();
+
+ // Interrupt blocking call if the socket is stuck in one.
+ // This function can be called from a different thread!
+ void stop ();
+
+ // Interface for communication with the API layer.
+ int setsockopt (int option_, const void *optval_, size_t optvallen_);
+ int getsockopt (int option_, void *optval_, size_t *optvallen_);
+ int bind (const char *addr_);
+ int connect (const char *addr_);
+ int send (zmq_msg_t *msg_, int flags_);
+ int recv (zmq_msg_t *msg_, int flags_);
+ int close ();
+
+ // These functions are used by the polling mechanism to determine
+ // which events are to be reported from this socket.
+ bool has_in ();
+ bool has_out ();
+
+ // Registry of named sessions.
+ bool register_session (const blob_t &name_, class session_t *session_);
+ void unregister_session (const blob_t &name_);
+ class session_t *find_session (const blob_t &name_);
+
+ // i_reader_events interface implementation.
+ void activated (class reader_t *pipe_);
+ void terminated (class reader_t *pipe_);
+
+ // i_writer_events interface implementation.
+ void activated (class writer_t *pipe_);
+ void terminated (class writer_t *pipe_);
+
+ // Using this function reaper thread ask the socket to regiter with
+ // its poller.
+ void start_reaping (poller_t *poller_);
+
+ // i_poll_events implementation. This interface is used when socket
+ // is handled by the poller in the reaper thread.
+ void in_event ();
+ void out_event ();
+ void timer_event (int id_);
+
+ // To be called after processing commands or invoking any command
+ // handlers explicitly. If required, it will deallocate the socket.
+ void check_destroy ();
+
+ protected:
+
+ socket_base_t (class ctx_t *parent_, uint32_t tid_);
+ virtual ~socket_base_t ();
+
+ // Concrete algorithms for the x- methods are to be defined by
+ // individual socket types.
+ virtual void xattach_pipes (class reader_t *inpipe_,
+ class writer_t *outpipe_, const blob_t &peer_identity_) = 0;
+
+ // The default implementation assumes there are no specific socket
+ // options for the particular socket type. If not so, overload this
+ // method.
+ virtual int xsetsockopt (int option_, const void *optval_,
+ size_t optvallen_);
+
+ // The default implementation assumes that send is not supported.
+ virtual bool xhas_out ();
+ virtual int xsend (zmq_msg_t *msg_, int options_);
+
+ // The default implementation assumes that recv in not supported.
+ virtual bool xhas_in ();
+ virtual int xrecv (zmq_msg_t *msg_, int options_);
+
+ // We are declaring termination handler as protected so that
+ // individual socket types can hook into the termination process
+ // by overloading it.
+ void process_term (int linger_);
+
+ // Delay actual destruction of the socket.
+ void process_destroy ();
+
+ private:
+
+ // Used to check whether the object is a socket.
+ uint32_t tag;
+
+ // If true, associated context was already terminated.
+ bool ctx_terminated;
+
+ // If true, object should have been already destroyed. However,
+ // destruction is delayed while we unwind the stack to the point
+ // where it doesn't intersect the object being destroyed.
+ bool destroyed;
+
+ // Parse URI string.
+ int parse_uri (const char *uri_, std::string &protocol_,
+ std::string &address_);
+
+ // Check whether transport protocol, as specified in connect or
+ // bind, is available and compatible with the socket type.
+ int check_protocol (const std::string &protocol_);
+
+ // If no identity set generate one and call xattach_pipes ().
+ void attach_pipes (class reader_t *inpipe_, class writer_t *outpipe_,
+ const blob_t &peer_identity_);
+
+ // Processes commands sent to this socket (if any). If timeout is -1,
+ // returns only after at least one command was processed.
+ // If throttle argument is true, commands are processed at most once
+ // in a predefined time period.
+ int process_commands (int timeout_, bool throttle_);
+
+ // Handlers for incoming commands.
+ void process_stop ();
+ void process_bind (class reader_t *in_pipe_, class writer_t *out_pipe_,
+ const blob_t &peer_identity_);
+ void process_unplug ();
+
+ // Socket's mailbox object.
+ mailbox_t mailbox;
+
+ // Reaper's poller and handle of this socket within it.
+ poller_t *poller;
+ poller_t::handle_t handle;
+
+ // Timestamp of when commands were processed the last time.
+ uint64_t last_tsc;
+
+ // Number of messages received since last command processing.
+ int ticks;
+
+ // If true there's a half-read message in the socket.
+ bool rcvmore;
+
+ // Lists of existing sessions. This list is never referenced from
+ // within the socket, instead it is used by objects owned by
+ // the socket. As those objects can live in different threads,
+ // the access is synchronised by mutex.
+ typedef std::map <blob_t, session_t*> sessions_t;
+ sessions_t sessions;
+ mutex_t sessions_sync;
+
+ socket_base_t (const socket_base_t&);
+ const socket_base_t &operator = (const socket_base_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/stdint.hpp b/src/0mq/stdint.hpp
new file mode 100644
index 0000000..73186d3
--- /dev/null
+++ b/src/0mq/stdint.hpp
@@ -0,0 +1,63 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_STDINT_HPP_INCLUDED__
+#define __ZMQ_STDINT_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#if defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_OPENVMS
+
+#include <inttypes.h>
+
+#elif defined _MSC_VER
+
+#ifndef int8_t
+typedef __int8 int8_t;
+#endif
+#ifndef int16_t
+typedef __int16 int16_t;
+#endif
+#ifndef int32_t
+typedef __int32 int32_t;
+#endif
+#ifndef int64_t
+typedef __int64 int64_t;
+#endif
+#ifndef uint8_t
+typedef unsigned __int8 uint8_t;
+#endif
+#ifndef uint16_t
+typedef unsigned __int16 uint16_t;
+#endif
+#ifndef uint32_t
+typedef unsigned __int32 uint32_t;
+#endif
+#ifndef uint64_t
+typedef unsigned __int64 uint64_t;
+#endif
+
+#else
+
+#include <stdint.h>
+
+#endif
+
+#endif
diff --git a/src/0mq/sub.cpp b/src/0mq/sub.cpp
new file mode 100644
index 0000000..aef7369
--- /dev/null
+++ b/src/0mq/sub.cpp
@@ -0,0 +1,75 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "sub.hpp"
+
+zmq::sub_t::sub_t (class ctx_t *parent_, uint32_t tid_) :
+ xsub_t (parent_, tid_)
+{
+ options.type = ZMQ_SUB;
+}
+
+zmq::sub_t::~sub_t ()
+{
+}
+
+int zmq::sub_t::xsetsockopt (int option_, const void *optval_,
+ size_t optvallen_)
+{
+ if (option_ != ZMQ_SUBSCRIBE && option_ != ZMQ_UNSUBSCRIBE) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ // Create the subscription message.
+ zmq_msg_t msg;
+ zmq_msg_init_size (&msg, optvallen_ + 1);
+ unsigned char *data = (unsigned char*) zmq_msg_data (&msg);
+ if (option_ == ZMQ_SUBSCRIBE)
+ *data = 1;
+ else if (option_ == ZMQ_UNSUBSCRIBE)
+ *data = 0;
+ memcpy (data + 1, optval_, optvallen_);
+
+ // Pass it further on in the stack.
+ int err = 0;
+ int rc = xsub_t::xsend (&msg, 0);
+ if (rc != 0)
+ err = errno;
+ zmq_msg_close (&msg);
+ if (rc != 0)
+ errno = err;
+ return rc;
+}
+
+int zmq::sub_t::xsend (zmq_msg_t *msg_, int options_)
+{
+ // Overload the XSUB's send.
+ errno = ENOTSUP;
+ return -1;
+}
+
+bool zmq::sub_t::xhas_out ()
+{
+ // Overload the XSUB's send.
+ return false;
+}
diff --git a/src/0mq/sub.hpp b/src/0mq/sub.hpp
new file mode 100644
index 0000000..d1f467d
--- /dev/null
+++ b/src/0mq/sub.hpp
@@ -0,0 +1,50 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_SUB_HPP_INCLUDED__
+#define __ZMQ_SUB_HPP_INCLUDED__
+
+#include "xsub.hpp"
+
+namespace zmq
+{
+
+ class sub_t : public xsub_t
+ {
+ public:
+
+ sub_t (class ctx_t *parent_, uint32_t tid_);
+ ~sub_t ();
+
+ protected:
+
+ int xsetsockopt (int option_, const void *optval_, size_t optvallen_);
+ int xsend (zmq_msg_t *msg_, int options_);
+ bool xhas_out ();
+
+ private:
+
+ sub_t (const sub_t&);
+ const sub_t &operator = (const sub_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/swap.cpp b/src/0mq/swap.cpp
new file mode 100644
index 0000000..5f1b261
--- /dev/null
+++ b/src/0mq/swap.cpp
@@ -0,0 +1,323 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "platform.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#include <io.h>
+#else
+#include <unistd.h>
+#endif
+
+#include "../include/zmq.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sstream>
+#include <algorithm>
+
+#include "swap.hpp"
+#include "config.hpp"
+#include "atomic_counter.hpp"
+#include "err.hpp"
+
+zmq::swap_t::swap_t (int64_t filesize_) :
+ fd (-1),
+ filesize (filesize_),
+ file_pos (0),
+ write_pos (0),
+ read_pos (0),
+ block_size (swap_block_size),
+ write_buf_start_addr (0)
+{
+ zmq_assert (filesize > 0);
+ zmq_assert (block_size > 0);
+
+ buf1 = new (std::nothrow) char [block_size];
+ alloc_assert (buf1);
+
+ buf2 = new (std::nothrow) char [block_size];
+ alloc_assert (buf2);
+
+ read_buf = write_buf = buf1;
+}
+
+zmq::swap_t::~swap_t ()
+{
+ delete [] buf1;
+ delete [] buf2;
+
+ if (fd == -1)
+ return;
+
+#ifdef ZMQ_HAVE_WINDOWS
+ int rc = _close (fd);
+#else
+ int rc = close (fd);
+#endif
+ errno_assert (rc == 0);
+
+#ifdef ZMQ_HAVE_WINDOWS
+ rc = _unlink (filename.c_str ());
+#else
+ rc = unlink (filename.c_str ());
+#endif
+ errno_assert (rc == 0);
+}
+
+int zmq::swap_t::init ()
+{
+ static zmq::atomic_counter_t seqnum (0);
+
+ // Get process ID.
+#ifdef ZMQ_HAVE_WINDOWS
+ int pid = GetCurrentThreadId ();
+#else
+ pid_t pid = getpid ();
+#endif
+
+ std::ostringstream outs;
+ outs << "zmq_" << pid << '_' << seqnum.get () << ".swap";
+ filename = outs.str ();
+
+ seqnum.add (1);
+
+ // Open the backing file.
+#ifdef ZMQ_HAVE_WINDOWS
+ fd = _open (filename.c_str (), _O_RDWR | _O_CREAT, 0600);
+#else
+ fd = open (filename.c_str (), O_RDWR | O_CREAT, 0600);
+#endif
+ if (fd == -1)
+ return -1;
+
+#if (defined (ZMQ_HAVE_LINUX) && !defined (ZMQ_HAVE_ANDROID))
+ // Enable more aggresive read-ahead optimization.
+ posix_fadvise (fd, 0, filesize, POSIX_FADV_SEQUENTIAL);
+#endif
+ return 0;
+}
+
+bool zmq::swap_t::store (zmq_msg_t *msg_)
+{
+ size_t msg_size = zmq_msg_size (msg_);
+
+ // Check buffer space availability.
+ // NOTE: We always keep one byte open.
+ if (buffer_space () <= (int64_t) (sizeof msg_size + 1 + msg_size))
+ return false;
+
+ // Don't store the ZMQ_MSG_SHARED flag.
+ uint8_t msg_flags = msg_->flags & ~ZMQ_MSG_SHARED;
+
+ // Write message length, flags, and message body.
+ copy_to_file (&msg_size, sizeof msg_size);
+ copy_to_file (&msg_flags, sizeof msg_flags);
+ copy_to_file (zmq_msg_data (msg_), msg_size);
+
+ return true;
+}
+
+void zmq::swap_t::fetch (zmq_msg_t *msg_)
+{
+ // There must be at least one message available.
+ zmq_assert (read_pos != write_pos);
+
+ // Retrieve the message size.
+ size_t msg_size;
+ copy_from_file (&msg_size, sizeof msg_size);
+
+ // Initialize the message.
+ zmq_msg_init_size (msg_, msg_size);
+
+ // Retrieve the message flags.
+ copy_from_file (&msg_->flags, sizeof msg_->flags);
+
+ // Retrieve the message payload.
+ copy_from_file (zmq_msg_data (msg_), msg_size);
+}
+
+void zmq::swap_t::commit ()
+{
+ commit_pos = write_pos;
+}
+
+void zmq::swap_t::rollback ()
+{
+ if (commit_pos == write_pos || read_pos == write_pos)
+ return;
+
+ if (write_pos > read_pos)
+ zmq_assert (read_pos <= commit_pos && commit_pos <= write_pos);
+ else
+ zmq_assert (read_pos <= commit_pos || commit_pos <= write_pos);
+
+ if (commit_pos / block_size == read_pos / block_size) {
+ write_buf_start_addr = commit_pos % block_size;
+ write_buf = read_buf;
+ }
+ else if (commit_pos / block_size != write_pos / block_size) {
+ write_buf_start_addr = commit_pos % block_size;
+ fill_buf (write_buf, write_buf_start_addr);
+ }
+ write_pos = commit_pos;
+}
+
+bool zmq::swap_t::empty ()
+{
+ return read_pos == write_pos;
+}
+
+/*
+bool zmq::swap_t::full ()
+{
+ // Check that at least the message size can be written to the swap.
+ return buffer_space () < (int64_t) (sizeof (size_t) + 1);
+}
+*/
+
+bool zmq::swap_t::fits (zmq_msg_t *msg_)
+{
+ // Check whether whole binary representation of the message
+ // fits into the swap.
+ size_t msg_size = zmq_msg_size (msg_);
+ if (buffer_space () <= (int64_t) (sizeof msg_size + 1 + msg_size))
+ return false;
+ return true;
+ }
+
+void zmq::swap_t::copy_from_file (void *buffer_, size_t count_)
+{
+ char *dest_ptr = (char *) buffer_;
+ size_t chunk_size, remainder = count_;
+
+ while (remainder > 0) {
+ chunk_size = std::min (remainder,
+ std::min ((size_t) (filesize - read_pos),
+ (size_t) (block_size - read_pos % block_size)));
+
+ memcpy (dest_ptr, &read_buf [read_pos % block_size], chunk_size);
+ dest_ptr += chunk_size;
+
+ read_pos = (read_pos + chunk_size) % filesize;
+ if (read_pos % block_size == 0) {
+ if (read_pos / block_size == write_pos / block_size)
+ read_buf = write_buf;
+ else
+ fill_buf (read_buf, read_pos);
+ }
+ remainder -= chunk_size;
+ }
+}
+
+void zmq::swap_t::copy_to_file (const void *buffer_, size_t count_)
+{
+ char *source_ptr = (char *) buffer_;
+ size_t chunk_size, remainder = count_;
+
+ while (remainder > 0) {
+ chunk_size = std::min (remainder,
+ std::min ((size_t) (filesize - write_pos),
+ (size_t) (block_size - write_pos % block_size)));
+
+ memcpy (&write_buf [write_pos % block_size], source_ptr, chunk_size);
+ source_ptr += chunk_size;
+
+ write_pos = (write_pos + chunk_size) % filesize;
+ if (write_pos % block_size == 0) {
+ save_write_buf ();
+ write_buf_start_addr = write_pos;
+
+ if (write_buf == read_buf) {
+ if (read_buf == buf2)
+ write_buf = buf1;
+ else
+ write_buf = buf2;
+ }
+ }
+ remainder -= chunk_size;
+ }
+}
+
+void zmq::swap_t::fill_buf (char *buf, int64_t pos)
+{
+ if (file_pos != pos) {
+#ifdef ZMQ_HAVE_WINDOWS
+ __int64 offset = _lseeki64 (fd, pos, SEEK_SET);
+#else
+ off_t offset = lseek (fd, (off_t) pos, SEEK_SET);
+#endif
+ errno_assert (offset == pos);
+ file_pos = pos;
+ }
+ size_t octets_stored = 0;
+ size_t octets_total = std::min (block_size, (size_t) (filesize - file_pos));
+
+ while (octets_stored < octets_total) {
+#ifdef ZMQ_HAVE_WINDOWS
+ int rc = _read (fd, &buf [octets_stored], octets_total - octets_stored);
+#else
+ ssize_t rc = read (fd, &buf [octets_stored],
+ octets_total - octets_stored);
+#endif
+ errno_assert (rc > 0);
+ octets_stored += rc;
+ }
+ file_pos += octets_total;
+}
+
+void zmq::swap_t::save_write_buf ()
+{
+ if (file_pos != write_buf_start_addr) {
+#ifdef ZMQ_HAVE_WINDOWS
+ __int64 offset = _lseeki64 (fd, write_buf_start_addr, SEEK_SET);
+#else
+ off_t offset = lseek (fd, (off_t) write_buf_start_addr, SEEK_SET);
+#endif
+ errno_assert (offset == write_buf_start_addr);
+ file_pos = write_buf_start_addr;
+ }
+ size_t octets_stored = 0;
+ size_t octets_total = std::min (block_size, (size_t) (filesize - file_pos));
+
+ while (octets_stored < octets_total) {
+#ifdef ZMQ_HAVE_WINDOWS
+ int rc = _write (fd, &write_buf [octets_stored],
+ octets_total - octets_stored);
+#else
+ ssize_t rc = write (fd, &write_buf [octets_stored],
+ octets_total - octets_stored);
+#endif
+ errno_assert (rc > 0);
+ octets_stored += rc;
+ }
+ file_pos += octets_total;
+}
+
+int64_t zmq::swap_t::buffer_space ()
+{
+ if (write_pos < read_pos)
+ return read_pos - write_pos;
+
+ return filesize - (write_pos - read_pos);
+}
diff --git a/src/0mq/swap.hpp b/src/0mq/swap.hpp
new file mode 100644
index 0000000..ad2bcc3
--- /dev/null
+++ b/src/0mq/swap.hpp
@@ -0,0 +1,123 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_SWAP_HPP_INCLUDED__
+#define __ZMQ_SWAP_HPP_INCLUDED__
+
+#include "../include/zmq.h"
+
+#include <string>
+#include "stdint.hpp"
+
+namespace zmq
+{
+
+ // This class implements a message swap. Messages are retrieved from
+ // the swap in the same order as they entered it.
+
+ class swap_t
+ {
+ public:
+
+ enum { default_block_size = 8192 };
+
+ // Creates the swap.
+ swap_t (int64_t filesize_);
+
+ ~swap_t ();
+
+ int init ();
+
+ // Stores the message into the swap. The function
+ // returns false if the swap is full; true otherwise.
+ bool store (zmq_msg_t *msg_);
+
+ // Fetches the oldest message from the swap. It is an error
+ // to call this function when the swap is empty.
+ void fetch (zmq_msg_t *msg_);
+
+ void commit ();
+
+ void rollback ();
+
+ // Returns true if the swap is empty; false otherwise.
+ bool empty ();
+
+
+// // Returns true if and only if the swap is full.
+// bool full ();
+
+ // Returns true if the message fits into swap.
+ bool fits (zmq_msg_t *msg_);
+
+ private:
+
+ // Copies data from a memory buffer to the backing file.
+ // Wraps around when reaching maximum file size.
+ void copy_from_file (void *buffer_, size_t count_);
+
+ // Copies data from the backing file to the memory buffer.
+ // Wraps around when reaching end-of-file.
+ void copy_to_file (const void *buffer_, size_t count_);
+
+ // Returns the buffer space available.
+ int64_t buffer_space ();
+
+ void fill_buf (char *buf, int64_t pos);
+
+ void save_write_buf ();
+
+ // File descriptor to the backing file.
+ int fd;
+
+ // Name of the backing file.
+ std::string filename;
+
+ // Maximum size of the backing file.
+ int64_t filesize;
+
+ // File offset associated with the fd file descriptor.
+ int64_t file_pos;
+
+ // File offset the next message will be stored at.
+ int64_t write_pos;
+
+ // File offset the next message will be read from.
+ int64_t read_pos;
+
+ int64_t commit_pos;
+
+ size_t block_size;
+
+ char *buf1;
+ char *buf2;
+ char *read_buf;
+ char *write_buf;
+
+ int64_t write_buf_start_addr;
+
+ // Disable copying of the swap object.
+ swap_t (const swap_t&);
+ const swap_t &operator = (const swap_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/tcp_connecter.cpp b/src/0mq/tcp_connecter.cpp
new file mode 100644
index 0000000..6bc1b2d
--- /dev/null
+++ b/src/0mq/tcp_connecter.cpp
@@ -0,0 +1,312 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <string.h>
+
+#include <string>
+
+#include "../include/zmq.h"
+
+#include "tcp_connecter.hpp"
+#include "platform.hpp"
+#include "ip.hpp"
+#include "err.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+
+zmq::tcp_connecter_t::tcp_connecter_t () :
+ s (retired_fd)
+{
+ memset (&addr, 0, sizeof (addr));
+ addr_len = 0;
+}
+
+zmq::tcp_connecter_t::~tcp_connecter_t ()
+{
+ if (s != retired_fd)
+ close ();
+}
+
+int zmq::tcp_connecter_t::set_address (const char *protocol_, const char *addr_)
+{
+ if (strcmp (protocol_, "tcp") == 0)
+ return resolve_ip_hostname (&addr, &addr_len, addr_);
+
+ errno = EPROTONOSUPPORT;
+ return -1;
+}
+
+int zmq::tcp_connecter_t::open ()
+{
+ zmq_assert (s == retired_fd);
+
+ // Create the socket.
+ s = open_socket (addr.ss_family, SOCK_STREAM, IPPROTO_TCP);
+ if (s == INVALID_SOCKET) {
+ wsa_error_to_errno ();
+ return -1;
+ }
+
+ // Set to non-blocking mode.
+ unsigned long argp = 1;
+ int rc = ioctlsocket (s, FIONBIO, &argp);
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Disable Nagle's algorithm.
+ int flag = 1;
+ rc = setsockopt (s, IPPROTO_TCP, TCP_NODELAY, (char*) &flag,
+ sizeof (int));
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Connect to the remote peer.
+ rc = ::connect (s, (sockaddr*) &addr, addr_len);
+
+ // Connect was successfull immediately.
+ if (rc == 0)
+ return 0;
+
+ // Asynchronous connect was launched.
+ if (rc == SOCKET_ERROR && (WSAGetLastError () == WSAEINPROGRESS ||
+ WSAGetLastError () == WSAEWOULDBLOCK)) {
+ errno = EAGAIN;
+ return -1;
+ }
+
+ wsa_error_to_errno ();
+ return -1;
+}
+
+int zmq::tcp_connecter_t::close ()
+{
+ zmq_assert (s != retired_fd);
+ int rc = closesocket (s);
+ wsa_assert (rc != SOCKET_ERROR);
+ s = retired_fd;
+ return 0;
+}
+
+zmq::fd_t zmq::tcp_connecter_t::get_fd ()
+{
+ return s;
+}
+
+zmq::fd_t zmq::tcp_connecter_t::connect ()
+{
+ // Nonblocking connect have finished. Check whether an error occured.
+ int err = 0;
+ socklen_t len = sizeof err;
+ int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char*) &err, &len);
+ zmq_assert (rc == 0);
+ if (err != 0) {
+
+ // Assert that the error was caused by the networking problems
+ // rather than 0MQ bug.
+ if (err == WSAECONNREFUSED || err == WSAETIMEDOUT ||
+ err == WSAECONNABORTED || err == WSAEHOSTUNREACH ||
+ err == WSAENETUNREACH || err == WSAENETDOWN)
+ return retired_fd;
+
+ wsa_assert_no (err);
+ }
+
+ // Return the newly connected socket.
+ fd_t result = s;
+ s = retired_fd;
+ return result;
+}
+
+#else
+
+#include <unistd.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <netinet/tcp.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#include <fcntl.h>
+
+#ifdef ZMQ_HAVE_OPENVMS
+#include <ioctl.h>
+#endif
+
+zmq::tcp_connecter_t::tcp_connecter_t () :
+ s (retired_fd)
+{
+ memset (&addr, 0, sizeof (addr));
+}
+
+zmq::tcp_connecter_t::~tcp_connecter_t ()
+{
+ if (s != retired_fd)
+ close ();
+}
+
+int zmq::tcp_connecter_t::set_address (const char *protocol_, const char *addr_)
+{
+ if (strcmp (protocol_, "tcp") == 0)
+ return resolve_ip_hostname (&addr, &addr_len, addr_);
+ else
+ if (strcmp (protocol_, "ipc") == 0)
+ return resolve_local_path (&addr, &addr_len, addr_);
+
+ errno = EPROTONOSUPPORT;
+ return -1;
+}
+
+int zmq::tcp_connecter_t::open ()
+{
+ zmq_assert (s == retired_fd);
+ struct sockaddr *sa = (struct sockaddr*) &addr;
+
+ if (AF_UNIX != sa->sa_family) {
+
+ // Create the socket.
+ s = open_socket (sa->sa_family, SOCK_STREAM, IPPROTO_TCP);
+ if (s == -1)
+ return -1;
+
+ // Set to non-blocking mode.
+#ifdef ZMQ_HAVE_OPENVMS
+ int flags = 1;
+ int rc = ioctl (s, FIONBIO, &flags);
+ errno_assert (rc != -1);
+#else
+ int flags = fcntl (s, F_GETFL, 0);
+ if (flags == -1)
+ flags = 0;
+ int rc = fcntl (s, F_SETFL, flags | O_NONBLOCK);
+ errno_assert (rc != -1);
+#endif
+
+ // Disable Nagle's algorithm.
+ int flag = 1;
+ rc = setsockopt (s, IPPROTO_TCP, TCP_NODELAY, (char*) &flag,
+ sizeof (int));
+ errno_assert (rc == 0);
+
+#ifdef ZMQ_HAVE_OPENVMS
+ // Disable delayed acknowledgements.
+ flag = 1;
+ rc = setsockopt (s, IPPROTO_TCP, TCP_NODELACK, (char*) &flag,
+ sizeof (int));
+ errno_assert (rc != SOCKET_ERROR);
+#endif
+
+ // Connect to the remote peer.
+ rc = ::connect (s, (struct sockaddr*) &addr, addr_len);
+
+ // Connect was successfull immediately.
+ if (rc == 0)
+ return 0;
+
+ // Asynchronous connect was launched.
+ if (rc == -1 && errno == EINPROGRESS) {
+ errno = EAGAIN;
+ return -1;
+ }
+
+ // Error occured.
+ int err = errno;
+ close ();
+ errno = err;
+ return -1;
+ }
+
+#ifndef ZMQ_HAVE_OPENVMS
+ else {
+
+ // Create the socket.
+ zmq_assert (AF_UNIX == sa->sa_family);
+ s = open_socket (AF_UNIX, SOCK_STREAM, 0);
+ if (s == -1)
+ return -1;
+
+ // Set the non-blocking flag.
+ int flag = fcntl (s, F_GETFL, 0);
+ if (flag == -1)
+ flag = 0;
+ int rc = fcntl (s, F_SETFL, flag | O_NONBLOCK);
+ errno_assert (rc != -1);
+
+ // Connect to the remote peer.
+ rc = ::connect (s, (struct sockaddr*) &addr, sizeof (sockaddr_un));
+
+ // Connect was successfull immediately.
+ if (rc == 0)
+ return 0;
+
+ // Error occured.
+ int err = errno;
+ close ();
+ errno = err;
+ return -1;
+ }
+#endif
+
+ zmq_assert (false);
+ return -1;
+}
+
+int zmq::tcp_connecter_t::close ()
+{
+ zmq_assert (s != retired_fd);
+ int rc = ::close (s);
+ if (rc != 0)
+ return -1;
+ s = retired_fd;
+ return 0;
+}
+
+zmq::fd_t zmq::tcp_connecter_t::get_fd ()
+{
+ return s;
+}
+
+zmq::fd_t zmq::tcp_connecter_t::connect ()
+{
+ // Following code should handle both Berkeley-derived socket
+ // implementations and Solaris.
+ int err = 0;
+#if defined ZMQ_HAVE_HPUX
+ int len = sizeof (err);
+#else
+ socklen_t len = sizeof (err);
+#endif
+ int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char*) &err, &len);
+ if (rc == -1)
+ err = errno;
+ if (err != 0) {
+
+ // Assert if the error was caused by 0MQ bug.
+ // Networking problems are OK. No need to assert.
+ errno = err;
+ errno_assert (errno == ECONNREFUSED || errno == ECONNRESET ||
+ errno == ETIMEDOUT || errno == EHOSTUNREACH ||
+ errno == ENETUNREACH);
+
+ return retired_fd;
+ }
+
+ fd_t result = s;
+ s = retired_fd;
+ return result;
+}
+
+#endif
diff --git a/src/0mq/tcp_connecter.hpp b/src/0mq/tcp_connecter.hpp
new file mode 100644
index 0000000..06641e5
--- /dev/null
+++ b/src/0mq/tcp_connecter.hpp
@@ -0,0 +1,81 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_TCP_CONNECTER_HPP_INCLUDED__
+#define __ZMQ_TCP_CONNECTER_HPP_INCLUDED__
+
+#include "platform.hpp"
+#include "fd.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#else
+#include <sys/types.h>
+#include <sys/socket.h>
+#endif
+
+namespace zmq
+{
+
+ // The class encapsulating simple TCP listening socket.
+
+ class tcp_connecter_t
+ {
+ public:
+
+ tcp_connecter_t ();
+ ~tcp_connecter_t ();
+
+ // Set address to connect to.
+ int set_address (const char *protocol, const char *addr_);
+
+ // Open TCP connecting socket. Address is in
+ // <hostname>:<port-number> format. Returns -1 in case of error,
+ // 0 if connect was successfull immediately and 1 if async connect
+ // was launched.
+ int open ();
+
+ // Close the connecting socket.
+ int close ();
+
+ // Get the file descriptor to poll on to get notified about
+ // connection success.
+ fd_t get_fd ();
+
+ // Get the file descriptor of newly created connection. Returns
+ // retired_fd if the connection was unsuccessfull.
+ fd_t connect ();
+
+ private:
+
+ // Address to connect to.
+ sockaddr_storage addr;
+ socklen_t addr_len;
+
+ // Underlying socket.
+ fd_t s;
+
+ tcp_connecter_t (const tcp_connecter_t&);
+ const tcp_connecter_t &operator = (const tcp_connecter_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/tcp_listener.cpp b/src/0mq/tcp_listener.cpp
new file mode 100644
index 0000000..4bfaa85
--- /dev/null
+++ b/src/0mq/tcp_listener.cpp
@@ -0,0 +1,371 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <string.h>
+
+#include "../include/zmq.h"
+
+#include "tcp_listener.hpp"
+#include "platform.hpp"
+#include "ip.hpp"
+#include "config.hpp"
+#include "err.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+
+zmq::tcp_listener_t::tcp_listener_t () :
+ has_file (false),
+ s (retired_fd)
+{
+ memset (&addr, 0, sizeof (addr));
+ addr_len = 0;
+}
+
+zmq::tcp_listener_t::~tcp_listener_t ()
+{
+ if (s != retired_fd)
+ close ();
+}
+
+int zmq::tcp_listener_t::set_address (const char *protocol_, const char *addr_,
+ int backlog_)
+{
+ // IPC protocol is not supported on Windows platform.
+ if (strcmp (protocol_, "tcp") != 0 ) {
+ errno = EPROTONOSUPPORT;
+ return -1;
+ }
+
+ // Convert the interface into sockaddr_in structure.
+ int rc = resolve_ip_interface (&addr, &addr_len, addr_);
+ if (rc != 0)
+ return rc;
+
+ // Create a listening socket.
+ s = socket (addr.ss_family, SOCK_STREAM, IPPROTO_TCP);
+ if (s == INVALID_SOCKET) {
+ wsa_error_to_errno ();
+ return -1;
+ }
+
+ // Allow reusing of the address.
+ int flag = 1;
+ rc = setsockopt (s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
+ (const char*) &flag, sizeof (int));
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Set the non-blocking flag.
+ u_long uflag = 1;
+ rc = ioctlsocket (s, FIONBIO, &uflag);
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Bind the socket to the network interface and port.
+ rc = bind (s, (struct sockaddr*) &addr, addr_len);
+ if (rc == SOCKET_ERROR) {
+ wsa_error_to_errno ();
+ return -1;
+ }
+
+ // Listen for incomming connections.
+ rc = listen (s, backlog_);
+ if (rc == SOCKET_ERROR) {
+ wsa_error_to_errno ();
+ return -1;
+ }
+
+ return 0;
+}
+
+int zmq::tcp_listener_t::close ()
+{
+ zmq_assert (s != retired_fd);
+ int rc = closesocket (s);
+ wsa_assert (rc != SOCKET_ERROR);
+ s = retired_fd;
+ return 0;
+}
+
+zmq::fd_t zmq::tcp_listener_t::get_fd ()
+{
+ return s;
+}
+
+zmq::fd_t zmq::tcp_listener_t::accept ()
+{
+ zmq_assert (s != retired_fd);
+
+ // Accept one incoming connection.
+ fd_t sock = ::accept (s, NULL, NULL);
+ if (sock == INVALID_SOCKET &&
+ (WSAGetLastError () == WSAEWOULDBLOCK ||
+ WSAGetLastError () == WSAECONNRESET))
+ return retired_fd;
+
+ zmq_assert (sock != INVALID_SOCKET);
+
+ // Set to non-blocking mode.
+ unsigned long argp = 1;
+ int rc = ioctlsocket (sock, FIONBIO, &argp);
+ wsa_assert (rc != SOCKET_ERROR);
+
+ // Disable Nagle's algorithm.
+ int flag = 1;
+ rc = setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, (char*) &flag,
+ sizeof (int));
+ wsa_assert (rc != SOCKET_ERROR);
+
+ return sock;
+}
+
+#else
+
+#include <unistd.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <netinet/tcp.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#include <fcntl.h>
+
+#ifndef ZMQ_HAVE_OPENVMS
+#include <sys/un.h>
+#endif
+
+#ifdef ZMQ_HAVE_OPENVMS
+#include <ioctl.h>
+#endif
+
+zmq::tcp_listener_t::tcp_listener_t () :
+ has_file (false),
+ s (retired_fd)
+{
+ memset (&addr, 0, sizeof (addr));
+}
+
+zmq::tcp_listener_t::~tcp_listener_t ()
+{
+ if (s != retired_fd)
+ close ();
+}
+
+int zmq::tcp_listener_t::set_address (const char *protocol_, const char *addr_,
+ int backlog_)
+{
+ if (strcmp (protocol_, "tcp") == 0 ) {
+
+ // Resolve the sockaddr to bind to.
+ int rc = resolve_ip_interface (&addr, &addr_len, addr_);
+ if (rc != 0)
+ return -1;
+
+ // Create a listening socket.
+ s = open_socket (addr.ss_family, SOCK_STREAM, IPPROTO_TCP);
+ if (s == -1)
+ return -1;
+
+ // Allow reusing of the address.
+ int flag = 1;
+ rc = setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int));
+ errno_assert (rc == 0);
+
+ // Set the non-blocking flag.
+#ifdef ZMQ_HAVE_OPENVMS
+ flag = 1;
+ rc = ioctl (s, FIONBIO, &flag);
+ errno_assert (rc != -1);
+#else
+ flag = fcntl (s, F_GETFL, 0);
+ if (flag == -1)
+ flag = 0;
+ rc = fcntl (s, F_SETFL, flag | O_NONBLOCK);
+ errno_assert (rc != -1);
+#endif
+
+ // Bind the socket to the network interface and port.
+ rc = bind (s, (struct sockaddr*) &addr, addr_len);
+ if (rc != 0) {
+ int err = errno;
+ if (close () != 0)
+ return -1;
+ errno = err;
+ return -1;
+ }
+
+ // Listen for incomming connections.
+ rc = listen (s, backlog_);
+ if (rc != 0) {
+ int err = errno;
+ if (close () != 0)
+ return -1;
+ errno = err;
+ return -1;
+ }
+
+ return 0;
+ }
+#ifndef ZMQ_HAVE_OPENVMS
+ else if (strcmp (protocol_, "ipc") == 0) {
+
+ // Get rid of the file associated with the UNIX domain socket that
+ // may have been left behind by the previous run of the application.
+ ::unlink (addr_);
+
+ // Convert the address into sockaddr_un structure.
+ int rc = resolve_local_path (&addr, &addr_len, addr_);
+ if (rc != 0)
+ return -1;
+
+ // Create a listening socket.
+ s = socket (AF_UNIX, SOCK_STREAM, 0);
+ if (s == -1)
+ return -1;
+
+ // Set the non-blocking flag.
+ int flag = fcntl (s, F_GETFL, 0);
+ if (flag == -1)
+ flag = 0;
+ rc = fcntl (s, F_SETFL, flag | O_NONBLOCK);
+ errno_assert (rc != -1);
+
+ // Bind the socket to the file path.
+ rc = bind (s, (struct sockaddr*) &addr, addr_len);
+ if (rc != 0) {
+ int err = errno;
+ if (close () != 0)
+ return -1;
+ errno = err;
+ return -1;
+ }
+ has_file = true;
+
+ // Listen for incomming connections.
+ rc = listen (s, backlog_);
+ if (rc != 0) {
+ int err = errno;
+ if (close () != 0)
+ return -1;
+ errno = err;
+ return -1;
+ }
+
+ return 0;
+ }
+#endif
+ else {
+ errno = EPROTONOSUPPORT;
+ return -1;
+ }
+}
+
+int zmq::tcp_listener_t::close ()
+{
+ zmq_assert (s != retired_fd);
+ int rc = ::close (s);
+ if (rc != 0)
+ return -1;
+ s = retired_fd;
+
+#ifndef ZMQ_HAVE_OPENVMS
+ // If there's an underlying UNIX domain socket, get rid of the file it
+ // is associated with.
+ struct sockaddr_un *su = (struct sockaddr_un*) &addr;
+ if (AF_UNIX == su->sun_family && has_file) {
+ rc = ::unlink(su->sun_path);
+ if (rc != 0)
+ return -1;
+ }
+#endif
+
+ return 0;
+}
+
+zmq::fd_t zmq::tcp_listener_t::get_fd ()
+{
+ return s;
+}
+
+zmq::fd_t zmq::tcp_listener_t::accept ()
+{
+ zmq_assert (s != retired_fd);
+
+ // Accept one incoming connection.
+ fd_t sock = ::accept (s, NULL, NULL);
+
+#if (defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD || \
+ defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_OSX || \
+ defined ZMQ_HAVE_OPENVMS || defined ZMQ_HAVE_NETBSD || \
+ defined ZMQ_HAVE_CYGWIN)
+ if (sock == -1 &&
+ (errno == EAGAIN || errno == EWOULDBLOCK ||
+ errno == EINTR || errno == ECONNABORTED))
+ return retired_fd;
+#elif (defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_AIX)
+ if (sock == -1 &&
+ (errno == EWOULDBLOCK || errno == EINTR ||
+ errno == ECONNABORTED || errno == EPROTO))
+ return retired_fd;
+#elif defined ZMQ_HAVE_HPUX
+ if (sock == -1 &&
+ (errno == EAGAIN || errno == EWOULDBLOCK ||
+ errno == EINTR || errno == ECONNABORTED || errno == ENOBUFS))
+ return retired_fd;
+#elif defined ZMQ_HAVE_QNXNTO
+ if (sock == -1 &&
+ (errno == EWOULDBLOCK || errno == EINTR || errno == ECONNABORTED))
+ return retired_fd;
+#endif
+
+ errno_assert (sock != -1);
+
+ // Set to non-blocking mode.
+#ifdef ZMQ_HAVE_OPENVMS
+ int flags = 1;
+ int rc = ioctl (sock, FIONBIO, &flags);
+ errno_assert (rc != -1);
+#else
+ int flags = fcntl (s, F_GETFL, 0);
+ if (flags == -1)
+ flags = 0;
+ int rc = fcntl (sock, F_SETFL, flags | O_NONBLOCK);
+ errno_assert (rc != -1);
+#endif
+
+ struct sockaddr *sa = (struct sockaddr*) &addr;
+ if (AF_UNIX != sa->sa_family) {
+
+ // Disable Nagle's algorithm.
+ int flag = 1;
+ rc = setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, (char*) &flag,
+ sizeof (int));
+ errno_assert (rc == 0);
+
+#ifdef ZMQ_HAVE_OPENVMS
+ // Disable delayed acknowledgements.
+ flag = 1;
+ rc = setsockopt (sock, IPPROTO_TCP, TCP_NODELACK, (char*) &flag,
+ sizeof (int));
+ errno_assert (rc != SOCKET_ERROR);
+#endif
+ }
+
+ return sock;
+}
+
+#endif
diff --git a/src/0mq/tcp_listener.hpp b/src/0mq/tcp_listener.hpp
new file mode 100644
index 0000000..27e3092
--- /dev/null
+++ b/src/0mq/tcp_listener.hpp
@@ -0,0 +1,73 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_TCP_LISTENER_HPP_INCLUDED__
+#define __ZMQ_TCP_LISTENER_HPP_INCLUDED__
+
+#include "fd.hpp"
+#include "ip.hpp"
+
+namespace zmq
+{
+
+ // The class encapsulating simple TCP listening socket.
+
+ class tcp_listener_t
+ {
+ public:
+
+ tcp_listener_t ();
+ ~tcp_listener_t ();
+
+ // Start listening on the interface.
+ int set_address (const char *protocol_, const char *addr_,
+ int backlog_);
+
+ // Close the listening socket.
+ int close ();
+
+ // Get the file descriptor to poll on to get notified about
+ // newly created connections.
+ fd_t get_fd ();
+
+ // Accept the new connection. Returns the file descriptor of the
+ // newly created connection. The function may return retired_fd
+ // if the connection was dropped while waiting in the listen backlog.
+ fd_t accept ();
+
+ private:
+
+ // Address to listen on.
+ sockaddr_storage addr;
+ socklen_t addr_len;
+
+ // True, if the undelying file for UNIX domain socket exists.
+ bool has_file;
+
+ // Underlying socket.
+ fd_t s;
+
+ tcp_listener_t (const tcp_listener_t&);
+ const tcp_listener_t &operator = (const tcp_listener_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/tcp_socket.cpp b/src/0mq/tcp_socket.cpp
new file mode 100644
index 0000000..775a7a6
--- /dev/null
+++ b/src/0mq/tcp_socket.cpp
@@ -0,0 +1,239 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tcp_socket.hpp"
+#include "platform.hpp"
+#include "err.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+
+zmq::tcp_socket_t::tcp_socket_t () :
+ s (retired_fd)
+{
+}
+
+zmq::tcp_socket_t::~tcp_socket_t ()
+{
+ if (s != retired_fd)
+ close ();
+}
+
+int zmq::tcp_socket_t::open (fd_t fd_, uint64_t sndbuf_, uint64_t rcvbuf_)
+{
+ zmq_assert (s == retired_fd);
+ s = fd_;
+
+ if (sndbuf_) {
+ int sz = (int) sndbuf_;
+ int rc = setsockopt (s, SOL_SOCKET, SO_SNDBUF,
+ (char*) &sz, sizeof (int));
+ errno_assert (rc == 0);
+ }
+
+ if (rcvbuf_) {
+ int sz = (int) rcvbuf_;
+ int rc = setsockopt (s, SOL_SOCKET, SO_RCVBUF,
+ (char*) &sz, sizeof (int));
+ errno_assert (rc == 0);
+ }
+
+ return 0;
+}
+
+int zmq::tcp_socket_t::close ()
+{
+ zmq_assert (s != retired_fd);
+ int rc = closesocket (s);
+ wsa_assert (rc != SOCKET_ERROR);
+ s = retired_fd;
+ return 0;
+}
+
+zmq::fd_t zmq::tcp_socket_t::get_fd ()
+{
+ return s;
+}
+
+int zmq::tcp_socket_t::write (const void *data, int size)
+{
+ int nbytes = send (s, (char*) data, size, 0);
+
+ // If not a single byte can be written to the socket in non-blocking mode
+ // we'll get an error (this may happen during the speculative write).
+ if (nbytes == SOCKET_ERROR && WSAGetLastError () == WSAEWOULDBLOCK)
+ return 0;
+
+ // Signalise peer failure.
+ if (nbytes == -1 && (
+ WSAGetLastError () == WSAENETDOWN ||
+ WSAGetLastError () == WSAENETRESET ||
+ WSAGetLastError () == WSAEHOSTUNREACH ||
+ WSAGetLastError () == WSAECONNABORTED ||
+ WSAGetLastError () == WSAETIMEDOUT ||
+ WSAGetLastError () == WSAECONNRESET))
+ return -1;
+
+ wsa_assert (nbytes != SOCKET_ERROR);
+
+ return (size_t) nbytes;
+}
+
+int zmq::tcp_socket_t::read (void *data, int size)
+{
+ int nbytes = recv (s, (char*) data, size, 0);
+
+ // If not a single byte can be read from the socket in non-blocking mode
+ // we'll get an error (this may happen during the speculative read).
+ if (nbytes == SOCKET_ERROR && WSAGetLastError () == WSAEWOULDBLOCK)
+ return 0;
+
+ // Connection failure.
+ if (nbytes == -1 && (
+ WSAGetLastError () == WSAENETDOWN ||
+ WSAGetLastError () == WSAENETRESET ||
+ WSAGetLastError () == WSAECONNABORTED ||
+ WSAGetLastError () == WSAETIMEDOUT ||
+ WSAGetLastError () == WSAECONNRESET ||
+ WSAGetLastError () == WSAECONNREFUSED ||
+ WSAGetLastError () == WSAENOTCONN))
+ return -1;
+
+ wsa_assert (nbytes != SOCKET_ERROR);
+
+ // Orderly shutdown by the other peer.
+ if (nbytes == 0)
+ return -1;
+
+ return (size_t) nbytes;
+}
+
+#else
+
+#include <unistd.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <netinet/tcp.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#include <fcntl.h>
+
+zmq::tcp_socket_t::tcp_socket_t () :
+ s (retired_fd)
+{
+}
+
+zmq::tcp_socket_t::~tcp_socket_t ()
+{
+ if (s != retired_fd)
+ close ();
+}
+
+int zmq::tcp_socket_t::open (fd_t fd_, uint64_t sndbuf_, uint64_t rcvbuf_)
+{
+ assert (s == retired_fd);
+ s = fd_;
+
+ if (sndbuf_) {
+ int sz = (int) sndbuf_;
+ int rc = setsockopt (s, SOL_SOCKET, SO_SNDBUF, &sz, sizeof (int));
+ errno_assert (rc == 0);
+ }
+
+ if (rcvbuf_) {
+ int sz = (int) rcvbuf_;
+ int rc = setsockopt (s, SOL_SOCKET, SO_RCVBUF, &sz, sizeof (int));
+ errno_assert (rc == 0);
+ }
+
+#if defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_FREEBSD
+ int set = 1;
+ int rc = setsockopt (s, SOL_SOCKET, SO_NOSIGPIPE, &set, sizeof (int));
+ errno_assert (rc == 0);
+#endif
+ return 0;
+}
+
+int zmq::tcp_socket_t::close ()
+{
+ zmq_assert (s != retired_fd);
+ int rc = ::close (s);
+ if (rc != 0)
+ return -1;
+ s = retired_fd;
+ return 0;
+}
+
+zmq::fd_t zmq::tcp_socket_t::get_fd ()
+{
+ return s;
+}
+
+int zmq::tcp_socket_t::write (const void *data, int size)
+{
+ ssize_t nbytes = send (s, data, size, 0);
+
+ // Several errors are OK. When speculative write is being done we may not
+ // be able to write a single byte to the socket. Also, SIGSTOP issued
+ // by a debugging tool can result in EINTR error.
+ if (nbytes == -1 && (errno == EAGAIN || errno == EWOULDBLOCK ||
+ errno == EINTR))
+ return 0;
+
+ // Signalise peer failure.
+ if (nbytes == -1 && (errno == ECONNRESET || errno == EPIPE))
+ return -1;
+
+ errno_assert (nbytes != -1);
+ return (size_t) nbytes;
+}
+
+int zmq::tcp_socket_t::read (void *data, int size)
+{
+ ssize_t nbytes = recv (s, data, size, 0);
+
+ // Several errors are OK. When speculative read is being done we may not
+ // be able to read a single byte to the socket. Also, SIGSTOP issued
+ // by a debugging tool can result in EINTR error.
+ if (nbytes == -1
+ && (errno == EAGAIN
+ || errno == EWOULDBLOCK
+ || errno == EINTR))
+ return 0;
+
+ // Signal peer failure.
+ if (nbytes == -1
+ && (errno == ECONNRESET
+ || errno == ECONNREFUSED
+ || errno == ETIMEDOUT
+ || errno == EHOSTUNREACH
+ || errno == ENOTCONN))
+ return -1;
+
+ errno_assert (nbytes != -1);
+
+ // Orderly shutdown by the other peer.
+ if (nbytes == 0)
+ return -1;
+
+ return (size_t) nbytes;
+}
+
+#endif
+
diff --git a/src/0mq/tcp_socket.hpp b/src/0mq/tcp_socket.hpp
new file mode 100644
index 0000000..3cb5739
--- /dev/null
+++ b/src/0mq/tcp_socket.hpp
@@ -0,0 +1,72 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_TCP_SOCKET_HPP_INCLUDED__
+#define __ZMQ_TCP_SOCKET_HPP_INCLUDED__
+
+#include "fd.hpp"
+#include "stdint.hpp"
+
+namespace zmq
+{
+
+ // The class encapsulating simple TCP read/write socket.
+
+ class tcp_socket_t
+ {
+ public:
+
+ tcp_socket_t ();
+ ~tcp_socket_t ();
+
+ // Associates a socket with a native socket descriptor.
+ int open (fd_t fd_, uint64_t sndbuf_, uint64_t rcvbuf_);
+
+ // Closes the underlying socket.
+ int close ();
+
+ // Returns the underlying socket. Returns retired_fd when the socket
+ // is in the closed state.
+ fd_t get_fd ();
+
+ // Writes data to the socket. Returns the number of bytes actually
+ // written (even zero is to be considered to be a success). In case
+ // of error or orderly shutdown by the other peer -1 is returned.
+ int write (const void *data, int size);
+
+ // Reads data from the socket (up to 'size' bytes). Returns the number
+ // of bytes actually read (even zero is to be considered to be
+ // a success). In case of error or orderly shutdown by the other
+ // peer -1 is returned.
+ int read (void *data, int size);
+
+ private:
+
+ // Underlying socket.
+ fd_t s;
+
+ // Disable copy construction of tcp_socket.
+ tcp_socket_t (const tcp_socket_t&);
+ const tcp_socket_t &operator = (const tcp_socket_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/thread.cpp b/src/0mq/thread.cpp
new file mode 100644
index 0000000..8e33eff
--- /dev/null
+++ b/src/0mq/thread.cpp
@@ -0,0 +1,99 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "thread.hpp"
+#include "err.hpp"
+#include "platform.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+
+extern "C"
+{
+ static unsigned int __stdcall thread_routine (void *arg_)
+ {
+ zmq::thread_t *self = (zmq::thread_t*) arg_;
+ self->tfn (self->arg);
+ return 0;
+ }
+}
+
+void zmq::thread_t::start (thread_fn *tfn_, void *arg_)
+{
+ tfn = tfn_;
+ arg =arg_;
+ descriptor = (HANDLE) _beginthreadex (NULL, 0,
+ &::thread_routine, this, 0 , NULL);
+ win_assert (descriptor != NULL);
+}
+
+void zmq::thread_t::stop ()
+{
+ DWORD rc = WaitForSingleObject (descriptor, INFINITE);
+ win_assert (rc != WAIT_FAILED);
+ BOOL rc2 = CloseHandle (descriptor);
+ win_assert (rc2 != 0);
+}
+
+#else
+
+#include <signal.h>
+
+extern "C"
+{
+ static void *thread_routine (void *arg_)
+ {
+#if !defined ZMQ_HAVE_OPENVMS
+ // Following code will guarantee more predictable latecnies as it'll
+ // disallow any signal handling in the I/O thread.
+ sigset_t signal_set;
+ int rc = sigfillset (&signal_set);
+ errno_assert (rc == 0);
+# if !defined ZMQ_HAVE_ANDROID
+ rc = pthread_sigmask (SIG_BLOCK, &signal_set, NULL);
+ posix_assert (rc);
+# endif
+#endif
+
+ zmq::thread_t *self = (zmq::thread_t*) arg_;
+ self->tfn (self->arg);
+ return NULL;
+ }
+}
+
+void zmq::thread_t::start (thread_fn *tfn_, void *arg_)
+{
+ tfn = tfn_;
+ arg =arg_;
+ int rc = pthread_create (&descriptor, NULL, thread_routine, this);
+ posix_assert (rc);
+}
+
+void zmq::thread_t::stop ()
+{
+ int rc = pthread_join (descriptor, NULL);
+ posix_assert (rc);
+}
+
+#endif
+
+
+
+
+
diff --git a/src/0mq/thread.hpp b/src/0mq/thread.hpp
new file mode 100644
index 0000000..f3f5f8d
--- /dev/null
+++ b/src/0mq/thread.hpp
@@ -0,0 +1,78 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_THREAD_HPP_INCLUDED__
+#define __ZMQ_THREAD_HPP_INCLUDED__
+
+#include "platform.hpp"
+
+#ifdef ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#else
+#include <pthread.h>
+#endif
+
+namespace zmq
+{
+
+ typedef void (thread_fn) (void*);
+
+ // Class encapsulating OS thread. Thread initiation/termination is done
+ // using special functions rather than in constructor/destructor so that
+ // thread isn't created during object construction by accident, causing
+ // newly created thread to access half-initialised object. Same applies
+ // to the destruction process: Thread should be terminated before object
+ // destruction begins, otherwise it can access half-destructed object.
+
+ class thread_t
+ {
+ public:
+
+ inline thread_t ()
+ {
+ }
+
+ // Creates OS thread. 'tfn' is main thread function. It'll be passed
+ // 'arg' as an argument.
+ void start (thread_fn *tfn_, void *arg_);
+
+ // Waits for thread termination.
+ void stop ();
+
+ // These are internal members. They should be private, however then
+ // they would not be accessible from the main C routine of the thread.
+ thread_fn *tfn;
+ void *arg;
+
+ private:
+
+#ifdef ZMQ_HAVE_WINDOWS
+ HANDLE descriptor;
+#else
+ pthread_t descriptor;
+#endif
+
+ thread_t (const thread_t&);
+ const thread_t &operator = (const thread_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/transient_session.cpp b/src/0mq/transient_session.cpp
new file mode 100644
index 0000000..a08f541
--- /dev/null
+++ b/src/0mq/transient_session.cpp
@@ -0,0 +1,41 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "transient_session.hpp"
+
+zmq::transient_session_t::transient_session_t (class io_thread_t *io_thread_,
+ class socket_base_t *socket_, const options_t &options_) :
+ session_t (io_thread_, socket_, options_)
+{
+}
+
+zmq::transient_session_t::~transient_session_t ()
+{
+}
+
+void zmq::transient_session_t::attached (const blob_t &peer_identity_)
+{
+}
+
+void zmq::transient_session_t::detached ()
+{
+ // There's no way to reestablish a transient session. Tear it down.
+ terminate ();
+}
diff --git a/src/0mq/transient_session.hpp b/src/0mq/transient_session.hpp
new file mode 100644
index 0000000..03f058d
--- /dev/null
+++ b/src/0mq/transient_session.hpp
@@ -0,0 +1,52 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_TRANSIENT_SESSION_HPP_INCLUDED__
+#define __ZMQ_TRANSIENT_SESSION_HPP_INCLUDED__
+
+#include "session.hpp"
+
+namespace zmq
+{
+
+ // Transient session is created by the listener when the connected peer
+ // stays anonymous. Transient session is destroyed on disconnect.
+
+ class transient_session_t : public session_t
+ {
+ public:
+
+ transient_session_t (class io_thread_t *io_thread_,
+ class socket_base_t *socket_, const options_t &options_);
+ ~transient_session_t ();
+
+ private:
+
+ // Handlers for events from session base class.
+ void attached (const blob_t &peer_identity_);
+ void detached ();
+
+ transient_session_t (const transient_session_t&);
+ const transient_session_t &operator = (const transient_session_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/trie.cpp b/src/0mq/trie.cpp
new file mode 100644
index 0000000..4198ff3
--- /dev/null
+++ b/src/0mq/trie.cpp
@@ -0,0 +1,181 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdlib.h>
+
+#include <new>
+#include <algorithm>
+
+#include "platform.hpp"
+#if defined ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#endif
+
+#include "err.hpp"
+#include "trie.hpp"
+
+zmq::trie_t::trie_t () :
+ refcnt (0),
+ min (0),
+ count (0)
+{
+}
+
+zmq::trie_t::~trie_t ()
+{
+ if (count == 1)
+ delete next.node;
+ else if (count > 1) {
+ for (unsigned short i = 0; i != count; ++i)
+ if (next.table [i])
+ delete next.table [i];
+ free (next.table);
+ }
+}
+
+void zmq::trie_t::add (unsigned char *prefix_, size_t size_)
+{
+ // We are at the node corresponding to the prefix. We are done.
+ if (!size_) {
+ ++refcnt;
+ return;
+ }
+
+ unsigned char c = *prefix_;
+ if (c < min || c >= min + count) {
+
+ // The character is out of range of currently handled
+ // charcters. We have to extend the table.
+ if (!count) {
+ min = c;
+ count = 1;
+ next.node = NULL;
+ }
+ else if (count == 1) {
+ unsigned char oldc = min;
+ trie_t *oldp = next.node;
+ count = (min < c ? c - min : min - c) + 1;
+ next.table = (trie_t**)
+ malloc (sizeof (trie_t*) * count);
+ alloc_assert (next.table);
+ for (unsigned short i = 0; i != count; ++i)
+ next.table [i] = 0;
+ min = std::min (min, c);
+ next.table [oldc - min] = oldp;
+ }
+ else if (min < c) {
+
+ // The new character is above the current character range.
+ unsigned short old_count = count;
+ count = c - min + 1;
+ next.table = (trie_t**) realloc ((void*) next.table,
+ sizeof (trie_t*) * count);
+ zmq_assert (next.table);
+ for (unsigned short i = old_count; i != count; i++)
+ next.table [i] = NULL;
+ }
+ else {
+
+ // The new character is below the current character range.
+ unsigned short old_count = count;
+ count = (min + old_count) - c;
+ next.table = (trie_t**) realloc ((void*) next.table,
+ sizeof (trie_t*) * count);
+ zmq_assert (next.table);
+ memmove (next.table + min - c, next.table,
+ old_count * sizeof (trie_t*));
+ for (unsigned short i = 0; i != min - c; i++)
+ next.table [i] = NULL;
+ min = c;
+ }
+ }
+
+ // If next node does not exist, create one.
+ if (count == 1) {
+ if (!next.node) {
+ next.node = new (std::nothrow) trie_t;
+ alloc_assert (next.node);
+ }
+ next.node->add (prefix_ + 1, size_ - 1);
+ }
+ else {
+ if (!next.table [c - min]) {
+ next.table [c - min] = new (std::nothrow) trie_t;
+ alloc_assert (next.table [c - min]);
+ }
+ next.table [c - min]->add (prefix_ + 1, size_ - 1);
+ }
+}
+
+bool zmq::trie_t::rm (unsigned char *prefix_, size_t size_)
+{
+ if (!size_) {
+ if (!refcnt)
+ return false;
+ refcnt--;
+ return true;
+ }
+
+ unsigned char c = *prefix_;
+ if (!count || c < min || c >= min + count)
+ return false;
+
+ trie_t *next_node =
+ count == 1 ? next.node : next.table [c - min];
+
+ if (!next_node)
+ return false;
+
+ return next_node->rm (prefix_ + 1, size_ - 1);
+}
+
+bool zmq::trie_t::check (unsigned char *data_, size_t size_)
+{
+ // This function is on critical path. It deliberately doesn't use
+ // recursion to get a bit better performance.
+ trie_t *current = this;
+ while (true) {
+
+ // We've found a corresponding subscription!
+ if (current->refcnt)
+ return true;
+
+ // We've checked all the data and haven't found matching subscription.
+ if (!size_)
+ return false;
+
+ // If there's no corresponding slot for the first character
+ // of the prefix, the message does not match.
+ unsigned char c = *data_;
+ if (c < current->min || c >= current->min + current->count)
+ return false;
+
+ // Move to the next character.
+ if (current->count == 1)
+ current = current->next.node;
+ else {
+ current = current->next.table [c - current->min];
+ if (!current)
+ return false;
+ }
+ data_++;
+ size_--;
+ }
+}
diff --git a/src/0mq/trie.hpp b/src/0mq/trie.hpp
new file mode 100644
index 0000000..dbf1cb1
--- /dev/null
+++ b/src/0mq/trie.hpp
@@ -0,0 +1,59 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_TRIE_HPP_INCLUDED__
+#define __ZMQ_TRIE_HPP_INCLUDED__
+
+#include <stddef.h>
+
+#include "stdint.hpp"
+
+namespace zmq
+{
+
+ class trie_t
+ {
+ public:
+
+ trie_t ();
+ ~trie_t ();
+
+ void add (unsigned char *prefix_, size_t size_);
+ bool rm (unsigned char *prefix_, size_t size_);
+ bool check (unsigned char *data_, size_t size_);
+
+ private:
+
+ uint32_t refcnt;
+ unsigned char min;
+ unsigned short count;
+ union {
+ class trie_t *node;
+ class trie_t **table;
+ } next;
+
+ trie_t (const trie_t&);
+ const trie_t &operator = (const trie_t&);
+ };
+
+}
+
+#endif
+
diff --git a/src/0mq/uuid.cpp b/src/0mq/uuid.cpp
new file mode 100644
index 0000000..35d854f
--- /dev/null
+++ b/src/0mq/uuid.cpp
@@ -0,0 +1,241 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "uuid.hpp"
+#include "err.hpp"
+
+#if defined ZMQ_HAVE_WINDOWS
+
+zmq::uuid_t::uuid_t ()
+{
+ RPC_STATUS ret = UuidCreate (&uuid);
+ zmq_assert (ret == RPC_S_OK);
+ ret = UuidToString (&uuid, &string_buf);
+ zmq_assert (ret == RPC_S_OK);
+
+ create_blob ();
+}
+
+zmq::uuid_t::~uuid_t ()
+{
+ if (string_buf)
+ RpcStringFree (&string_buf);
+}
+
+const char *zmq::uuid_t::to_string ()
+{
+ return (char*) string_buf;
+}
+
+#elif defined ZMQ_HAVE_FREEBSD || defined ZMQ_HAVE_NETBSD || (defined ZMQ_HAVE_HPUX && defined HAVE_LIBDCEKT)
+
+#include <stdlib.h>
+#ifdef ZMQ_HAVE_HPUX
+# include <dce/uuid.h>
+#else
+# include <uuid.h>
+#endif
+
+zmq::uuid_t::uuid_t ()
+{
+#ifdef ZMQ_HAVE_HPUX
+ unsigned32 status;
+#else
+ uint32_t status;
+#endif
+ uuid_create (&uuid, &status);
+ zmq_assert (status == uuid_s_ok);
+ uuid_to_string (&uuid, &string_buf, &status);
+ zmq_assert (status == uuid_s_ok);
+
+ create_blob ();
+}
+
+zmq::uuid_t::~uuid_t ()
+{
+ free (string_buf);
+}
+
+const char *zmq::uuid_t::to_string ()
+{
+ return (char*) string_buf;
+}
+
+#elif defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_SOLARIS ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_CYGWIN
+
+#include <uuid/uuid.h>
+
+zmq::uuid_t::uuid_t ()
+{
+ uuid_generate (uuid);
+ uuid_unparse (uuid, string_buf);
+
+ create_blob ();
+}
+
+zmq::uuid_t::~uuid_t ()
+{
+}
+
+const char *zmq::uuid_t::to_string ()
+{
+ return string_buf;
+}
+
+#elif defined ZMQ_HAVE_OPENVMS
+
+#include <starlet.h>
+
+#define uuid_generate(x) sys$create_uid(&(x))
+
+#define uuid_unparse(x, y) \
+ sprintf (y, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", \
+ x.data0, x.data1, x.data2, \
+ x.data3 [0], x.data3 [1], \
+ x.data3 [2], x.data3 [3], \
+ x.data3 [4], x.data3 [5], \
+ x.data3 [6], x.data3 [7]);
+
+zmq::uuid_t::uuid_t ()
+{
+ uuid_generate (uuid);
+ uuid_unparse (uuid, string_buf);
+}
+
+zmq::uuid_t::~uuid_t ()
+{
+}
+
+const char *zmq::uuid_t::to_string ()
+{
+ return string_buf;
+}
+
+#else
+
+#include <stdio.h>
+#include <string.h>
+#include <openssl/rand.h>
+
+zmq::uuid_t::uuid_t ()
+{
+ unsigned char rand_buf [16];
+ int ret = RAND_bytes (rand_buf, sizeof rand_buf);
+ zmq_assert (ret == 1);
+
+ // Read in UUID fields.
+ memcpy (&time_low, rand_buf, sizeof time_low);
+ memcpy (&time_mid, rand_buf + 4, sizeof time_mid);
+ memcpy (&time_hi_and_version, rand_buf + 6, sizeof time_hi_and_version);
+ memcpy (&clock_seq_hi_and_reserved, rand_buf + 8,
+ sizeof clock_seq_hi_and_reserved);
+ memcpy (&clock_seq_low, rand_buf + 9, sizeof clock_seq_low);
+ memcpy (&node [0], rand_buf + 10, sizeof node);
+
+ // Store UUID version number.
+ time_hi_and_version = (time_hi_and_version & 0x0fff) | 4 << 12;
+
+ // Store UUID type.
+ clock_seq_hi_and_reserved = (clock_seq_hi_and_reserved & 0x3f) | 0x80;
+
+ snprintf (string_buf, sizeof string_buf,
+ "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+ time_low,
+ time_mid,
+ time_hi_and_version,
+ clock_seq_hi_and_reserved,
+ clock_seq_low,
+ node [0], node [1], node [2], node [3], node [4], node [5]);
+
+ create_blob ();
+}
+
+zmq::uuid_t::~uuid_t ()
+{
+}
+
+const char *zmq::uuid_t::to_string ()
+{
+ return string_buf;
+}
+
+#endif
+
+const unsigned char *zmq::uuid_t::to_blob ()
+{
+ return blob_buf;
+}
+
+unsigned char zmq::uuid_t::convert_byte (const char *hexa_)
+{
+ unsigned char byte;
+
+ if (*hexa_ >= '0' && *hexa_ <= '9')
+ byte = *hexa_ - '0';
+ else if (*hexa_ >= 'A' && *hexa_ <= 'F')
+ byte = *hexa_ - 'A' + 10;
+ else if (*hexa_ >= 'a' && *hexa_ <= 'f')
+ byte = *hexa_ - 'a' + 10;
+ else {
+ zmq_assert (false);
+ byte = 0;
+ }
+
+ byte *= 16;
+
+ hexa_++;
+ if (*hexa_ >= '0' && *hexa_ <= '9')
+ byte += *hexa_ - '0';
+ else if (*hexa_ >= 'A' && *hexa_ <= 'F')
+ byte += *hexa_ - 'A' + 10;
+ else if (*hexa_ >= 'a' && *hexa_ <= 'f')
+ byte += *hexa_ - 'a' + 10;
+ else
+ zmq_assert (false);
+
+ return byte;
+}
+
+void zmq::uuid_t::create_blob ()
+{
+ const char *buf = (const char*) string_buf;
+
+ blob_buf [0] = convert_byte (buf + 0);
+ blob_buf [1] = convert_byte (buf + 2);
+ blob_buf [2] = convert_byte (buf + 4);
+ blob_buf [3] = convert_byte (buf + 6);
+
+ blob_buf [4] = convert_byte (buf + 9);
+ blob_buf [5] = convert_byte (buf + 11);
+
+ blob_buf [6] = convert_byte (buf + 14);
+ blob_buf [7] = convert_byte (buf + 16);
+
+ blob_buf [8] = convert_byte (buf + 19);
+ blob_buf [9] = convert_byte (buf + 21);
+
+ blob_buf [10] = convert_byte (buf + 24);
+ blob_buf [11] = convert_byte (buf + 26);
+ blob_buf [12] = convert_byte (buf + 28);
+ blob_buf [13] = convert_byte (buf + 30);
+ blob_buf [14] = convert_byte (buf + 32);
+ blob_buf [15] = convert_byte (buf + 34);
+}
diff --git a/src/0mq/uuid.hpp b/src/0mq/uuid.hpp
new file mode 100644
index 0000000..525dbcb
--- /dev/null
+++ b/src/0mq/uuid.hpp
@@ -0,0 +1,116 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_UUID_HPP_INCLUDED__
+#define __ZMQ_UUID_HPP_INCLUDED__
+
+#include "platform.hpp"
+#include "stdint.hpp"
+
+#if defined ZMQ_HAVE_FREEBSD || defined ZMQ_HAVE_NETBSD
+#include <uuid.h>
+#elif defined ZMQ_HAVE_HPUX && defined HAVE_LIBDCEKT
+#include <dce/uuid.h>
+#elif defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_SOLARIS ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_CYGWIN
+#include <uuid/uuid.h>
+#elif defined ZMQ_HAVE_WINDOWS
+#include "windows.hpp"
+#include <rpc.h>
+#elif defined ZMQ_HAVE_OPENVMS
+typedef struct
+{
+ unsigned long data0;
+ unsigned short data1;
+ unsigned short data2;
+ unsigned char data3 [8];
+} uuid_t;
+#endif
+
+namespace zmq
+{
+
+ // This class provides RFC 4122 (a Universally Unique IDentifier)
+ // implementation.
+
+ class uuid_t
+ {
+ public:
+
+ uuid_t ();
+ ~uuid_t ();
+
+ // The length of textual representation of UUID.
+ enum { uuid_string_len = 36 };
+
+ // Returns a pointer to buffer containing the textual
+ // representation of the UUID. The callee is reponsible to
+ // free the allocated memory.
+ const char *to_string ();
+
+ // The length of binary representation of UUID.
+ enum { uuid_blob_len = 16 };
+
+ const unsigned char *to_blob ();
+
+ private:
+
+ // Converts one byte from hexa representation to binary.
+ unsigned char convert_byte (const char *hexa_);
+
+ // Converts string representation of UUID into standardised BLOB.
+ // The function is endianness agnostic.
+ void create_blob ();
+
+#if defined ZMQ_HAVE_WINDOWS
+#ifdef ZMQ_HAVE_MINGW32
+ typedef unsigned char* RPC_CSTR;
+#endif
+ ::UUID uuid;
+ RPC_CSTR string_buf;
+#elif defined ZMQ_HAVE_FREEBSD || defined ZMQ_HAVE_NETBSD
+ ::uuid_t uuid;
+ char *string_buf;
+#elif defined ZMQ_HAVE_HPUX && defined HAVE_LIBDCEKT
+ ::uuid_t uuid;
+ unsigned_char_t *string_buf;
+#elif defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_SOLARIS ||\
+ defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_CYGWIN ||\
+ defined ZMQ_HAVE_OPENVMS
+ ::uuid_t uuid;
+ char string_buf [uuid_string_len + 1];
+#else
+ // RFC 4122 UUID's fields
+ uint32_t time_low;
+ uint16_t time_mid;
+ uint16_t time_hi_and_version;
+ uint8_t clock_seq_hi_and_reserved;
+ uint8_t clock_seq_low;
+ uint8_t node [6];
+
+ char string_buf [uuid_string_len + 1];
+#endif
+
+ unsigned char blob_buf [uuid_blob_len];
+ };
+
+}
+
+#endif
diff --git a/src/0mq/windows.hpp b/src/0mq/windows.hpp
new file mode 100644
index 0000000..a821339
--- /dev/null
+++ b/src/0mq/windows.hpp
@@ -0,0 +1,177 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_WINDOWS_HPP_INCLUDED__
+#define __ZMQ_WINDOWS_HPP_INCLUDED__
+
+// The purpose of this header file is to turn on only the items actually needed
+// on the windows platform.
+
+// Disable deprecation warning.
+#define _CRT_SECURE_NO_WARNINGS
+
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOGDICAPMASKS
+#define NOGDICAPMASKS // CC_*, LC_*, PC_*, CP_*, TC_*, RC_
+#endif
+#ifndef NOVIRTUALKEYCODES
+#define NOVIRTUALKEYCODES // VK_*
+#endif
+#ifndef NOWINMESSAGES
+#define NOWINMESSAGES // WM_*, EM_*, LB_*, CB_*
+#endif
+#ifndef NOWINSTYLES
+#define NOWINSTYLES // WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_*
+#endif
+#ifndef NOSYSMETRICS
+#define NOSYSMETRICS // SM_*
+#endif
+#ifndef NOMENUS
+#define NOMENUS // MF_*
+#endif
+#ifndef NOICONS
+#define NOICONS // IDI_*
+#endif
+#ifndef NOKEYSTATES
+#define NOKEYSTATES // MK_*
+#endif
+#ifndef NOSYSCOMMANDS
+#define NOSYSCOMMANDS // SC_*
+#endif
+#ifndef NORASTEROPS
+#define NORASTEROPS // Binary and Tertiary raster ops
+#endif
+#ifndef NOSHOWWINDOW
+#define NOSHOWWINDOW // SW_*
+#endif
+#ifndef OEMRESOURCE
+#define OEMRESOURCE // OEM Resource values
+#endif
+#ifndef NOATOM
+#define NOATOM // Atom Manager routines
+#endif
+#ifndef NOCLIPBOARD
+#define NOCLIPBOARD // Clipboard routines
+#endif
+#ifndef NOCOLOR
+#define NOCOLOR // Screen colors
+#endif
+#ifndef NOCTLMGR
+#define NOCTLMGR // Control and Dialog routines
+#endif
+#ifndef NODRAWTEXT
+#define NODRAWTEXT // DrawText() and DT_*
+#endif
+#ifndef NOGDI
+#define NOGDI // All GDI defines and routines
+#endif
+#ifndef NOKERNEL
+#define NOKERNEL // All KERNEL defines and routines
+#endif
+#ifndef NOUSER
+#define NOUSER // All USER defines and routines
+#endif
+#ifndef NONLS
+#define NONLS // All NLS defines and routines
+#endif
+#ifndef NOMB
+#define NOMB // MB_* and MessageBox()
+#endif
+#ifndef NOMEMMGR
+#define NOMEMMGR // GMEM_*, LMEM_*, GHND, LHND, associated routines
+#endif
+#ifndef NOMETAFILE
+#define NOMETAFILE // typedef METAFILEPICT
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX // Macros min(a,b) and max(a,b)
+#endif
+#ifndef NOMSG
+#define NOMSG // typedef MSG and associated routines
+#endif
+#ifndef NOOPENFILE
+#define NOOPENFILE // OpenFile(), OemToAnsi, AnsiToOem, and OF_*
+#endif
+#ifndef NOSCROLL
+#define NOSCROLL // SB_* and scrolling routines
+#endif
+#ifndef NOSERVICE
+#define NOSERVICE // All Service Controller routines, SERVICE_ equates, etc.
+#endif
+#ifndef NOSOUND
+#define NOSOUND // Sound driver routines
+#endif
+#ifndef NOTEXTMETRIC
+#define NOTEXTMETRIC // typedef TEXTMETRIC and associated routines
+#endif
+#ifndef NOWH
+#define NOWH // SetWindowsHook and WH_*
+#endif
+#ifndef NOWINOFFSETS
+#define NOWINOFFSETS // GWL_*, GCL_*, associated routines
+#endif
+#ifndef NOCOMM
+#define NOCOMM // COMM driver routines
+#endif
+#ifndef NOKANJI
+#define NOKANJI // Kanji support stuff.
+#endif
+#ifndef NOHELP
+#define NOHELP // Help engine interface.
+#endif
+#ifndef NOPROFILER
+#define NOPROFILER // Profiler interface.
+#endif
+#ifndef NODEFERWINDOWPOS
+#define NODEFERWINDOWPOS // DeferWindowPos routines
+#endif
+#ifndef NOMCX
+#define NOMCX // Modem Configuration ExtensionsA
+#endif
+
+// Set target version to Windows Server 2003, Windows XP/SP1 or higher.
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT 0x0501
+#endif
+
+#include <windows.h>
+
+#ifdef __MINGW32__
+// Require Windows XP or higher with MinGW for getaddrinfo().
+#if(_WIN32_WINNT >= 0x0501)
+#else
+#undef _WIN32_WINNT
+#define _WIN32_WINNT 0x0501
+#endif /* _WIN32_WINNT >= 0x0501 */
+#endif /* __MINGW32__ */
+
+#include <winsock2.h>
+#include <mswsock.h>
+#include <ws2tcpip.h>
+#include <ipexport.h>
+#include <process.h>
+
+// On mingw environment AI_NUMERICSERV is not defined, needed in ip.cpp.
+#ifndef AI_NUMERICSERV
+#define AI_NUMERICSERV 0x0400
+#endif
+#endif
diff --git a/src/0mq/wire.hpp b/src/0mq/wire.hpp
new file mode 100644
index 0000000..bc9dfe5
--- /dev/null
+++ b/src/0mq/wire.hpp
@@ -0,0 +1,99 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_WIRE_HPP_INCLUDED__
+#define __ZMQ_WIRE_HPP_INCLUDED__
+
+#include "stdint.hpp"
+
+namespace zmq
+{
+
+ // Helper functions to convert different integer types to/from network
+ // byte order.
+
+ inline void put_uint8 (unsigned char *buffer_, uint8_t value)
+ {
+ *buffer_ = value;
+ }
+
+ inline uint8_t get_uint8 (unsigned char *buffer_)
+ {
+ return *buffer_;
+ }
+
+ inline void put_uint16 (unsigned char *buffer_, uint16_t value)
+ {
+ buffer_ [0] = (unsigned char) (((value) >> 8) & 0xff);
+ buffer_ [1] = (unsigned char) (value & 0xff);
+ }
+
+ inline uint16_t get_uint16 (unsigned char *buffer_)
+ {
+ return
+ (((uint16_t) buffer_ [0]) << 8) |
+ ((uint16_t) buffer_ [1]);
+ }
+
+ inline void put_uint32 (unsigned char *buffer_, uint32_t value)
+ {
+ buffer_ [0] = (unsigned char) (((value) >> 24) & 0xff);
+ buffer_ [1] = (unsigned char) (((value) >> 16) & 0xff);
+ buffer_ [2] = (unsigned char) (((value) >> 8) & 0xff);
+ buffer_ [3] = (unsigned char) (value & 0xff);
+ }
+
+ inline uint32_t get_uint32 (unsigned char *buffer_)
+ {
+ return
+ (((uint32_t) buffer_ [0]) << 24) |
+ (((uint32_t) buffer_ [1]) << 16) |
+ (((uint32_t) buffer_ [2]) << 8) |
+ ((uint32_t) buffer_ [3]);
+ }
+
+ inline void put_uint64 (unsigned char *buffer_, uint64_t value)
+ {
+ buffer_ [0] = (unsigned char) (((value) >> 56) & 0xff);
+ buffer_ [1] = (unsigned char) (((value) >> 48) & 0xff);
+ buffer_ [2] = (unsigned char) (((value) >> 40) & 0xff);
+ buffer_ [3] = (unsigned char) (((value) >> 32) & 0xff);
+ buffer_ [4] = (unsigned char) (((value) >> 24) & 0xff);
+ buffer_ [5] = (unsigned char) (((value) >> 16) & 0xff);
+ buffer_ [6] = (unsigned char) (((value) >> 8) & 0xff);
+ buffer_ [7] = (unsigned char) (value & 0xff);
+ }
+
+ inline uint64_t get_uint64 (unsigned char *buffer_)
+ {
+ return
+ (((uint64_t) buffer_ [0]) << 56) |
+ (((uint64_t) buffer_ [1]) << 48) |
+ (((uint64_t) buffer_ [2]) << 40) |
+ (((uint64_t) buffer_ [3]) << 32) |
+ (((uint64_t) buffer_ [4]) << 24) |
+ (((uint64_t) buffer_ [5]) << 16) |
+ (((uint64_t) buffer_ [6]) << 8) |
+ ((uint64_t) buffer_ [7]);
+ }
+
+}
+
+#endif
diff --git a/src/0mq/xpub.cpp b/src/0mq/xpub.cpp
new file mode 100644
index 0000000..ed56183
--- /dev/null
+++ b/src/0mq/xpub.cpp
@@ -0,0 +1,76 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "xpub.hpp"
+#include "err.hpp"
+#include "pipe.hpp"
+
+zmq::xpub_t::xpub_t (class ctx_t *parent_, uint32_t tid_) :
+ socket_base_t (parent_, tid_),
+ dist (this)
+{
+ options.type = ZMQ_XPUB;
+ options.requires_in = false;
+ options.requires_out = true;
+}
+
+zmq::xpub_t::~xpub_t ()
+{
+}
+
+void zmq::xpub_t::xattach_pipes (class reader_t *inpipe_,
+ class writer_t *outpipe_, const blob_t &peer_identity_)
+{
+ zmq_assert (!inpipe_ && outpipe_);
+ dist.attach (outpipe_);
+}
+
+void zmq::xpub_t::process_term (int linger_)
+{
+ // Terminate the outbound pipes.
+ dist.terminate ();
+
+ // Continue with the termination immediately.
+ socket_base_t::process_term (linger_);
+}
+
+int zmq::xpub_t::xsend (zmq_msg_t *msg_, int flags_)
+{
+ return dist.send (msg_, flags_);
+}
+
+bool zmq::xpub_t::xhas_out ()
+{
+ return dist.has_out ();
+}
+
+int zmq::xpub_t::xrecv (zmq_msg_t *msg_, int flags_)
+{
+ errno = EAGAIN;
+ return -1;
+}
+
+bool zmq::xpub_t::xhas_in ()
+{
+ return false;
+}
+
diff --git a/src/0mq/xpub.hpp b/src/0mq/xpub.hpp
new file mode 100644
index 0000000..e945198
--- /dev/null
+++ b/src/0mq/xpub.hpp
@@ -0,0 +1,61 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef __ZMQ_XPUB_HPP_INCLUDED__
+#define __ZMQ_XPUB_HPP_INCLUDED__
+
+#include "socket_base.hpp"
+#include "array.hpp"
+#include "pipe.hpp"
+#include "dist.hpp"
+
+namespace zmq
+{
+
+ class xpub_t : public socket_base_t
+ {
+ public:
+
+ xpub_t (class ctx_t *parent_, uint32_t tid_);
+ ~xpub_t ();
+
+ // Implementations of virtual functions from socket_base_t.
+ void xattach_pipes (class reader_t *inpipe_, class writer_t *outpipe_,
+ const blob_t &peer_identity_);
+ int xsend (zmq_msg_t *msg_, int flags_);
+ bool xhas_out ();
+ int xrecv (zmq_msg_t *msg_, int flags_);
+ bool xhas_in ();
+
+ private:
+
+ // Hook into the termination process.
+ void process_term (int linger_);
+
+ // Distributor of messages holding the list of outbound pipes.
+ dist_t dist;
+
+ xpub_t (const xpub_t&);
+ const xpub_t &operator = (const xpub_t&);
+ };
+
+}
+
+#endif
diff --git a/src/0mq/xrep.cpp b/src/0mq/xrep.cpp
new file mode 100644
index 0000000..c60d6a6
--- /dev/null
+++ b/src/0mq/xrep.cpp
@@ -0,0 +1,332 @@
+/*
+ Copyright (c) 2007-2011 iMatix Corporation
+ Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
+
+ This file is part of 0MQ.
+
+ 0MQ is free software; you can redistribute it and/or modify it under
+ the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ 0MQ is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "../include/zmq.h"
+
+#include "xrep.hpp"
+#include "err.hpp"
+#include "pipe.hpp"
+
+zmq::xrep_t::xrep_t (class ctx_t *parent_, uint32_t tid_) :
+ socket_base_t (parent_, tid_),
+ current_in (0),
+ prefetched (false),
+ more_in (false),
+ current_out (NULL),
+ more_out (false),
+ terminating (false)
+{
+ options.type = ZMQ_XREP;
+ options.requires_in = true;
+ options.requires_out = true;
+
+ // On connect, pipes are created only after initial handshaking.
+ // That way we are aware of the peer's identity when binding to the pipes.
+ options.immediate_connect = false;
+}
+
+zmq::xrep_t::~xrep_t ()
+{
+ zmq_assert (inpipes.empty ());
+ zmq_assert (outpipes.empty ());
+}
+
+void zmq::xrep_t::xattach_pipes (reader