socket_base.cpp 26.3 KB
Newer Older
1
/*
Martin Sustrik's avatar
Martin Sustrik committed
2
    Copyright (c) 2009-2011 250bpm s.r.o.
3
    Copyright (c) 2007-2009 iMatix Corporation
4
    Copyright (c) 2011 VMware, Inc.
5
    Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
6 7 8 9

    This file is part of 0MQ.

    0MQ is free software; you can redistribute it and/or modify it under
10
    the terms of the GNU Lesser General Public License as published by
11 12 13 14 15 16
    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
17
    GNU Lesser General Public License for more details.
18

19
    You should have received a copy of the GNU Lesser General Public License
20 21 22
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

23
#include <new>
24
#include <string>
25 26
#include <algorithm>

27 28 29 30 31
#include "platform.hpp"

#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#if defined _MSC_VER
boris@boressoft.ru's avatar
boris@boressoft.ru committed
32 33 34
#if defined WINCE
#include <cmnintrin.h>
#else
35 36
#include <intrin.h>
#endif
boris@boressoft.ru's avatar
boris@boressoft.ru committed
37
#endif
38 39 40
#else
#include <unistd.h>
#endif
41

42
#include "socket_base.hpp"
43
#include "tcp_listener.hpp"
44
#include "ipc_listener.hpp"
45
#include "tcp_connecter.hpp"
46
#include "io_thread.hpp"
47
#include "session_base.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
48
#include "config.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
49
#include "clock.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
50
#include "pipe.hpp"
51
#include "err.hpp"
52
#include "ctx.hpp"
malosek's avatar
malosek committed
53
#include "platform.hpp"
54
#include "likely.hpp"
55
#include "msg.hpp"
56 57 58
#include "address.hpp"
#include "ipc_address.hpp"
#include "tcp_address.hpp"
59

60 61 62 63 64 65 66
#include "pair.hpp"
#include "pub.hpp"
#include "sub.hpp"
#include "req.hpp"
#include "rep.hpp"
#include "pull.hpp"
#include "push.hpp"
67 68
#include "dealer.hpp"
#include "router.hpp"
69 70
#include "xpub.hpp"
#include "xsub.hpp"
71

72 73 74 75 76
bool zmq::socket_base_t::check_tag ()
{
    return tag == 0xbaddecaf;
}

77
zmq::socket_base_t *zmq::socket_base_t::create (int type_, class ctx_t *parent_,
78
    uint32_t tid_, int sid_)
79 80 81 82 83
{
    socket_base_t *s = NULL;
    switch (type_) {

    case ZMQ_PAIR:
84
        s = new (std::nothrow) pair_t (parent_, tid_, sid_);
85 86
        break;
    case ZMQ_PUB:
87
        s = new (std::nothrow) pub_t (parent_, tid_, sid_);
88 89
        break;
    case ZMQ_SUB:
90
        s = new (std::nothrow) sub_t (parent_, tid_, sid_);
91 92
        break;
    case ZMQ_REQ:
93
        s = new (std::nothrow) req_t (parent_, tid_, sid_);
94 95
        break;
    case ZMQ_REP:
96
        s = new (std::nothrow) rep_t (parent_, tid_, sid_);
97
        break;
98 99
    case ZMQ_DEALER:
        s = new (std::nothrow) dealer_t (parent_, tid_, sid_);
100
        break;
101 102
    case ZMQ_ROUTER:
        s = new (std::nothrow) router_t (parent_, tid_, sid_);
103 104
        break;     
    case ZMQ_PULL:
105
        s = new (std::nothrow) pull_t (parent_, tid_, sid_);
106 107
        break;
    case ZMQ_PUSH:
108
        s = new (std::nothrow) push_t (parent_, tid_, sid_);
109
        break;
110
    case ZMQ_XPUB:
111
        s = new (std::nothrow) xpub_t (parent_, tid_, sid_);
112 113
        break;
    case ZMQ_XSUB:
114
        s = new (std::nothrow) xsub_t (parent_, tid_, sid_);
115
        break;
116 117 118 119
    default:
        errno = EINVAL;
        return NULL;
    }
120
    alloc_assert (s);
121 122 123
    return s;
}

124
zmq::socket_base_t::socket_base_t (ctx_t *parent_, uint32_t tid_, int sid_) :
Martin Sustrik's avatar
Martin Sustrik committed
125
    own_t (parent_, tid_),
126
    tag (0xbaddecaf),
127
    ctx_terminated (false),
128
    destroyed (false),
Martin Sustrik's avatar
Martin Sustrik committed
129
    last_tsc (0),
Martin Sustrik's avatar
Martin Sustrik committed
130
    ticks (0),
131
    rcvmore (false)
Martin Sustrik's avatar
Martin Sustrik committed
132
{
133
    options.socket_id = sid_;
134 135 136 137
}

zmq::socket_base_t::~socket_base_t ()
{
138
    zmq_assert (destroyed);
139 140
}

141
zmq::mailbox_t *zmq::socket_base_t::get_mailbox ()
142
{
143
    return &mailbox;
144 145 146 147 148 149 150 151 152 153 154
}

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 ();
}

155 156 157 158 159 160 161 162 163 164 165 166 167
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);
168
    
169 170 171 172 173 174 175
    if (protocol_.empty () || address_.empty ()) {
        errno = EINVAL;
        return -1;
    }
    return 0;
}

176 177 178 179
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" &&
Pieter Hintjens's avatar
Pieter Hintjens committed
180
          protocol_ != "pgm" && protocol_ != "epgm") {
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        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
196
    if (protocol_ == "ipc") {
197 198 199 200 201 202 203 204 205 206
        //  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") &&
207 208
          options.type != ZMQ_PUB && options.type != ZMQ_SUB &&
          options.type != ZMQ_XPUB && options.type != ZMQ_XSUB) {
209 210 211 212 213 214 215 216
        errno = ENOCOMPATPROTO;
        return -1;
    }

    //  Protocol is available.
    return 0;
}

217
void zmq::socket_base_t::attach_pipe (pipe_t *pipe_, bool icanhasall_)
218
{
219 220 221 222
    //  First, register the pipe so that we can terminate it later on.
    pipe_->set_event_sink (this);
    pipes.push_back (pipe_);
    
223
    //  Let the derived socket type know about new pipe.
224
    xattach_pipe (pipe_, icanhasall_);
225 226 227 228 229

    //  If the socket is already being closed, ask any new pipes to terminate
    //  straight away.
    if (is_terminating ()) {
        register_term_acks (1);
230
        pipe_->terminate (false);
231
    }
232 233
}

234
int zmq::socket_base_t::setsockopt (int option_, const void *optval_,
235
    size_t optvallen_)
236
{
237
    if (unlikely (ctx_terminated)) {
238 239 240 241
        errno = ETERM;
        return -1;
    }

242 243 244 245 246 247 248 249
    //  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_);
250 251
}

252 253 254
int zmq::socket_base_t::getsockopt (int option_, void *optval_,
    size_t *optvallen_)
{
255
    if (unlikely (ctx_terminated)) {
256 257 258 259
        errno = ETERM;
        return -1;
    }

260
    if (option_ == ZMQ_RCVMORE) {
261
        if (*optvallen_ < sizeof (int)) {
262 263 264
            errno = EINVAL;
            return -1;
        }
265 266
        *((int*) optval_) = rcvmore ? 1 : 0;
        *optvallen_ = sizeof (int);
267 268 269
        return 0;
    }

270 271 272 273 274
    if (option_ == ZMQ_FD) {
        if (*optvallen_ < sizeof (fd_t)) {
            errno = EINVAL;
            return -1;
        }
275
        *((fd_t*) optval_) = mailbox.get_fd ();
276 277 278 279 280
        *optvallen_ = sizeof (fd_t);
        return 0;
    }

    if (option_ == ZMQ_EVENTS) {
281
        if (*optvallen_ < sizeof (int)) {
282 283 284
            errno = EINVAL;
            return -1;
        }
285
        int rc = process_commands (0, false);
286
        if (rc != 0 && (errno == EINTR || errno == ETERM))
287 288
            return -1;
        errno_assert (rc == 0);
289
        *((int*) optval_) = 0;
290
        if (has_out ())
291
            *((int*) optval_) |= ZMQ_POLLOUT;
292
        if (has_in ())
293 294
            *((int*) optval_) |= ZMQ_POLLIN;
        *optvallen_ = sizeof (int);
295 296 297
        return 0;
    }

298 299 300
    return options.getsockopt (option_, optval_, optvallen_);
}

301 302
int zmq::socket_base_t::bind (const char *addr_)
{
303
    if (unlikely (ctx_terminated)) {
304 305 306 307
        errno = ETERM;
        return -1;
    }

308
    //  Parse addr_ string.
309 310
    std::string protocol;
    std::string address;
311 312 313
    int rc = parse_uri (addr_, protocol, address);
    if (rc != 0)
        return -1;
314

315
    rc = check_protocol (protocol);
316 317
    if (rc != 0)
        return -1;
318

Pieter Hintjens's avatar
Pieter Hintjens committed
319
    if (protocol == "inproc") {
320
        endpoint_t endpoint = {this, options};
321 322 323 324 325 326 327
        int rc = register_endpoint (addr_, endpoint);
        if (rc == 0) {
            // Save last endpoint info
            options.last_endpoint.clear ();
            options.last_endpoint_id = NULL;
        }
        return rc;
328
    }
329

330 331 332
    if (protocol == "pgm" || protocol == "epgm") {
        //  For convenience's sake, bind can be used interchageable with
        //  connect for PGM and EPGM transports.
333
        return connect (addr_);
334 335 336 337 338 339 340 341 342
    }

    //  Remaining trasnports require to be run in an I/O thread, so at this
    //  point we'll choose one.
    io_thread_t *io_thread = choose_io_thread (options.affinity);
    if (!io_thread) {
        errno = EMTHREAD;
        return -1;
    }
343

344
    if (protocol == "tcp") {
345
        tcp_listener_t *listener = new (std::nothrow) tcp_listener_t (
346
            io_thread, this, options);
347
        alloc_assert (listener);
348
        int rc = listener->set_address (address.c_str ());
349 350
        if (rc != 0) {
            delete listener;
351
            return -1;
352
        }
353

354 355 356 357
        // Save last endpoint info
        options.last_endpoint_id = (void *) ((own_t *) listener);
        listener->get_address (options.last_endpoint);

358
        launch_child (listener);
359 360 361
        return 0;
    }

362
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS
363 364 365 366
    if (protocol == "ipc") {
        ipc_listener_t *listener = new (std::nothrow) ipc_listener_t (
            io_thread, this, options);
        alloc_assert (listener);
367
        int rc = listener->set_address (address.c_str ());
368 369
        if (rc != 0) {
            delete listener;
370 371
            return -1;
        }
372

373 374 375 376
        // Save last endpoint info
        options.last_endpoint_id = (void *) ((own_t *) listener);
        listener->get_address (options.last_endpoint);

377 378
        launch_child (listener);
        return 0;
379
    }
380
#endif
381

382
    zmq_assert (false);
Martin Sustrik's avatar
Martin Sustrik committed
383
    return -1;
384 385
}

386
int zmq::socket_base_t::connect (const char *addr_)
387
{
388
    if (unlikely (ctx_terminated)) {
389 390 391 392
        errno = ETERM;
        return -1;
    }

malosek's avatar
malosek committed
393
    //  Parse addr_ string.
394 395
    std::string protocol;
    std::string address;
396 397 398
    int rc = parse_uri (addr_, protocol, address);
    if (rc != 0)
        return -1;
malosek's avatar
malosek committed
399

400
    rc = check_protocol (protocol);
401 402
    if (rc != 0)
        return -1;
malosek's avatar
malosek committed
403

Pieter Hintjens's avatar
Pieter Hintjens committed
404
    if (protocol == "inproc") {
405

406 407 408 409
        //  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.

410 411 412
        //  Find the peer endpoint.
        endpoint_t peer = find_endpoint (addr_);
        if (!peer.socket)
413 414
            return -1;

415
        // The total HWM for an inproc connection should be the sum of
416
        // the binder's HWM and the connector's HWM.
417 418 419 420
        int  sndhwm;
        int  rcvhwm;
        if (options.sndhwm == 0 || peer.options.rcvhwm == 0)
            sndhwm = 0;
421
        else
422 423 424 425 426
            sndhwm = options.sndhwm + peer.options.rcvhwm;
        if (options.rcvhwm == 0 || peer.options.sndhwm == 0)
            rcvhwm = 0;
        else
            rcvhwm = options.rcvhwm + peer.options.sndhwm;
427

428 429 430 431
        //  Create a bi-directional pipe to connect the peers.
        object_t *parents [2] = {this, peer.socket};
        pipe_t *pipes [2] = {NULL, NULL};
        int hwms [2] = {sndhwm, rcvhwm};
432
        bool delays [2] = {options.delay_on_disconnect, options.delay_on_close};
433 434
        int rc = pipepair (parents, pipes, hwms, delays);
        errno_assert (rc == 0);
435

436
        //  Attach local end of the pipe to this socket object.
437
        attach_pipe (pipes [0]);
438

439 440 441 442 443 444 445 446 447
        //  If required, send the identity of the local socket to the peer.
        if (options.send_identity) {
            msg_t id;
            rc = id.init_size (options.identity_size);
            zmq_assert (rc == 0);
            memcpy (id.data (), options.identity, options.identity_size);
            id.set_flags (msg_t::identity);
            bool written = pipes [0]->write (&id);
            zmq_assert (written);
448
            pipes [0]->flush ();
449 450
        }

451 452 453 454 455 456 457 458 459 460 461 462
        //  If required, send the identity of the peer to the local socket.
        if (peer.options.send_identity) {
            msg_t id;
            rc = id.init_size (peer.options.identity_size);
            zmq_assert (rc == 0);
            memcpy (id.data (), peer.options.identity, peer.options.identity_size);
            id.set_flags (msg_t::identity);
            bool written = pipes [1]->write (&id);
            zmq_assert (written);
            pipes [1]->flush ();
        }

463 464
        //  Attach remote end of the pipe to the peer socket. Note that peer's
        //  seqnum was incremented in find_endpoint function. We don't need it
465
        //  increased here.
466
        send_bind (peer.socket, pipes [1], false);
467

468 469 470 471
        // Save last endpoint info
        options.last_endpoint.clear ();
        options.last_endpoint_id = NULL;

472 473 474
        return 0;
    }

475 476 477 478 479 480 481
    //  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;
    }

482 483 484 485 486 487 488 489 490 491 492 493 494 495
    address_t *paddr = new (std::nothrow) address_t (protocol, address);
    zmq_assert (paddr);

    //  Resolve address (if needed by the protocol)
    if (protocol == "tcp") {
        paddr->resolved.tcp_addr = new (std::nothrow) tcp_address_t ();
        zmq_assert (paddr->resolved.tcp_addr);
        int rc = paddr->resolved.tcp_addr->resolve (
            address.c_str (), false, options.ipv4only ? true : false);
        if (rc != 0) {
            delete paddr;
            return -1;
        }
    }
496
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS
497 498 499 500 501 502 503 504 505
    else if(protocol == "ipc") {
        paddr->resolved.ipc_addr = new (std::nothrow) ipc_address_t ();
        zmq_assert (paddr->resolved.ipc_addr);
        int rc = paddr->resolved.ipc_addr->resolve (address.c_str ());
        if (rc != 0) {
            delete paddr;
            return -1;
        }
    }
506
#endif
507
    //  Create session.
508
    session_base_t *session = session_base_t::create (io_thread, true, this,
509
        options, paddr);
510
    errno_assert (session);
Martin Sustrik's avatar
Martin Sustrik committed
511

512 513 514 515 516 517 518 519
    //  Create a bi-directional pipe.
    object_t *parents [2] = {this, session};
    pipe_t *pipes [2] = {NULL, NULL};
    int hwms [2] = {options.sndhwm, options.rcvhwm};
    bool delays [2] = {options.delay_on_disconnect, options.delay_on_close};
    rc = pipepair (parents, pipes, hwms, delays);
    errno_assert (rc == 0);

520 521 522 523 524 525
    //  PGM does not support subscription forwarding; ask for all data to be
    //  sent to this pipe.
    bool icanhasall = false;
    if (protocol == "pgm" || protocol == "epgm")
        icanhasall = true;

526
    //  Attach local end of the pipe to the socket object.
527
    attach_pipe (pipes [0], icanhasall);
528 529 530

    //  Attach remote end of the pipe to the session object later on.
    session->attach_pipe (pipes [1]);
Martin Sustrik's avatar
Martin Sustrik committed
531

532 533 534 535
    // Save last endpoint info
    paddr->to_string (options.last_endpoint);
    options.last_endpoint_id = (void *) ((own_t *) session);

536 537
    //  Activate the session. Make it a child of this socket.
    launch_child (session);
malosek's avatar
malosek committed
538

539
    return 0;
540 541
}

542
int zmq::socket_base_t::send (msg_t *msg_, int flags_)
543
{
544
    //  Check whether the library haven't been shut down yet.
545
    if (unlikely (ctx_terminated)) {
546 547 548 549
        errno = ETERM;
        return -1;
    }

550
    //  Check whether message passed to the function is valid.
551
    if (unlikely (!msg_ || !msg_->check ())) {
552 553 554 555
        errno = EFAULT;
        return -1;
    }

556
    //  Process pending commands, if any.
557
    int rc = process_commands (0, true);
558
    if (unlikely (rc != 0))
559 560
        return -1;

561 562 563
    //  Clear any user-visible flags that are set on the message.
    msg_->reset_flags (msg_t::more);

564
    //  At this point we impose the flags on the message.
565
    if (flags_ & ZMQ_SNDMORE)
566
        msg_->set_flags (msg_t::more);
567

Martin Sustrik's avatar
Martin Sustrik committed
568
    //  Try to send the message.
569
    rc = xsend (msg_, flags_);
570 571
    if (rc == 0)
        return 0;
572 573
    if (unlikely (errno != EAGAIN))
        return -1;
Martin Sustrik's avatar
Martin Sustrik committed
574

575
    //  In case of non-blocking send we'll simply propagate
576 577
    //  the error - including EAGAIN - up the stack.
    if (flags_ & ZMQ_DONTWAIT || options.sndtimeo == 0)
Martin Sustrik's avatar
Martin Sustrik committed
578 579
        return -1;

580 581 582 583 584 585
    //  Compute the time when the timeout should occur.
    //  If the timeout is infite, don't care. 
    clock_t clock ;
    int timeout = options.sndtimeo;
    uint64_t end = timeout < 0 ? 0 : (clock.now_ms () + timeout);

586 587
    //  Oops, we couldn't send the message. Wait for the next
    //  command, process it and try to send the message again.
588 589 590
    //  If timeout is reached in the meantime, return EAGAIN.
    while (true) {
        if (unlikely (process_commands (timeout, false) != 0))
591
            return -1;
592
        rc = xsend (msg_, flags_);
593 594 595 596 597
        if (rc == 0)
            break;
        if (unlikely (errno != EAGAIN))
            return -1;
        if (timeout > 0) {
598
            timeout = (int) (end - clock.now_ms ());
599 600 601 602 603
            if (timeout <= 0) {
                errno = EAGAIN;
                return -1;
            }
        }
604
    }
Martin Sustrik's avatar
Martin Sustrik committed
605
    return 0;
606 607
}

608 609 610 611 612 613 614 615 616 617
int zmq::socket_base_t::term_endpoint (void *ep_)
{
    if (unlikely (ctx_terminated)) {
        errno = ETERM;
        return -1;
    }
    term_child ((own_t *) ep_);
    return 0;
}

618
int zmq::socket_base_t::recv (msg_t *msg_, int flags_)
619
{
620
    //  Check whether the library haven't been shut down yet.
621
    if (unlikely (ctx_terminated)) {
622 623 624 625
        errno = ETERM;
        return -1;
    }

626
    //  Check whether message passed to the function is valid.
627
    if (unlikely (!msg_ || !msg_->check ())) {
628 629 630 631
        errno = EFAULT;
        return -1;
    }

632
    //  Get the message.
633
    int rc = xrecv (msg_, flags_);
634 635
    if (unlikely (rc != 0 && errno != EAGAIN))
        return -1;
636 637 638 639 640 641 642 643

    //  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
Martin Sustrik's avatar
Martin Sustrik committed
644
    //  ticks is more efficient than doing RDTSC all the time.
645
    if (++ticks == inbound_poll_rate) {
646
        if (unlikely (process_commands (0, false) != 0))
647
            return -1;
648 649 650 651
        ticks = 0;
    }

    //  If we have the message, return immediately.
652
    if (rc == 0) {
653
        extract_flags (msg_);
654
        return 0;
655
    }
656

Martin Sustrik's avatar
Martin Sustrik committed
657
    //  If the message cannot be fetched immediately, there are two scenarios.
658 659 660
    //  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.
661 662
    if (flags_ & ZMQ_DONTWAIT || options.rcvtimeo == 0) {
        if (unlikely (process_commands (0, false) != 0))
663
            return -1;
664
        ticks = 0;
665 666

        rc = xrecv (msg_, flags_);
667 668
        if (rc < 0)
            return rc;
669
        extract_flags (msg_);
670
        return 0;
Martin Sustrik's avatar
Martin Sustrik committed
671 672
    }

673 674 675 676 677 678
    //  Compute the time when the timeout should occur.
    //  If the timeout is infite, don't care. 
    clock_t clock ;
    int timeout = options.rcvtimeo;
    uint64_t end = timeout < 0 ? 0 : (clock.now_ms () + timeout);

679 680
    //  In blocking scenario, commands are processed over and over again until
    //  we are able to fetch a message.
681
    bool block = (ticks != 0);
682 683
    while (true) {
        if (unlikely (process_commands (block ? timeout : 0, false) != 0))
684
            return -1;
685
        rc = xrecv (msg_, flags_);
686 687 688 689 690 691
        if (rc == 0) {
            ticks = 0;
            break;
        }
        if (unlikely (errno != EAGAIN))
            return -1;
692
        block = true;
693
        if (timeout > 0) {
694
            timeout = (int) (end - clock.now_ms ());
695 696 697 698 699
            if (timeout <= 0) {
                errno = EAGAIN;
                return -1;
            }
        }
700
    }
701

702
    extract_flags (msg_);
703
    return 0;
704 705 706 707
}

int zmq::socket_base_t::close ()
{
708 709 710
    //  Mark the socket as dead
    tag = 0xdeadbeef;
    
711 712 713 714
    //  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);
715

716 717 718
    return 0;
}

719 720 721 722 723 724 725 726 727 728
bool zmq::socket_base_t::has_in ()
{
    return xhas_in ();
}

bool zmq::socket_base_t::has_out ()
{
    return xhas_out ();
}

729
void zmq::socket_base_t::start_reaping (poller_t *poller_)
730
{
731
    //  Plug the socket to the reaper thread.
732 733 734
    poller = poller_;
    handle = poller->add_fd (mailbox.get_fd (), this);
    poller->set_pollin (handle);
735 736 737 738 739

    //  Initialise the termination and check whether it can be deallocated
    //  immediately.
    terminate ();
    check_destroy ();
Martin Hurton's avatar
Martin Hurton committed
740 741
}

742
int zmq::socket_base_t::process_commands (int timeout_, bool throttle_)
Martin Sustrik's avatar
Martin Sustrik committed
743
{
744
    int rc;
745
    command_t cmd;
746 747 748 749
    if (timeout_ != 0) {

        //  If we are asked to wait, simply ask mailbox to wait.
        rc = mailbox.recv (&cmd, timeout_);
750 751
    }
    else {
752

753 754 755
        //  If we are asked not to wait, check whether we haven't processed
        //  commands recently, so that we can throttle the new commands.

Martin Sustrik's avatar
Martin Sustrik committed
756 757 758
        //  Get the CPU's tick counter. If 0, the counter is not available.
        uint64_t tsc = zmq::clock_t::rdtsc ();

759 760 761 762 763 764
        //  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).
Martin Sustrik's avatar
Martin Sustrik committed
765 766
        if (tsc && throttle_) {

Martin Sustrik's avatar
Martin Sustrik committed
767 768 769
            //  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.
Martin Sustrik's avatar
Martin Sustrik committed
770
            if (tsc >= last_tsc && tsc - last_tsc <= max_command_delay)
771
                return 0;
Martin Sustrik's avatar
Martin Sustrik committed
772
            last_tsc = tsc;
773 774 775
        }

        //  Check whether there are any commands pending for this thread.
776
        rc = mailbox.recv (&cmd, 0);
777
    }
Martin Sustrik's avatar
Martin Sustrik committed
778

779
    //  Process all the commands available at the moment.
780 781 782 783 784 785
    while (true) {
        if (rc == -1 && errno == EAGAIN)
            break;
        if (rc == -1 && errno == EINTR)
            return -1;
        errno_assert (rc == 0);
786
        cmd.destination->process_command (cmd);
787
        rc = mailbox.recv (&cmd, 0);
788 789
     }

790
    if (ctx_terminated) {
791 792
        errno = ETERM;
        return -1;
793
    }
794 795

    return 0;
Martin Sustrik's avatar
Martin Sustrik committed
796 797
}

798
void zmq::socket_base_t::process_stop ()
Martin Sustrik's avatar
Martin Sustrik committed
799
{
800
    //  Here, someone have called zmq_term while the socket was still alive.
801
    //  We'll remember the fact so that any blocking call is interrupted and any
802 803
    //  further attempt to use the socket will return ETERM. The user is still
    //  responsible for calling zmq_close on the socket though!
804
    ctx_terminated = true;
Martin Sustrik's avatar
Martin Sustrik committed
805 806
}

807
void zmq::socket_base_t::process_bind (pipe_t *pipe_)
Martin Sustrik's avatar
Martin Sustrik committed
808
{
809
    attach_pipe (pipe_);
Martin Sustrik's avatar
Martin Sustrik committed
810 811
}

812
void zmq::socket_base_t::process_unplug ()
813 814 815
{
}

816
void zmq::socket_base_t::process_term (int linger_)
817
{
818 819 820 821 822
    //  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);

823 824
    //  Ask all attached pipes to terminate.
    for (pipes_t::size_type i = 0; i != pipes.size (); ++i)
825
        pipes [i]->terminate (false);
Martin Sustrik's avatar
Martin Sustrik committed
826
    register_term_acks ((int) pipes.size ());
827

828
    //  Continue the termination process immediately.
829
    own_t::process_term (linger_);
830 831
}

832 833 834 835 836
void zmq::socket_base_t::process_destroy ()
{
    destroyed = true;
}

837 838 839 840 841 842 843 844 845 846 847 848
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;
}

849
int zmq::socket_base_t::xsend (msg_t *msg_, int flags_)
850 851 852 853 854 855 856 857 858 859
{
    errno = ENOTSUP;
    return -1;
}

bool zmq::socket_base_t::xhas_in ()
{
    return false;
}

860
int zmq::socket_base_t::xrecv (msg_t *msg_, int flags_)
861 862 863 864 865
{
    errno = ENOTSUP;
    return -1;
}

866 867 868 869 870 871 872 873 874
void zmq::socket_base_t::xread_activated (pipe_t *pipe_)
{
    zmq_assert (false);
}
void zmq::socket_base_t::xwrite_activated (pipe_t *pipe_)
{
    zmq_assert (false);
}

875 876 877 878 879
void zmq::socket_base_t::xhiccuped (pipe_t *pipe_)
{
    zmq_assert (false);
}

880 881
void zmq::socket_base_t::in_event ()
{
882 883 884 885 886
    //  This function is invoked only once the socket is running in the context
    //  of the reaper thread. Process any commands from other threads/sockets
    //  that may be available at the moment. Ultimately, the socket will
    //  be destroyed.
    process_commands (0, false);
887 888 889 890 891 892 893 894 895 896 897 898
    check_destroy ();
}

void zmq::socket_base_t::out_event ()
{
    zmq_assert (false);
}

void zmq::socket_base_t::timer_event (int id_)
{
    zmq_assert (false);
}
899

900 901
void zmq::socket_base_t::check_destroy ()
{
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
    //  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 ();
    }
}
918 919 920 921 922 923 924 925 926 927 928

void zmq::socket_base_t::read_activated (pipe_t *pipe_)
{
    xread_activated (pipe_);
}

void zmq::socket_base_t::write_activated (pipe_t *pipe_)
{
    xwrite_activated (pipe_);
}

929 930 931 932 933
void zmq::socket_base_t::hiccuped (pipe_t *pipe_)
{
    xhiccuped (pipe_);
}

934 935 936 937 938 939 940 941 942 943 944 945
void zmq::socket_base_t::terminated (pipe_t *pipe_)
{
    //  Notify the specific socket type about the pipe termination.
    xterminated (pipe_);

    //  Remove the pipe from the list of attached pipes and confirm its
    //  termination if we are already shutting down.
    pipes.erase (pipe_);
    if (is_terminating ())
        unregister_term_ack ();
}

946 947
void zmq::socket_base_t::extract_flags (msg_t *msg_)
{
948
    //  Test whether IDENTITY flag is valid for this socket type.
949
    if (unlikely (msg_->flags () & msg_t::identity))
950 951 952
        zmq_assert (options.recv_identity);
  
    //  Remove MORE flag.
953 954
    rcvmore = msg_->flags () & msg_t::more ? true : false;
}