tcp_connecter.cpp 8.55 KB
Newer Older
Martin Sustrik's avatar
Martin Sustrik committed
1
/*
2
    Copyright (c) 2007-2013 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
      const 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 62
    session (session_),
    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);
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 116 117 118 119 120 121 122 123
    //  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 ()
{
    fd_t fd = connect ();
    rm_fd (handle);
    handle_valid = false;

    //  Handle the error condition by attempt to reconnect.
    if (fd == retired_fd) {
        close ();
        add_reconnect_timer();
        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
    //  Create the engine object for this connection.
128
    stream_engine_t *engine = new (std::nothrow)
129
        stream_engine_t (fd, options, endpoint);
130 131 132 133 134 135 136
    alloc_assert (engine);

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

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

138
    socket->event_connected (endpoint, fd);
139 140 141 142 143
}

void zmq::tcp_connecter_t::timer_event (int id_)
{
    zmq_assert (id_ == reconnect_timer_id);
144
    timer_started = false;
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    start_connecting ();
}

void zmq::tcp_connecter_t::start_connecting ()
{
    //  Open the connecting socket.
    int rc = open ();

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

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

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

void zmq::tcp_connecter_t::add_reconnect_timer()
{
179 180
    int rc_ivl = get_new_reconnect_ivl();
    add_timer (rc_ivl, reconnect_timer_id);
181
    socket->event_connect_retried (endpoint, rc_ivl);
182
    timer_started = true;
183 184 185 186 187 188
}

int zmq::tcp_connecter_t::get_new_reconnect_ivl ()
{
    //  The new interval is the current interval + random value.
    int this_interval = current_reconnect_ivl +
189
        (generate_random () % options.reconnect_ivl);
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

    //  Only change the current reconnect interval  if the maximum reconnect
    //  interval was set and if it's larger than the reconnect interval.
    if (options.reconnect_ivl_max > 0 && 
        options.reconnect_ivl_max > options.reconnect_ivl) {

        //  Calculate the next interval
        current_reconnect_ivl = current_reconnect_ivl * 2;
        if(current_reconnect_ivl >= options.reconnect_ivl_max) {
            current_reconnect_ivl = options.reconnect_ivl_max;
        }   
    }
    return this_interval;
}

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

    //  Create the socket.
210
    s = open_socket (addr->resolved.tcp_addr->family (), SOCK_STREAM, IPPROTO_TCP);
211
#ifdef ZMQ_HAVE_WINDOWS
212
    if (s == INVALID_SOCKET) {
213
        errno = wsa_error_to_errno (WSAGetLastError ());
214 215
        return -1;
    }
216 217 218 219
#else
    if (s == -1)
        return -1;
#endif
unknown's avatar
unknown committed
220

221 222
    //  On some systems, IPv4 mapping in IPv6 sockets is disabled by default.
    //  Switch it on in such cases.
223
    if (addr->resolved.tcp_addr->family () == AF_INET6)
224
        enable_ipv4_mapping (s);
225

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

229 230 231 232 233 234
    //  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);

unknown's avatar
unknown committed
235
    //  Connect to the remote peer.
236 237 238
    int rc = ::connect (
        s, addr->resolved.tcp_addr->addr (),
        addr->resolved.tcp_addr->addrlen ());
unknown's avatar
unknown committed
239 240 241 242 243

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

244
    //  Translate error codes indicating asynchronous connect has been
245
    //  launched to a uniform EINPROGRESS.
246
#ifdef ZMQ_HAVE_WINDOWS
247 248
    const int error_code = WSAGetLastError ();
    if (error_code == WSAEINPROGRESS || error_code == WSAEWOULDBLOCK)
249
        errno = EINPROGRESS;
250 251
    else
        errno = wsa_error_to_errno (error_code);
252
#else
253
    if (errno == EINTR)
254
        errno = EINPROGRESS;
255
#endif
unknown's avatar
unknown committed
256 257 258
    return -1;
}

259 260
zmq::fd_t zmq::tcp_connecter_t::connect ()
{
Pieter Hintjens's avatar
Pieter Hintjens committed
261
    //  Async connect has finished. Check whether an error occurred
262
    int err = 0;
263 264 265 266 267 268
#if defined ZMQ_HAVE_HPUX
    int len = sizeof (err);
#else
    socklen_t len = sizeof (err);
#endif

269
    int rc = getsockopt (s, SOL_SOCKET, SO_ERROR, (char*) &err, &len);
270 271 272 273

    //  Assert if the error was caused by 0MQ bug.
    //  Networking problems are OK. No need to assert.
#ifdef ZMQ_HAVE_WINDOWS
274 275
    zmq_assert (rc == 0);
    if (err != 0) {
Pieter Hintjens's avatar
Pieter Hintjens committed
276 277 278 279 280 281 282
        if (err == WSAECONNREFUSED ||
            err == WSAETIMEDOUT ||
            err == WSAECONNABORTED ||
            err == WSAEHOSTUNREACH ||
            err == WSAENETUNREACH ||
            err == WSAENETDOWN ||
            err == WSAEINVAL)
283 284
            return retired_fd;
        wsa_assert_no (err);
285
    }
Brett Cameron's avatar
Brett Cameron committed
286
#else
Martin Sustrik's avatar
Martin Sustrik committed
287 288 289 290 291 292 293

    //  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
294 295 296 297 298 299 300
        errno_assert (
            errno == ECONNREFUSED ||
            errno == ECONNRESET ||
            errno == ETIMEDOUT ||
            errno == EHOSTUNREACH ||
            errno == ENETUNREACH ||
            errno == ENETDOWN ||
Pieter Hintjens's avatar
Pieter Hintjens committed
301
            errno == EINVAL);
Martin Sustrik's avatar
Martin Sustrik committed
302 303
        return retired_fd;
    }
304
#endif
Martin Sustrik's avatar
Martin Sustrik committed
305

306
    //  Return the newly connected socket.
Martin Sustrik's avatar
Martin Sustrik committed
307 308 309 310 311
    fd_t result = s;
    s = retired_fd;
    return result;
}

312 313 314 315 316 317 318 319 320
void zmq::tcp_connecter_t::close ()
{
    zmq_assert (s != retired_fd);
#ifdef ZMQ_HAVE_WINDOWS
    int rc = closesocket (s);
    wsa_assert (rc != SOCKET_ERROR);
#else
    int rc = ::close (s);
    errno_assert (rc == 0);
Martin Sustrik's avatar
Martin Sustrik committed
321
#endif
322
    socket->event_closed (endpoint, s);
323 324
    s = retired_fd;
}