tcp.cpp 11.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 27 28 29

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

30
#include "precompiled.hpp"
31
#include "macros.hpp"
32 33 34 35
#include "ip.hpp"
#include "tcp.hpp"
#include "err.hpp"

36
#if !defined ZMQ_HAVE_WINDOWS
37 38 39 40 41
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
42 43 44
#ifdef ZMQ_HAVE_VXWORKS
#include <sockLib.h>
#endif
45 46 47 48 49 50
#endif

#if defined ZMQ_HAVE_OPENVMS
#include <ioctl.h>
#endif

51
int zmq::tune_tcp_socket (fd_t s_)
52 53 54 55 56
{
    //  Disable Nagle's algorithm. We are doing data batching on 0MQ level,
    //  so using Nagle wouldn't improve throughput in anyway, but it would
    //  hurt latency.
    int nodelay = 1;
57 58
    int rc = setsockopt (s_, IPPROTO_TCP, TCP_NODELAY, (char *) &nodelay,
                         sizeof (int));
59
    tcp_assert_tuning_error (s_, rc);
60 61
    if (rc != 0)
        return rc;
62 63

#ifdef ZMQ_HAVE_OPENVMS
64
    //  Disable delayed acknowledgements as they hurt latency significantly.
65
    int nodelack = 1;
66 67
    rc = setsockopt (s_, IPPROTO_TCP, TCP_NODELACK, (char *) &nodelack,
                     sizeof (int));
68
    tcp_assert_tuning_error (s_, rc);
69
#endif
70
    return rc;
71 72
}

73
int zmq::set_tcp_send_buffer (fd_t sockfd_, int bufsize_)
74 75
{
    const int rc = setsockopt (sockfd_, SOL_SOCKET, SO_SNDBUF,
76
                               (char *) &bufsize_, sizeof bufsize_);
77
    tcp_assert_tuning_error (sockfd_, rc);
78
    return rc;
79 80
}

81
int zmq::set_tcp_receive_buffer (fd_t sockfd_, int bufsize_)
82 83
{
    const int rc = setsockopt (sockfd_, SOL_SOCKET, SO_RCVBUF,
84
                               (char *) &bufsize_, sizeof bufsize_);
85
    tcp_assert_tuning_error (sockfd_, rc);
86
    return rc;
87 88
}

89 90 91 92 93
int zmq::tune_tcp_keepalives (fd_t s_,
                              int keepalive_,
                              int keepalive_cnt_,
                              int keepalive_idle_,
                              int keepalive_intvl_)
94
{
95
    // These options are used only under certain #ifdefs below.
96 97 98 99
    LIBZMQ_UNUSED (keepalive_);
    LIBZMQ_UNUSED (keepalive_cnt_);
    LIBZMQ_UNUSED (keepalive_idle_);
    LIBZMQ_UNUSED (keepalive_intvl_);
100 101

    // If none of the #ifdefs apply, then s_ is unused.
102
    LIBZMQ_UNUSED (s_);
103

104 105
    //  Tuning TCP keep-alives if platform allows it
    //  All values = -1 means skip and leave it for OS
106
#ifdef ZMQ_HAVE_WINDOWS
107 108 109
    if (keepalive_ != -1) {
        tcp_keepalive keepalive_opts;
        keepalive_opts.onoff = keepalive_;
110 111 112 113
        keepalive_opts.keepalivetime =
          keepalive_idle_ != -1 ? keepalive_idle_ * 1000 : 7200000;
        keepalive_opts.keepaliveinterval =
          keepalive_intvl_ != -1 ? keepalive_intvl_ * 1000 : 1000;
114
        DWORD num_bytes_returned;
115
        int rc = WSAIoctl (s_, SIO_KEEPALIVE_VALS, &keepalive_opts,
116 117
                           sizeof (keepalive_opts), NULL, 0,
                           &num_bytes_returned, NULL, NULL);
118
        tcp_assert_tuning_error (s_, rc);
119 120
        if (rc == SOCKET_ERROR)
            return rc;
121
    }
122
#else
123 124
#ifdef ZMQ_HAVE_SO_KEEPALIVE
    if (keepalive_ != -1) {
125 126
        int rc = setsockopt (s_, SOL_SOCKET, SO_KEEPALIVE, (char *) &keepalive_,
                             sizeof (int));
127
        tcp_assert_tuning_error (s_, rc);
128 129
        if (rc != 0)
            return rc;
130 131 132

#ifdef ZMQ_HAVE_TCP_KEEPCNT
        if (keepalive_cnt_ != -1) {
133 134
            int rc = setsockopt (s_, IPPROTO_TCP, TCP_KEEPCNT, &keepalive_cnt_,
                                 sizeof (int));
135
            tcp_assert_tuning_error (s_, rc);
136 137
            if (rc != 0)
                return rc;
138 139 140 141 142
        }
#endif // ZMQ_HAVE_TCP_KEEPCNT

#ifdef ZMQ_HAVE_TCP_KEEPIDLE
        if (keepalive_idle_ != -1) {
143
            int rc = setsockopt (s_, IPPROTO_TCP, TCP_KEEPIDLE,
144
                                 &keepalive_idle_, sizeof (int));
145
            tcp_assert_tuning_error (s_, rc);
146 147
            if (rc != 0)
                return rc;
148 149 150 151
        }
#else // ZMQ_HAVE_TCP_KEEPIDLE
#ifdef ZMQ_HAVE_TCP_KEEPALIVE
        if (keepalive_idle_ != -1) {
152
            int rc = setsockopt (s_, IPPROTO_TCP, TCP_KEEPALIVE,
153
                                 &keepalive_idle_, sizeof (int));
154
            tcp_assert_tuning_error (s_, rc);
155 156
            if (rc != 0)
                return rc;
157 158 159 160 161 162
        }
#endif // ZMQ_HAVE_TCP_KEEPALIVE
#endif // ZMQ_HAVE_TCP_KEEPIDLE

#ifdef ZMQ_HAVE_TCP_KEEPINTVL
        if (keepalive_intvl_ != -1) {
163
            int rc = setsockopt (s_, IPPROTO_TCP, TCP_KEEPINTVL,
164
                                 &keepalive_intvl_, sizeof (int));
165
            tcp_assert_tuning_error (s_, rc);
166 167
            if (rc != 0)
                return rc;
168 169 170 171
        }
#endif // ZMQ_HAVE_TCP_KEEPINTVL
    }
#endif // ZMQ_HAVE_SO_KEEPALIVE
172
#endif // ZMQ_HAVE_WINDOWS
173

174
    return 0;
175
}
176

177
int zmq::tune_tcp_maxrt (fd_t sockfd_, int timeout_)
178 179
{
    if (timeout_ <= 0)
180
        return 0;
181

182 183
    LIBZMQ_UNUSED (sockfd_);

184
#if defined(ZMQ_HAVE_WINDOWS) && defined(TCP_MAXRT)
185
    // msdn says it's supported in >= Vista, >= Windows Server 2003
186 187 188
    timeout_ /= 1000; // in seconds
    int rc = setsockopt (sockfd_, IPPROTO_TCP, TCP_MAXRT, (char *) &timeout_,
                         sizeof (timeout_));
189
    tcp_assert_tuning_error (sockfd_, rc);
190
    return rc;
191
// FIXME: should be ZMQ_HAVE_TCP_USER_TIMEOUT
192
#elif defined(TCP_USER_TIMEOUT)
193
    int rc = setsockopt (sockfd_, IPPROTO_TCP, TCP_USER_TIMEOUT, &timeout_,
194
                         sizeof (timeout_));
195
    tcp_assert_tuning_error (sockfd_, rc);
196
    return rc;
197
#endif
198
    return 0;
199 200
}

201
int zmq::tcp_write (fd_t s_, const void *data_, size_t size_)
202 203 204
{
#ifdef ZMQ_HAVE_WINDOWS

205
    int nbytes = send (s_, (char *) data_, (int) size_, 0);
206 207 208

    //  If not a single byte can be written to the socket in non-blocking mode
    //  we'll get an error (this may happen during the speculative write).
209
    const int last_error = WSAGetLastError ();
210
    if (nbytes == SOCKET_ERROR && last_error == WSAEWOULDBLOCK)
211 212 213
        return 0;

    //  Signalise peer failure.
214 215 216 217
    if (nbytes == SOCKET_ERROR
        && (last_error == WSAENETDOWN || last_error == WSAENETRESET
            || last_error == WSAEHOSTUNREACH || last_error == WSAECONNABORTED
            || last_error == WSAETIMEDOUT || last_error == WSAECONNRESET))
218 219
        return -1;

220 221 222
    //  Circumvent a Windows bug:
    //  See https://support.microsoft.com/en-us/kb/201213
    //  See https://zeromq.jira.com/browse/LIBZMQ-195
223
    if (nbytes == SOCKET_ERROR && last_error == WSAENOBUFS)
224 225
        return 0;

226 227 228 229
    wsa_assert (nbytes != SOCKET_ERROR);
    return nbytes;

#else
230
    ssize_t nbytes = send (s_, (char *) data_, size_, 0);
231 232 233 234

    //  Several errors are OK. When speculative write is being done we may not
    //  be able to write a single byte from the socket. Also, SIGSTOP issued
    //  by a debugging tool can result in EINTR error.
235 236
    if (nbytes == -1
        && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
237 238 239 240
        return 0;

    //  Signalise peer failure.
    if (nbytes == -1) {
241 242 243 244
        errno_assert (errno != EACCES && errno != EBADF && errno != EDESTADDRREQ
                      && errno != EFAULT && errno != EISCONN
                      && errno != EMSGSIZE && errno != ENOMEM
                      && errno != ENOTSOCK && errno != EOPNOTSUPP);
245 246 247
        return -1;
    }

248
    return static_cast<int> (nbytes);
249 250 251 252 253 254 255 256

#endif
}

int zmq::tcp_read (fd_t s_, void *data_, size_t size_)
{
#ifdef ZMQ_HAVE_WINDOWS

257
    const int rc = recv (s_, (char *) data_, (int) size_, 0);
258 259 260

    //  If not a single byte can be read from the socket in non-blocking mode
    //  we'll get an error (this may happen during the speculative read).
261
    if (rc == SOCKET_ERROR) {
262
        const int last_error = WSAGetLastError ();
263 264
        if (last_error == WSAEWOULDBLOCK) {
            errno = EAGAIN;
265 266 267 268 269 270
        } else {
            wsa_assert (
              last_error == WSAENETDOWN || last_error == WSAENETRESET
              || last_error == WSAECONNABORTED || last_error == WSAETIMEDOUT
              || last_error == WSAECONNRESET || last_error == WSAECONNREFUSED
              || last_error == WSAENOTCONN);
271 272
            errno = wsa_error_to_errno (last_error);
        }
273 274
    }

275
    return rc == SOCKET_ERROR ? -1 : rc;
276 277 278

#else

279
    const ssize_t rc = recv (s_, (char *) data_, size_, 0);
280 281 282 283 284

    //  Several errors are OK. When speculative read is being done we may not
    //  be able to read a single byte from the socket. Also, SIGSTOP issued
    //  by a debugging tool can result in EINTR error.
    if (rc == -1) {
285 286
        errno_assert (errno != EBADF && errno != EFAULT && errno != ENOMEM
                      && errno != ENOTSOCK);
287 288 289 290
        if (errno == EWOULDBLOCK || errno == EINTR)
            errno = EAGAIN;
    }

291
    return static_cast<int> (rc);
292 293 294

#endif
}
295

296
void zmq::tcp_assert_tuning_error (zmq::fd_t s_, int rc_)
297 298 299 300 301 302
{
    if (rc_ == 0)
        return;

    //  Check whether an error occurred
    int err = 0;
303
#if defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_VXWORKS
304 305 306 307
    int len = sizeof err;
#else
    socklen_t len = sizeof err;
#endif
308 309 310

    int rc = getsockopt (s_, SOL_SOCKET, SO_ERROR, (char *) &err, &len);

311 312 313 314 315
    //  Assert if the error was caused by 0MQ bug.
    //  Networking problems are OK. No need to assert.
#ifdef ZMQ_HAVE_WINDOWS
    zmq_assert (rc == 0);
    if (err != 0) {
316 317 318 319 320 321
        wsa_assert (err == WSAECONNREFUSED || err == WSAECONNRESET
                    || err == WSAECONNABORTED || err == WSAEINTR
                    || err == WSAETIMEDOUT || err == WSAEHOSTUNREACH
                    || err == WSAENETUNREACH || err == WSAENETDOWN
                    || err == WSAENETRESET || err == WSAEACCES
                    || err == WSAEINVAL || err == WSAEADDRINUSE);
322 323 324 325 326 327 328 329
    }
#else
    //  Following code should handle both Berkeley-derived socket
    //  implementations and Solaris.
    if (rc == -1)
        err = errno;
    if (err != 0) {
        errno = err;
330 331 332 333 334
        errno_assert (errno == ECONNREFUSED || errno == ECONNRESET
                      || errno == ECONNABORTED || errno == EINTR
                      || errno == ETIMEDOUT || errno == EHOSTUNREACH
                      || errno == ENETUNREACH || errno == ENETDOWN
                      || errno == ENETRESET || errno == EINVAL);
335 336 337
    }
#endif
}
338 339 340

void zmq::tcp_tune_loopback_fast_path (const fd_t socket_)
{
341
#if defined ZMQ_HAVE_WINDOWS && defined SIO_LOOPBACK_FAST_PATH
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    int sio_loopback_fastpath = 1;
    DWORD numberOfBytesReturned = 0;

    int rc = WSAIoctl (socket_, SIO_LOOPBACK_FAST_PATH, &sio_loopback_fastpath,
                       sizeof sio_loopback_fastpath, NULL, 0,
                       &numberOfBytesReturned, 0, 0);

    if (SOCKET_ERROR == rc) {
        DWORD lastError = ::WSAGetLastError ();

        if (WSAEOPNOTSUPP == lastError) {
            // This system is not Windows 8 or Server 2012, and the call is not supported.
        } else {
            wsa_assert (false);
        }
    }
#else
    LIBZMQ_UNUSED (socket_);
#endif
}