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

4
    This file is part of libzmq, the ZeroMQ core engine in C++.
Martin Sustrik's avatar
Martin Sustrik committed
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
Martin Sustrik's avatar
Martin Sustrik committed
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.
Martin Sustrik's avatar
Martin Sustrik committed
25

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

30
#include "precompiled.hpp"
31
#include <new>
32 33
#include <string>

34
#include "macros.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
35
#include "tcp_connecter.hpp"
36
#include "io_thread.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
37
#include "err.hpp"
38
#include "ip.hpp"
39
#include "tcp.hpp"
40 41
#include "address.hpp"
#include "tcp_address.hpp"
42
#include "session_base.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
43

44
#if !defined ZMQ_HAVE_WINDOWS
45 46 47 48 49 50 51 52
#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>
53 54 55
#ifdef ZMQ_HAVE_VXWORKS
#include <sockLib.h>
#endif
56 57 58 59
#ifdef ZMQ_HAVE_OPENVMS
#include <ioctl.h>
#endif
#endif
Martin Sustrik's avatar
Martin Sustrik committed
60

61 62 63 64
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif

65
zmq::tcp_connecter_t::tcp_connecter_t (class io_thread_t *io_thread_,
66 67 68 69
                                       class session_base_t *session_,
                                       const options_t &options_,
                                       address_t *addr_,
                                       bool delayed_start_) :
70 71 72
    stream_connecter_base_t (
      io_thread_, session_, options_, addr_, delayed_start_),
    _connect_timer_started (false)
unknown's avatar
unknown committed
73
{
74
    zmq_assert (_addr->protocol == protocol_name::tcp);
unknown's avatar
unknown committed
75 76 77 78
}

zmq::tcp_connecter_t::~tcp_connecter_t ()
{
79
    zmq_assert (!_connect_timer_started);
unknown's avatar
unknown committed
80 81
}

82 83
void zmq::tcp_connecter_t::process_term (int linger_)
{
84
    if (_connect_timer_started) {
85
        cancel_timer (connect_timer_id);
86
        _connect_timer_started = false;
87 88
    }

89
    stream_connecter_base_t::process_term (linger_);
90 91
}

92 93
void zmq::tcp_connecter_t::out_event ()
{
94
    if (_connect_timer_started) {
95
        cancel_timer (connect_timer_id);
96
        _connect_timer_started = false;
97 98
    }

99 100 101
    //  TODO this is still very similar to (t)ipc_connecter_t, maybe the
    //  differences can be factored out

102
    rm_handle ();
103

Martin Hurton's avatar
Martin Hurton committed
104
    const fd_t fd = connect ();
105

106
    //  Handle the error condition by attempt to reconnect.
107
    if (fd == retired_fd || !tune_socket (fd)) {
108 109 110 111
        close ();
        add_reconnect_timer ();
        return;
    }
112

113
    create_engine (fd, get_socket_name<tcp_address_t> (fd, socket_end_local));
114 115 116 117
}

void zmq::tcp_connecter_t::timer_event (int id_)
{
118
    if (id_ == connect_timer_id) {
119
        _connect_timer_started = false;
120
        rm_handle ();
121 122
        close ();
        add_reconnect_timer ();
123 124
    } else
        stream_connecter_base_t::timer_event (id_);
125 126 127 128 129
}

void zmq::tcp_connecter_t::start_connecting ()
{
    //  Open the connecting socket.
Martin Hurton's avatar
Martin Hurton committed
130
    const int rc = open ();
131 132 133

    //  Connect may succeed in synchronous manner.
    if (rc == 0) {
134
        _handle = add_fd (_s);
135 136 137
        out_event ();
    }

138
    //  Connection establishment may be delayed. Poll for its completion.
139
    else if (rc == -1 && errno == EINPROGRESS) {
140 141
        _handle = add_fd (_s);
        set_pollout (_handle);
142 143
        _socket->event_connect_delayed (
          make_unconnected_connect_endpoint_pair (_endpoint), zmq_errno ());
144 145 146

        //  add userspace connect timeout
        add_connect_timer ();
147 148 149
    }

    //  Handle any other error condition by eventual reconnect.
150
    else {
151
        if (_s != retired_fd)
152
            close ();
153 154
        add_reconnect_timer ();
    }
155 156
}

157 158 159 160
void zmq::tcp_connecter_t::add_connect_timer ()
{
    if (options.connect_timeout > 0) {
        add_timer (options.connect_timeout, connect_timer_id);
161
        _connect_timer_started = true;
162 163 164
    }
}

unknown's avatar
unknown committed
165 166
int zmq::tcp_connecter_t::open ()
{
167
    zmq_assert (_s == retired_fd);
unknown's avatar
unknown committed
168

169
    //  Resolve the address
170 171
    if (_addr->resolved.tcp_addr != NULL) {
        LIBZMQ_DELETE (_addr->resolved.tcp_addr);
172 173
    }

174 175
    _addr->resolved.tcp_addr = new (std::nothrow) tcp_address_t ();
    alloc_assert (_addr->resolved.tcp_addr);
176
    _s = tcp_open_socket (_addr->address.c_str (), options, false, true,
177 178
                          _addr->resolved.tcp_addr);
    if (_s == retired_fd) {
179 180
        //  TODO we should emit some event in this case!

181
        LIBZMQ_DELETE (_addr->resolved.tcp_addr);
182 183
        return -1;
    }
184
    zmq_assert (_addr->resolved.tcp_addr != NULL);
185

186 187 188
    // Set the socket to non-blocking mode so that we get async connect().
    unblock_socket (_s);

189
    const tcp_address_t *const tcp_addr = _addr->resolved.tcp_addr;
190

191
    int rc;
192

193
    // Set a source address for conversations
Martin Hurton's avatar
Martin Hurton committed
194
    if (tcp_addr->has_src_addr ()) {
195 196 197 198
        //  Allow reusing of the address, to connect to different servers
        //  using the same source port on the client.
        int flag = 1;
#ifdef ZMQ_HAVE_WINDOWS
199
        rc = setsockopt (_s, SOL_SOCKET, SO_REUSEADDR,
200
                         reinterpret_cast<const char *> (&flag), sizeof (int));
201
        wsa_assert (rc != SOCKET_ERROR);
202
#elif defined ZMQ_HAVE_VXWORKS
203
        rc = setsockopt (_s, SOL_SOCKET, SO_REUSEADDR, (char *) &flag,
204 205
                         sizeof (int));
        errno_assert (rc == 0);
206
#else
207
        rc = setsockopt (_s, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int));
208 209 210
        errno_assert (rc == 0);
#endif

211
#if defined ZMQ_HAVE_VXWORKS
212
        rc = ::bind (_s, (sockaddr *) tcp_addr->src_addr (),
213 214
                     tcp_addr->src_addrlen ());
#else
215
        rc = ::bind (_s, tcp_addr->src_addr (), tcp_addr->src_addrlen ());
216
#endif
Martin Hurton's avatar
Martin Hurton committed
217
        if (rc == -1)
218 219 220
            return -1;
    }

221
    //  Connect to the remote peer.
222
#if defined ZMQ_HAVE_VXWORKS
223
    rc = ::connect (_s, (sockaddr *) tcp_addr->addr (), tcp_addr->addrlen ());
224
#else
225
    rc = ::connect (_s, tcp_addr->addr (), tcp_addr->addrlen ());
226
#endif
227
    //  Connect was successful immediately.
228
    if (rc == 0) {
unknown's avatar
unknown committed
229
        return 0;
230
    }
unknown's avatar
unknown committed
231

232 233
    //  Translate error codes indicating asynchronous connect has been
    //  launched to a uniform EINPROGRESS.
234
#ifdef ZMQ_HAVE_WINDOWS
235
    const int last_error = WSAGetLastError ();
236
    if (last_error == WSAEINPROGRESS || last_error == WSAEWOULDBLOCK)
237
        errno = EINPROGRESS;
238
    else
239
        errno = wsa_error_to_errno (last_error);
240
#else
241
    if (errno == EINTR)
242
        errno = EINPROGRESS;
243
#endif
unknown's avatar
unknown committed
244 245 246
    return -1;
}

247 248
zmq::fd_t zmq::tcp_connecter_t::connect ()
{
Pieter Hintjens's avatar
Pieter Hintjens committed
249
    //  Async connect has finished. Check whether an error occurred
250
    int err = 0;
251
#if defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_VXWORKS
Martin Hurton's avatar
Martin Hurton committed
252
    int len = sizeof err;
253
#else
Martin Hurton's avatar
Martin Hurton committed
254
    socklen_t len = sizeof err;
255 256
#endif

257
    const int rc = getsockopt (_s, SOL_SOCKET, SO_ERROR,
258
                               reinterpret_cast<char *> (&err), &len);
259 260 261 262

    //  Assert if the error was caused by 0MQ bug.
    //  Networking problems are OK. No need to assert.
#ifdef ZMQ_HAVE_WINDOWS
263 264
    zmq_assert (rc == 0);
    if (err != 0) {
265 266
        if (err == WSAEBADF || err == WSAENOPROTOOPT || err == WSAENOTSOCK
            || err == WSAENOBUFS) {
267 268
            wsa_assert_no (err);
        }
Martin Hurton's avatar
Martin Hurton committed
269
        return retired_fd;
270
    }
Brett Cameron's avatar
Brett Cameron committed
271
#else
Martin Sustrik's avatar
Martin Sustrik committed
272 273 274 275 276 277
    //  Following code should handle both Berkeley-derived socket
    //  implementations and Solaris.
    if (rc == -1)
        err = errno;
    if (err != 0) {
        errno = err;
278
#if !defined(TARGET_OS_IPHONE) || !TARGET_OS_IPHONE
279 280
        errno_assert (errno != EBADF && errno != ENOPROTOOPT
                      && errno != ENOTSOCK && errno != ENOBUFS);
281 282 283 284
#else
        errno_assert (errno != ENOPROTOOPT && errno != ENOTSOCK
                      && errno != ENOBUFS);
#endif
Martin Sustrik's avatar
Martin Sustrik committed
285 286
        return retired_fd;
    }
287
#endif
Martin Sustrik's avatar
Martin Sustrik committed
288

289
    //  Return the newly connected socket.
290 291
    const fd_t result = _s;
    _s = retired_fd;
Martin Sustrik's avatar
Martin Sustrik committed
292 293 294
    return result;
}

295
bool zmq::tcp_connecter_t::tune_socket (const fd_t fd_)
296
{
297
    const int rc = tune_tcp_socket (fd_)
298
                   | tune_tcp_keepalives (
299
                       fd_, options.tcp_keepalive, options.tcp_keepalive_cnt,
300
                       options.tcp_keepalive_idle, options.tcp_keepalive_intvl)
301
                   | tune_tcp_maxrt (fd_, options.tcp_maxrt);
302 303
    return rc == 0;
}