router.cpp 14.9 KB
Newer Older
1
/*
2
    Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file
3

4
    This file is part of libzmq, the ZeroMQ core engine in C++.
5

6 7 8
    libzmq is free software; you can redistribute it and/or modify it under
    the terms of the GNU Lesser General Public License (LGPL) as published
    by the Free Software Foundation; either version 3 of the License, or
9 10
    (at your option) any later version.

11 12 13 14 15 16 17 18 19 20 21 22 23 24
    As a special exception, the Contributors give you permission to link
    this library with independent modules to produce an executable,
    regardless of the license terms of these independent modules, and to
    copy and distribute the resulting executable under terms of your choice,
    provided that you also meet, for each linked independent module, the
    terms and conditions of the license of that module. An independent
    module is a module which is not derived from or based on this library.
    If you modify this library, you must extend this exception to your
    version of the library.

    libzmq 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.
25

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

30
#include "macros.hpp"
31
#include "router.hpp"
32
#include "pipe.hpp"
33 34
#include "wire.hpp"
#include "random.hpp"
35
#include "likely.hpp"
36
#include "err.hpp"
37

38
zmq::router_t::router_t (class ctx_t *parent_, uint32_t tid_, int sid_) :
39
    socket_base_t (parent_, tid_, sid_),
40 41
    prefetched (false),
    identity_sent (false),
42 43
    current_in (NULL),
    terminate_current_in (false),
44 45
    more_in (false),
    current_out (NULL),
46
    more_out (false),
47
    next_rid (generate_random ()),
48
    mandatory (false),
49
    //  raw_socket functionality in ROUTER is deprecated
50
    raw_socket (false),
51
    probe_router (false),
Pieter Hintjens's avatar
Pieter Hintjens committed
52
    handover (false)
53
{
54
    options.type = ZMQ_ROUTER;
55
    options.recv_identity = true;
56
    options.raw_socket = false;
57

58
    prefetched_id.init ();
59
    prefetched_msg.init ();
60 61
}

62
zmq::router_t::~router_t ()
63
{
64
    zmq_assert (anonymous_pipes.empty ());;
65
    zmq_assert (outpipes.empty ());
66
    prefetched_id.close ();
67
    prefetched_msg.close ();
68 69
}

70
void zmq::router_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_)
71
{
72
    LIBZMQ_UNUSED (subscribe_to_all_);
73

74 75
    zmq_assert (pipe_);

76 77 78 79 80 81 82 83 84 85 86 87 88
    if (probe_router) {
        msg_t probe_msg_;
        int rc = probe_msg_.init ();
        errno_assert (rc == 0);

        rc = pipe_->write (&probe_msg_);
        // zmq_assert (rc) is not applicable here, since it is not a bug.
        pipe_->flush ();

        rc = probe_msg_.close ();
        errno_assert (rc == 0);
    }

89 90 91 92 93
    bool identity_ok = identify_peer (pipe_);
    if (identity_ok)
        fq.attach (pipe_);
    else
        anonymous_pipes.insert (pipe_);
94 95
}

96
int zmq::router_t::xsetsockopt (int option_, const void *optval_,
97 98
    size_t optvallen_)
{
99 100 101 102
    bool is_int = (optvallen_ == sizeof (int));
    int value = is_int? *((int *) optval_): 0;

    switch (option_) {
103 104 105
        case ZMQ_CONNECT_RID:
            if (optval_ && optvallen_) {
                connect_rid.assign ((char *) optval_, optvallen_);
106 107
                return 0;
            }
108
            break;
109

110 111
        case ZMQ_ROUTER_RAW:
            if (is_int && value >= 0) {
112 113
                raw_socket = (value != 0);
                if (raw_socket) {
114
                    options.recv_identity = false;
115
                    options.raw_socket = true;
116 117 118 119
                }
                return 0;
            }
            break;
120

121 122
        case ZMQ_ROUTER_MANDATORY:
            if (is_int && value >= 0) {
123
                mandatory = (value != 0);
124 125 126
                return 0;
            }
            break;
127

128
        case ZMQ_PROBE_ROUTER:
129
            if (is_int && value >= 0) {
130
                probe_router = (value != 0);
131 132 133
                return 0;
            }
            break;
134 135

        case ZMQ_ROUTER_HANDOVER:
136
            if (is_int && value >= 0) {
137
                handover = (value != 0);
138 139 140
                return 0;
            }
            break;
141

142 143
        default:
            break;
144
    }
145 146
    errno = EINVAL;
    return -1;
147 148
}

149

150
void zmq::router_t::xpipe_terminated (pipe_t *pipe_)
151
{
152 153 154 155 156 157 158
    std::set <pipe_t*>::iterator it = anonymous_pipes.find (pipe_);
    if (it != anonymous_pipes.end ())
        anonymous_pipes.erase (it);
    else {
        outpipes_t::iterator it = outpipes.find (pipe_->get_identity ());
        zmq_assert (it != outpipes.end ());
        outpipes.erase (it);
159
        fq.pipe_terminated (pipe_);
160 161
        if (pipe_ == current_out)
            current_out = NULL;
162
    }
163 164
}

165
void zmq::router_t::xread_activated (pipe_t *pipe_)
166
{
167 168 169 170 171
    std::set <pipe_t*>::iterator it = anonymous_pipes.find (pipe_);
    if (it == anonymous_pipes.end ())
        fq.activated (pipe_);
    else {
        bool identity_ok = identify_peer (pipe_);
172
        if (identity_ok) {
173
            anonymous_pipes.erase (it);
174 175
            fq.attach (pipe_);
        }
176
    }
177 178
}

179
void zmq::router_t::xwrite_activated (pipe_t *pipe_)
Martin Hurton's avatar
Martin Hurton committed
180
{
181 182 183 184 185 186 187 188
    outpipes_t::iterator it;
    for (it = outpipes.begin (); it != outpipes.end (); ++it)
        if (it->second.pipe == pipe_)
            break;

    zmq_assert (it != outpipes.end ());
    zmq_assert (!it->second.active);
    it->second.active = true;
Martin Hurton's avatar
Martin Hurton committed
189 190
}

191
int zmq::router_t::xsend (msg_t *msg_)
192
{
193
    //  If this is the first part of the message it's the ID of the
194 195 196 197
    //  peer to send the message to.
    if (!more_out) {
        zmq_assert (!current_out);

198
        //  If we have malformed message (prefix with no subsequent message)
199
        //  then just silently ignore it.
200
        //  TODO: The connections should be killed instead.
201
        if (msg_->flags () & msg_t::more) {
202 203 204

            more_out = true;

205
            //  Find the pipe associated with the identity stored in the prefix.
206
            //  If there's no such pipe just silently ignore the message, unless
207
            //  router_mandatory is set.
208 209 210 211 212
            blob_t identity ((unsigned char*) msg_->data (), msg_->size ());
            outpipes_t::iterator it = outpipes.find (identity);

            if (it != outpipes.end ()) {
                current_out = it->second.pipe;
213
                if (!current_out->check_write ()) {
214 215
                    it->second.active = false;
                    current_out = NULL;
216 217 218 219 220
                    if (mandatory) {
                        more_out = false;
                        errno = EAGAIN;
                        return -1;
                    }
221
                }
Martin Hurton's avatar
Martin Hurton committed
222 223
            }
            else
224
            if (mandatory) {
225
                more_out = false;
Pieter Hintjens's avatar
Pieter Hintjens committed
226
                errno = EHOSTUNREACH;
227
                return -1;
228
            }
229
        }
230

231 232 233 234
        int rc = msg_->close ();
        errno_assert (rc == 0);
        rc = msg_->init ();
        errno_assert (rc == 0);
235
        return 0;
236 237
    }

Martin Hurton's avatar
Martin Hurton committed
238
    //  Ignore the MORE flag for raw-sock or assert?
239
    if (options.raw_socket)
Martin Hurton's avatar
Martin Hurton committed
240
        msg_->reset_flags (msg_t::more);
241

242
    //  Check whether this is the last part of the message.
243
    more_out = msg_->flags () & msg_t::more ? true : false;
244

245 246
    //  Push the message into the pipe. If there's no out pipe, just drop it.
    if (current_out) {
247 248 249 250

        // Close the remote connection if user has asked to do so
        // by sending zero length message.
        // Pending messages in the pipe will be dropped (on receiving term- ack)
251
        if (raw_socket && msg_->size() == 0) {
Martin Hurton's avatar
Martin Hurton committed
252
            current_out->terminate (false);
253 254
            int rc = msg_->close ();
            errno_assert (rc == 0);
255 256
            rc = msg_->init ();
            errno_assert (rc == 0);
257 258
            current_out = NULL;
            return 0;
Martin Hurton's avatar
Martin Hurton committed
259
        }
260

261
        bool ok = current_out->write (msg_);
262 263 264 265
        if (unlikely (!ok)) {
            // Message failed to send - we must close it ourselves.
            int rc = msg_->close ();
            errno_assert (rc == 0);
266
            current_out = NULL;
267 268 269 270 271
        } else {
          if (!more_out) {
              current_out->flush ();
              current_out = NULL;
          }
272 273 274
        }
    }
    else {
275 276
        int rc = msg_->close ();
        errno_assert (rc == 0);
277
    }
278 279

    //  Detach the message from the data buffer.
280 281
    int rc = msg_->init ();
    errno_assert (rc == 0);
282 283

    return 0;
284 285
}

286
int zmq::router_t::xrecv (msg_t *msg_)
287
{
288 289 290 291 292 293 294 295 296 297 298
    if (prefetched) {
        if (!identity_sent) {
            int rc = msg_->move (prefetched_id);
            errno_assert (rc == 0);
            identity_sent = true;
        }
        else {
            int rc = msg_->move (prefetched_msg);
            errno_assert (rc == 0);
            prefetched = false;
        }
299
        more_in = msg_->flags () & msg_t::more ? true : false;
300 301 302 303 304 305 306 307
 
        if (!more_in) {
            if (terminate_current_in) {
                current_in->terminate (true);
                terminate_current_in = false;
            }
            current_in = NULL;
        }
308 309 310
        return 0;
    }

311
    pipe_t *pipe = NULL;
312
    int rc = fq.recvpipe (msg_, &pipe);
Martin Hurton's avatar
Martin Hurton committed
313 314 315 316 317 318 319 320

    //  It's possible that we receive peer's identity. That happens
    //  after reconnection. The current implementation assumes that
    //  the peer always uses the same identity.
    while (rc == 0 && msg_->is_identity ())
        rc = fq.recvpipe (msg_, &pipe);

    if (rc != 0)
321
        return -1;
322

323
    zmq_assert (pipe != NULL);
324

325
    //  If we are in the middle of reading a message, just return the next part.
326
    if (more_in) {
327
        more_in = msg_->flags () & msg_t::more ? true : false;
328 329 330 331 332 333 334 335 336

        if (!more_in) {
            if (terminate_current_in) {
                current_in->terminate (true);
                terminate_current_in = false;
            }
            current_in = NULL;
        }
    }
337 338 339 340 341 342 343
    else {
        //  We are at the beginning of a message.
        //  Keep the message part we have in the prefetch buffer
        //  and return the ID of the peer instead.
        rc = prefetched_msg.move (*msg_);
        errno_assert (rc == 0);
        prefetched = true;
344
        current_in = pipe;
345 346 347 348 349 350

        blob_t identity = pipe->get_identity ();
        rc = msg_->init_size (identity.size ());
        errno_assert (rc == 0);
        memcpy (msg_->data (), identity.data (), identity.size ());
        msg_->set_flags (msg_t::more);
351 352
        if (prefetched_msg.metadata())
            msg_->set_metadata(prefetched_msg.metadata());
353
        identity_sent = true;
354
    }
355

356
    return 0;
357 358
}

359
int zmq::router_t::rollback (void)
360 361 362 363 364 365 366 367 368
{
    if (current_out) {
        current_out->rollback ();
        current_out = NULL;
        more_out = false;
    }
    return 0;
}

369
bool zmq::router_t::xhas_in ()
370
{
371
    //  If we are in the middle of reading the messages, there are
372 373 374 375
    //  definitely more parts available.
    if (more_in)
        return true;

376
    //  We may already have a message pre-fetched.
377
    if (prefetched)
378
        return true;
379

380 381 382
    //  Try to read the next message.
    //  The message, if read, is kept in the pre-fetch buffer.
    pipe_t *pipe = NULL;
383
    int rc = fq.recvpipe (&prefetched_msg, &pipe);
Martin Hurton's avatar
Martin Hurton committed
384 385 386 387 388 389 390 391

    //  It's possible that we receive peer's identity. That happens
    //  after reconnection. The current implementation assumes that
    //  the peer always uses the same identity.
    //  TODO: handle the situation when the peer changes its identity.
    while (rc == 0 && prefetched_msg.is_identity ())
        rc = fq.recvpipe (&prefetched_msg, &pipe);

392
    if (rc != 0)
393
        return false;
394

Martin Hurton's avatar
Martin Hurton committed
395
    zmq_assert (pipe != NULL);
396 397 398 399 400 401 402 403 404

    blob_t identity = pipe->get_identity ();
    rc = prefetched_id.init_size (identity.size ());
    errno_assert (rc == 0);
    memcpy (prefetched_id.data (), identity.data (), identity.size ());
    prefetched_id.set_flags (msg_t::more);

    prefetched = true;
    identity_sent = false;
405
    current_in = pipe;
406

407
    return true;
408 409
}

410
bool zmq::router_t::xhas_out ()
411
{
412
    //  In theory, ROUTER socket is always ready for writing. Whether actual
413
    //  attempt to write succeeds depends on which pipe the message is going
414 415
    //  to be routed to.
    return true;
416 417
}

418 419 420 421 422
zmq::blob_t zmq::router_t::get_credential () const
{
    return fq.get_credential ();
}

423 424 425 426
bool zmq::router_t::identify_peer (pipe_t *pipe_)
{
    msg_t msg;
    blob_t identity;
427
    bool ok;
428

429 430 431 432
    if (connect_rid.length()) {
        identity = blob_t ((unsigned char*) connect_rid.c_str (),
            connect_rid.length());
        connect_rid.clear ();
433
        outpipes_t::iterator it = outpipes.find (identity);
434
        if (it != outpipes.end ())
435
            zmq_assert(false); //  Not allowed to duplicate an existing rid
436
    }
437
    else
438
    if (options.raw_socket) { //  Always assign identity for raw-socket
439
        unsigned char buf [5];
440
        buf [0] = 0;
441
        put_uint32 (buf + 1, next_rid++);
442
        identity = blob_t (buf, sizeof buf);
Martin Hurton's avatar
Martin Hurton committed
443
    }
Tim M's avatar
Tim M committed
444
    else
445
    if (!options.raw_socket) {
446
        //  Pick up handshake cases and also case where next identity is set
447 448 449
        msg.init ();
        ok = pipe_->read (&msg);
        if (!ok)
450
            return false;
451 452

        if (msg.size () == 0) {
453 454 455
            //  Fall back on the auto-generation
            unsigned char buf [5];
            buf [0] = 0;
456
            put_uint32 (buf + 1, next_rid++);
457 458 459 460 461 462 463 464
            identity = blob_t (buf, sizeof buf);
            msg.close ();
        }
        else {
            identity = blob_t ((unsigned char*) msg.data (), msg.size ());
            outpipes_t::iterator it = outpipes.find (identity);
            msg.close ();

Pieter Hintjens's avatar
Pieter Hintjens committed
465 466 467
            if (it != outpipes.end ()) {
                if (!handover)
                    //  Ignore peers with duplicate ID
468
                    return false;
Pieter Hintjens's avatar
Pieter Hintjens committed
469
                else {
470
                    //  We will allow the new connection to take over this
471
                    //  identity. Temporarily assign a new identity to the
472 473 474
                    //  existing pipe so we can terminate it asynchronously.
                    unsigned char buf [5];
                    buf [0] = 0;
475
                    put_uint32 (buf + 1, next_rid++);
476 477 478
                    blob_t new_identity = blob_t (buf, sizeof buf);

                    it->second.pipe->set_identity (new_identity);
479
                    outpipe_t existing_outpipe =
480
                        {it->second.pipe, it->second.active};
481

482 483 484
                    ok = outpipes.insert (outpipes_t::value_type (
                        new_identity, existing_outpipe)).second;
                    zmq_assert (ok);
485

486 487 488 489
                    //  Remove the existing identity entry to allow the new
                    //  connection to take the identity.
                    outpipes.erase (it);

490 491 492 493
                    if (existing_outpipe.pipe == current_in)
                        terminate_current_in = true;
                    else
                        existing_outpipe.pipe->terminate (true);
494 495
                }
            }
496
        }
497 498 499 500 501 502 503 504 505 506
    }

    pipe_->set_identity (identity);
    //  Add the record into output pipes lookup table
    outpipe_t outpipe = {pipe_, true};
    ok = outpipes.insert (outpipes_t::value_type (identity, outpipe)).second;
    zmq_assert (ok);

    return true;
}