tcp_listener.cpp 8.43 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 32
#include <new>

33
#include <string>
34
#include <stdio.h>
35

36
#include "tcp_listener.hpp"
37
#include "io_thread.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
38 39
#include "config.hpp"
#include "err.hpp"
40
#include "ip.hpp"
41
#include "tcp.hpp"
42
#include "socket_base.hpp"
43
#include "address.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
44

45
#ifndef ZMQ_HAVE_WINDOWS
46 47 48 49 50 51 52
#include <unistd.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
#endif
57 58 59

#ifdef ZMQ_HAVE_OPENVMS
#include <ioctl.h>
60
#endif
Martin Sustrik's avatar
Martin Sustrik committed
61

62
zmq::tcp_listener_t::tcp_listener_t (io_thread_t *io_thread_,
63 64
                                     socket_base_t *socket_,
                                     const options_t &options_) :
65
    stream_listener_base_t (io_thread_, socket_, options_)
66 67 68
{
}

69 70
void zmq::tcp_listener_t::in_event ()
{
71
    const fd_t fd = accept ();
72 73 74

    //  If connection was reset by the peer in the meantime, just ignore it.
    //  TODO: Handle specific errors like ENFILE/EMFILE etc.
75
    if (fd == retired_fd) {
76 77
        _socket->event_accept_failed (
          make_unconnected_bind_endpoint_pair (_endpoint), zmq_errno ());
78
        return;
79
    }
80

81
    int rc = tune_tcp_socket (fd);
82 83
    rc = rc
         | tune_tcp_keepalives (
84 85
           fd, options.tcp_keepalive, options.tcp_keepalive_cnt,
           options.tcp_keepalive_idle, options.tcp_keepalive_intvl);
86 87
    rc = rc | tune_tcp_maxrt (fd, options.tcp_maxrt);
    if (rc != 0) {
88 89
        _socket->event_accept_failed (
          make_unconnected_bind_endpoint_pair (_endpoint), zmq_errno ());
90 91
        return;
    }
92

93
    //  Create the engine object for this connection.
94
    create_engine (fd);
95 96
}

97 98 99
std::string
zmq::tcp_listener_t::get_socket_name (zmq::fd_t fd_,
                                      socket_end_t socket_end_) const
100
{
101
    return zmq::get_socket_name<tcp_address_t> (fd_, socket_end_);
102 103
}

104
int zmq::tcp_listener_t::create_socket (const char *addr_)
105
{
106
    _s = tcp_open_socket (addr_, options, true, true, &_address);
107
    if (_s == retired_fd) {
108 109
        return -1;
    }
110

111 112
    //  TODO why is this only done for the listener?
    make_socket_noninheritable (_s);
113

114 115
    //  Allow reusing of the address.
    int flag = 1;
116
    int rc;
117
#ifdef ZMQ_HAVE_WINDOWS
118 119 120 121 122
    //  TODO this was changed for Windows from SO_REUSEADDRE to
    //  SE_EXCLUSIVEADDRUSE by 0ab65324195ad70205514d465b03d851a6de051c,
    //  so the comment above is no longer correct; also, now the settings are
    //  different between listener and connecter with a src address.
    //  is this intentional?
123
    rc = setsockopt (_s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
124
                     reinterpret_cast<const char *> (&flag), sizeof (int));
125
    wsa_assert (rc != SOCKET_ERROR);
126
#elif defined ZMQ_HAVE_VXWORKS
127 128
    rc =
      setsockopt (_s, SOL_SOCKET, SO_REUSEADDR, (char *) &flag, sizeof (int));
129
    errno_assert (rc == 0);
130
#else
131
    rc = setsockopt (_s, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int));
132 133
    errno_assert (rc == 0);
#endif
134 135

    //  Bind the socket to the network interface and port.
136
#if defined ZMQ_HAVE_VXWORKS
137
    rc = bind (_s, (sockaddr *) _address.addr (), _address.addrlen ());
138
#else
139
    rc = bind (_s, _address.addr (), _address.addrlen ());
140
#endif
141
#ifdef ZMQ_HAVE_WINDOWS
142
    if (rc == SOCKET_ERROR) {
143
        errno = wsa_error_to_errno (WSAGetLastError ());
144
        goto error;
145
    }
Martin Sustrik's avatar
Martin Sustrik committed
146
#else
147
    if (rc != 0)
148
        goto error;
149
#endif
150

151
    //  Listen for incoming connections.
152
    rc = listen (_s, options.backlog);
153 154
#ifdef ZMQ_HAVE_WINDOWS
    if (rc == SOCKET_ERROR) {
155
        errno = wsa_error_to_errno (WSAGetLastError ());
156
        goto error;
157
    }
158
#else
Martin Sustrik's avatar
Martin Sustrik committed
159
    if (rc != 0)
160
        goto error;
Brett Cameron's avatar
Brett Cameron committed
161
#endif
162

Martin Sustrik's avatar
Martin Sustrik committed
163
    return 0;
164 165

error:
166
    const int err = errno;
167 168 169
    close ();
    errno = err;
    return -1;
Martin Sustrik's avatar
Martin Sustrik committed
170 171
}

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
int zmq::tcp_listener_t::set_local_address (const char *addr_)
{
    if (options.use_fd != -1) {
        //  in this case, the addr_ passed is not used and ignored, since the
        //  socket was already created by the application
        _s = options.use_fd;
    } else {
        if (create_socket (addr_) == -1)
            return -1;
    }

    _endpoint = get_socket_name (_s, socket_end_local);

    _socket->event_listening (make_unconnected_bind_endpoint_pair (_endpoint),
                              _s);
    return 0;
}

Martin Sustrik's avatar
Martin Sustrik committed
190
zmq::fd_t zmq::tcp_listener_t::accept ()
Martin Sustrik's avatar
Martin Sustrik committed
191
{
192 193
    //  The situation where connection cannot be accepted due to insufficient
    //  resources is considered valid and treated by ignoring the connection.
194
    //  Accept one connection and deal with different failure modes.
195
    zmq_assert (_s != retired_fd);
196

197 198
    struct sockaddr_storage ss;
    memset (&ss, 0, sizeof (ss));
199
#if defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_VXWORKS
AJ Lewis's avatar
AJ Lewis committed
200 201
    int ss_len = sizeof (ss);
#else
202
    socklen_t ss_len = sizeof (ss);
AJ Lewis's avatar
AJ Lewis committed
203
#endif
204
#if defined ZMQ_HAVE_SOCK_CLOEXEC && defined HAVE_ACCEPT4
205 206
    fd_t sock = ::accept4 (_s, reinterpret_cast<struct sockaddr *> (&ss),
                           &ss_len, SOCK_CLOEXEC);
207
#else
208
    const fd_t sock =
209
      ::accept (_s, reinterpret_cast<struct sockaddr *> (&ss), &ss_len);
210
#endif
211

212
    if (sock == retired_fd) {
213
#if defined ZMQ_HAVE_WINDOWS
214 215 216
        const int last_error = WSAGetLastError ();
        wsa_assert (last_error == WSAEWOULDBLOCK || last_error == WSAECONNRESET
                    || last_error == WSAEMFILE || last_error == WSAENOBUFS);
217 218 219 220 221
#elif defined ZMQ_HAVE_ANDROID
        errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR
                      || errno == ECONNABORTED || errno == EPROTO
                      || errno == ENOBUFS || errno == ENOMEM || errno == EMFILE
                      || errno == ENFILE || errno == EINVAL);
Brett Cameron's avatar
Brett Cameron committed
222
#else
223 224 225 226
        errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR
                      || errno == ECONNABORTED || errno == EPROTO
                      || errno == ENOBUFS || errno == ENOMEM || errno == EMFILE
                      || errno == ENFILE);
227
#endif
228 229
        return retired_fd;
    }
230

231
    make_socket_noninheritable (sock);
232

233 234
    if (!options.tcp_accept_filters.empty ()) {
        bool matched = false;
235 236 237 238
        for (options_t::tcp_accept_filters_t::size_type
               i = 0,
               size = options.tcp_accept_filters.size ();
             i != size; ++i) {
239
            if (options.tcp_accept_filters[i].match_address (
240
                  reinterpret_cast<struct sockaddr *> (&ss), ss_len)) {
241 242 243 244 245 246
                matched = true;
                break;
            }
        }
        if (!matched) {
#ifdef ZMQ_HAVE_WINDOWS
247
            const int rc = closesocket (sock);
248 249 250 251 252 253 254 255 256
            wsa_assert (rc != SOCKET_ERROR);
#else
            int rc = ::close (sock);
            errno_assert (rc == 0);
#endif
            return retired_fd;
        }
    }

257 258
    if (zmq::set_nosigpipe (sock)) {
#ifdef ZMQ_HAVE_WINDOWS
259
        const int rc = closesocket (sock);
260 261 262 263 264 265 266 267
        wsa_assert (rc != SOCKET_ERROR);
#else
        int rc = ::close (sock);
        errno_assert (rc == 0);
#endif
        return retired_fd;
    }

268 269 270 271
    // Set the IP Type-Of-Service priority for this client socket
    if (options.tos != 0)
        set_ip_type_of_service (sock, options.tos);

Martin Sustrik's avatar
Martin Sustrik committed
272 273
    return sock;
}