tcp_connecter.cpp 9.62 KB
Newer Older
Martin Sustrik's avatar
Martin Sustrik committed
1
/*
2
    Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file
Martin Sustrik's avatar
Martin Sustrik committed
3 4 5 6

    This file is part of 0MQ.

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

16
    You should have received a copy of the GNU Lesser General Public License
Martin Sustrik's avatar
Martin Sustrik committed
17 18 19
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

20
#include <new>
21 22
#include <string>

Martin Sustrik's avatar
Martin Sustrik committed
23
#include "tcp_connecter.hpp"
24
#include "stream_engine.hpp"
25
#include "io_thread.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
26
#include "platform.hpp"
27
#include "random.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
28
#include "err.hpp"
29
#include "ip.hpp"
30
#include "tcp.hpp"
31 32
#include "address.hpp"
#include "tcp_address.hpp"
33
#include "session_base.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
34

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#else
#include <unistd.h>
#include <sys/types.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
#endif
Martin Sustrik's avatar
Martin Sustrik committed
50

51
zmq::tcp_connecter_t::tcp_connecter_t (class io_thread_t *io_thread_,
52
      class session_base_t *session_, const options_t &options_,
53
      address_t *addr_, bool delayed_start_) :
54 55
    own_t (io_thread_, options_),
    io_object_t (io_thread_),
56
    addr (addr_),
57 58
    s (retired_fd),
    handle_valid (false),
59 60
    delayed_start (delayed_start_),
    timer_started (false),
61
    session (session_),
Martin Hurton's avatar
Martin Hurton committed
62
    current_reconnect_ivl (options.reconnect_ivl)
unknown's avatar
unknown committed
63
{
64 65
    zmq_assert (addr);
    zmq_assert (addr->protocol == "tcp");
66
    addr->to_string (endpoint);
Martin Hurton's avatar
Martin Hurton committed
67
    socket = session->get_socket ();
unknown's avatar
unknown committed
68 69 70 71
}

zmq::tcp_connecter_t::~tcp_connecter_t ()
{
72
    zmq_assert (!timer_started);
73 74
    zmq_assert (!handle_valid);
    zmq_assert (s == retired_fd);
unknown's avatar
unknown committed
75 76
}

77 78
void zmq::tcp_connecter_t::process_plug ()
{
79 80
    if (delayed_start)
        add_reconnect_timer ();
81 82 83 84
    else
        start_connecting ();
}

85 86
void zmq::tcp_connecter_t::process_term (int linger_)
{
87
    if (timer_started) {
88
        cancel_timer (reconnect_timer_id);
89
        timer_started = false;
90 91 92 93 94 95 96 97 98 99 100 101 102
    }

    if (handle_valid) {
        rm_fd (handle);
        handle_valid = false;
    }

    if (s != retired_fd)
        close ();

    own_t::process_term (linger_);
}

103 104
void zmq::tcp_connecter_t::in_event ()
{
105
    //  We are not polling for incoming data, so we are actually called
106 107 108 109 110 111 112 113 114 115
    //  because of error here. However, we can get error on out event as well
    //  on some platforms, so we'll simply handle both events in the same way.
    out_event ();
}

void zmq::tcp_connecter_t::out_event ()
{
    rm_fd (handle);
    handle_valid = false;

Martin Hurton's avatar
Martin Hurton committed
116
    const fd_t fd = connect ();
117 118 119
    //  Handle the error condition by attempt to reconnect.
    if (fd == retired_fd) {
        close ();
Martin Hurton's avatar
Martin Hurton committed
120
        add_reconnect_timer ();
121 122 123
        return;
    }

124
    tune_tcp_socket (fd);
125
    tune_tcp_keepalives (fd, options.tcp_keepalive, options.tcp_keepalive_cnt, options.tcp_keepalive_idle, options.tcp_keepalive_intvl);
126

127
    // remember our fd for ZMQ_SRCFD in messages
Martin Hurton's avatar
Martin Hurton committed
128
    socket->set_fd (fd);
129

130
    //  Create the engine object for this connection.
131
    stream_engine_t *engine = new (std::nothrow)
132
        stream_engine_t (fd, options, endpoint);
133 134 135 136 137 138 139
    alloc_assert (engine);

    //  Attach the engine to the corresponding session object.
    send_attach (session, engine);

    //  Shut the connecter down.
    terminate ();
140

141
    socket->event_connected (endpoint, fd);
142 143 144 145 146
}

void zmq::tcp_connecter_t::timer_event (int id_)
{
    zmq_assert (id_ == reconnect_timer_id);
147
    timer_started = false;
148 149 150 151 152 153
    start_connecting ();
}

void zmq::tcp_connecter_t::start_connecting ()
{
    //  Open the connecting socket.
Martin Hurton's avatar
Martin Hurton committed
154
    const int rc = open ();
155 156 157 158 159 160 161 162

    //  Connect may succeed in synchronous manner.
    if (rc == 0) {
        handle = add_fd (s);
        handle_valid = true;
        out_event ();
    }

163
    //  Connection establishment may be delayed. Poll for its completion.
164 165
    else
    if (rc == -1 && errno == EINPROGRESS) {
166 167 168
        handle = add_fd (s);
        handle_valid = true;
        set_pollout (handle);
169
        socket->event_connect_delayed (endpoint, zmq_errno());
170 171 172
    }

    //  Handle any other error condition by eventual reconnect.
173
    else {
174 175
        if (s != retired_fd)
            close ();
176 177
        add_reconnect_timer ();
    }
178 179
}

Martin Hurton's avatar
Martin Hurton committed
180
void zmq::tcp_connecter_t::add_reconnect_timer ()
181
{
Martin Hurton's avatar
Martin Hurton committed
182 183 184
    const int interval = get_new_reconnect_ivl ();
    add_timer (interval, reconnect_timer_id);
    socket->event_connect_retried (endpoint, interval);
185
    timer_started = true;
186 187 188 189 190
}

int zmq::tcp_connecter_t::get_new_reconnect_ivl ()
{
    //  The new interval is the current interval + random value.
Martin Hurton's avatar
Martin Hurton committed
191 192
    const int interval = current_reconnect_ivl +
        generate_random () % options.reconnect_ivl;
193 194 195

    //  Only change the current reconnect interval  if the maximum reconnect
    //  interval was set and if it's larger than the reconnect interval.
196
    if (options.reconnect_ivl_max > 0 &&
Martin Hurton's avatar
Martin Hurton committed
197
        options.reconnect_ivl_max > options.reconnect_ivl)
198
        //  Calculate the next interval
Martin Hurton's avatar
Martin Hurton committed
199 200 201
        current_reconnect_ivl =
            std::min (current_reconnect_ivl * 2, options.reconnect_ivl_max);
    return interval;
202 203
}

unknown's avatar
unknown committed
204 205 206 207
int zmq::tcp_connecter_t::open ()
{
    zmq_assert (s == retired_fd);

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    //  Resolve the address
    if (addr->resolved.tcp_addr != NULL) {
        delete addr->resolved.tcp_addr;
        addr->resolved.tcp_addr = NULL;
    }

    addr->resolved.tcp_addr = new (std::nothrow) tcp_address_t ();
    alloc_assert (addr->resolved.tcp_addr);
    int rc = addr->resolved.tcp_addr->resolve (
        addr->address.c_str (), false, options.ipv6);
    if (rc != 0) {
        delete addr->resolved.tcp_addr;
        addr->resolved.tcp_addr = NULL;
        return -1;
    }
    zmq_assert (addr->resolved.tcp_addr != NULL);
Martin Hurton's avatar
Martin Hurton committed
224
    tcp_address_t * const tcp_addr = addr->resolved.tcp_addr;
225

unknown's avatar
unknown committed
226
    //  Create the socket.
Martin Hurton's avatar
Martin Hurton committed
227
    s = open_socket (tcp_addr->family (), SOCK_STREAM, IPPROTO_TCP);
228
#ifdef ZMQ_HAVE_WINDOWS
229
    if (s == INVALID_SOCKET) {
230
        errno = wsa_error_to_errno (WSAGetLastError ());
231 232
        return -1;
    }
233 234 235 236
#else
    if (s == -1)
        return -1;
#endif
unknown's avatar
unknown committed
237

238 239
    //  On some systems, IPv4 mapping in IPv6 sockets is disabled by default.
    //  Switch it on in such cases.
Martin Hurton's avatar
Martin Hurton committed
240
    if (tcp_addr->family () == AF_INET6)
241
        enable_ipv4_mapping (s);
242

243 244 245 246
    // Set the IP Type-Of-Service priority for this socket
    if (options.tos != 0)
        set_ip_type_of_service (s, options.tos);

247 248
    // Set the socket to non-blocking mode so that we get async connect().
    unblock_socket (s);
unknown's avatar
unknown committed
249

250 251 252 253 254 255
    //  Set the socket buffer limits for the underlying socket.
    if (options.sndbuf != 0)
        set_tcp_send_buffer (s, options.sndbuf);
    if (options.rcvbuf != 0)
        set_tcp_receive_buffer (s, options.rcvbuf);

256 257 258 259
    // Set the IP Type-Of-Service for the underlying socket
    if (options.tos != 0)
        set_ip_type_of_service (s, options.tos);

260
    // Set a source address for conversations
Martin Hurton's avatar
Martin Hurton committed
261 262 263
    if (tcp_addr->has_src_addr ()) {
        rc = ::bind (s, tcp_addr->src_addr (), tcp_addr->src_addrlen ());
        if (rc == -1)
264 265 266
            return -1;
    }

unknown's avatar
unknown committed
267
    //  Connect to the remote peer.
Martin Hurton's avatar
Martin Hurton committed
268
    rc = ::connect (s, tcp_addr->addr (), tcp_addr->addrlen ());
unknown's avatar
unknown committed
269 270 271 272 273

    //  Connect was successfull immediately.
    if (rc == 0)
        return 0;

274
    //  Translate error codes indicating asynchronous connect has been
275
    //  launched to a uniform EINPROGRESS.
276
#ifdef ZMQ_HAVE_WINDOWS
277 278
    const int error_code = WSAGetLastError ();
    if (error_code == WSAEINPROGRESS || error_code == WSAEWOULDBLOCK)
279
        errno = EINPROGRESS;
280 281
    else
        errno = wsa_error_to_errno (error_code);
282
#else
283
    if (errno == EINTR)
284
        errno = EINPROGRESS;
285
#endif
unknown's avatar
unknown committed
286 287 288
    return -1;
}

289 290
zmq::fd_t zmq::tcp_connecter_t::connect ()
{
Pieter Hintjens's avatar
Pieter Hintjens committed
291
    //  Async connect has finished. Check whether an error occurred
292
    int err = 0;
Martin Hurton's avatar
Martin Hurton committed
293 294
#ifdef ZMQ_HAVE_HPUX
    int len = sizeof err;
295
#else
Martin Hurton's avatar
Martin Hurton committed
296
    socklen_t len = sizeof err;
297 298
#endif

Martin Hurton's avatar
Martin Hurton committed
299
    const int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char*) &err, &len);
300 301 302 303

    //  Assert if the error was caused by 0MQ bug.
    //  Networking problems are OK. No need to assert.
#ifdef ZMQ_HAVE_WINDOWS
304 305
    zmq_assert (rc == 0);
    if (err != 0) {
306 307 308 309 310 311 312 313 314 315 316 317
        if (err != WSAECONNREFUSED
            && err != WSAETIMEDOUT
            && err != WSAECONNABORTED
            && err != WSAEHOSTUNREACH
            && err != WSAENETUNREACH
            && err != WSAENETDOWN
            && err != WSAEACCES
            && err != WSAEINVAL
            && err != WSAEADDRINUSE)
        {
            wsa_assert_no (err);
        }
Martin Hurton's avatar
Martin Hurton committed
318
        return retired_fd;
319
    }
Brett Cameron's avatar
Brett Cameron committed
320
#else
Martin Sustrik's avatar
Martin Sustrik committed
321 322 323 324 325 326
    //  Following code should handle both Berkeley-derived socket
    //  implementations and Solaris.
    if (rc == -1)
        err = errno;
    if (err != 0) {
        errno = err;
Pieter Hintjens's avatar
Pieter Hintjens committed
327 328 329 330 331 332 333
        errno_assert (
            errno == ECONNREFUSED ||
            errno == ECONNRESET ||
            errno == ETIMEDOUT ||
            errno == EHOSTUNREACH ||
            errno == ENETUNREACH ||
            errno == ENETDOWN ||
Pieter Hintjens's avatar
Pieter Hintjens committed
334
            errno == EINVAL);
Martin Sustrik's avatar
Martin Sustrik committed
335 336
        return retired_fd;
    }
337
#endif
Martin Sustrik's avatar
Martin Sustrik committed
338

339
    //  Return the newly connected socket.
Martin Hurton's avatar
Martin Hurton committed
340
    const fd_t result = s;
Martin Sustrik's avatar
Martin Sustrik committed
341 342 343 344
    s = retired_fd;
    return result;
}

345 346 347 348
void zmq::tcp_connecter_t::close ()
{
    zmq_assert (s != retired_fd);
#ifdef ZMQ_HAVE_WINDOWS
Martin Hurton's avatar
Martin Hurton committed
349
    const int rc = closesocket (s);
350 351
    wsa_assert (rc != SOCKET_ERROR);
#else
Martin Hurton's avatar
Martin Hurton committed
352
    const int rc = ::close (s);
353
    errno_assert (rc == 0);
Martin Sustrik's avatar
Martin Sustrik committed
354
#endif
355
    socket->event_closed (endpoint, s);
356 357
    s = retired_fd;
}