signaler.cpp 15.1 KB
Newer Older
1
/*
2
    Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

    This file is part of 0MQ.

    0MQ is free software; you can redistribute it and/or modify it under
    the terms of the GNU Lesser General Public License as published by
    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
    GNU Lesser General Public License for more details.

    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/>.
*/

#include "platform.hpp"

#if defined ZMQ_FORCE_SELECT
#define ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#elif defined ZMQ_FORCE_POLL
#define ZMQ_SIGNALER_WAIT_BASED_ON_POLL
#elif defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
    defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
    defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
    defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
    defined ZMQ_HAVE_NETBSD
#define ZMQ_SIGNALER_WAIT_BASED_ON_POLL
Steven McCoy's avatar
Steven McCoy committed
32 33
#elif defined ZMQ_HAVE_WINDOWS || defined ZMQ_HAVE_OPENVMS ||\
	defined ZMQ_HAVE_CYGWIN
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#define ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#endif

//  On AIX, poll.h has to be included before zmq.h to get consistent
//  definition of pollfd structure (AIX uses 'reqevents' and 'retnevents'
//  instead of 'events' and 'revents' and defines macros to map from POSIX-y
//  names to AIX-specific names).
#if defined ZMQ_SIGNALER_WAIT_BASED_ON_POLL
#include <poll.h>
#elif defined ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#elif defined ZMQ_HAVE_HPUX
#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
#elif defined ZMQ_HAVE_OPENVMS
#include <sys/types.h>
#include <sys/time.h>
#else
#include <sys/select.h>
#endif
#endif

#include "signaler.hpp"
#include "likely.hpp"
60
#include "stdint.hpp"
61
#include "config.hpp"
62 63 64 65
#include "err.hpp"
#include "fd.hpp"
#include "ip.hpp"

66 67 68 69
#if defined ZMQ_HAVE_EVENTFD
#include <sys/eventfd.h>
#endif

70 71
#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
72
#include <tchar.h>
73 74 75 76 77 78 79 80 81 82 83
#else
#include <unistd.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#endif

zmq::signaler_t::signaler_t ()
{
    //  Create the socketpair for signaling.
Pieter Hintjens's avatar
Pieter Hintjens committed
84 85 86 87
    if (make_fdpair (&r, &w) == 0) {
        unblock_socket (w);
        unblock_socket (r);
    }
88 89 90
#ifdef HAVE_FORK
    pid = getpid();
#endif
91 92 93 94
}

zmq::signaler_t::~signaler_t ()
{
95 96 97 98
#if defined ZMQ_HAVE_EVENTFD
    int rc = close (r);
    errno_assert (rc == 0);
#elif defined ZMQ_HAVE_WINDOWS
99 100 101 102 103
    struct linger so_linger = { 1, 0 };
    int rc = setsockopt (w, SOL_SOCKET, SO_LINGER,
        (char *)&so_linger, sizeof (so_linger));
    wsa_assert (rc != SOCKET_ERROR);
    rc = closesocket (w);
104 105 106 107
    wsa_assert (rc != SOCKET_ERROR);
    rc = closesocket (r);
    wsa_assert (rc != SOCKET_ERROR);
#else
108 109 110 111
    int rc = close (w);
    errno_assert (rc == 0);
    rc = close (r);
    errno_assert (rc == 0);
112 113 114 115 116 117 118 119 120 121
#endif
}

zmq::fd_t zmq::signaler_t::get_fd ()
{
    return r;
}

void zmq::signaler_t::send ()
{
122 123 124 125 126 127
#if HAVE_FORK
    if (unlikely(pid != getpid())) {
        //printf("Child process %d signaler_t::send returning without sending #1\n", getpid());
        return; // do not send anything in forked child context
    }
#endif
128 129 130 131 132
#if defined ZMQ_HAVE_EVENTFD
    const uint64_t inc = 1;
    ssize_t sz = write (w, &inc, sizeof (inc));
    errno_assert (sz == sizeof (inc));
#elif defined ZMQ_HAVE_WINDOWS
133
    unsigned char dummy = 0;
Martin Sustrik's avatar
Martin Sustrik committed
134
    int nbytes = ::send (w, (char*) &dummy, sizeof (dummy), 0);
135 136 137 138 139 140 141 142
    wsa_assert (nbytes != SOCKET_ERROR);
    zmq_assert (nbytes == sizeof (dummy));
#else
    unsigned char dummy = 0;
    while (true) {
        ssize_t nbytes = ::send (w, &dummy, sizeof (dummy), 0);
        if (unlikely (nbytes == -1 && errno == EINTR))
            continue;
143 144 145 146 147 148 149
#if HAVE_FORK
        if (unlikely(pid != getpid())) {
            //printf("Child process %d signaler_t::send returning without sending #2\n", getpid());
            errno = EINTR;
            break;
        }
#endif
150 151 152 153 154 155 156 157
        zmq_assert (nbytes == sizeof (dummy));
        break;
    }
#endif
}

int zmq::signaler_t::wait (int timeout_)
{
158 159 160 161 162 163 164 165 166 167 168
#ifdef HAVE_FORK
    if (unlikely(pid != getpid()))
    {
        // we have forked and the file descriptor is closed. Emulate an interupt
        // response.
        //printf("Child process %d signaler_t::wait returning simulating interrupt #1\n", getpid());
        errno = EINTR;
        return -1;
    }
#endif

169 170 171 172 173 174 175
#ifdef ZMQ_SIGNALER_WAIT_BASED_ON_POLL

    struct pollfd pfd;
    pfd.fd = r;
    pfd.events = POLLIN;
    int rc = poll (&pfd, 1, timeout_);
    if (unlikely (rc < 0)) {
176
        errno_assert (errno == EINTR);
177 178
        return -1;
    }
179 180
    else
    if (unlikely (rc == 0)) {
181 182 183
        errno = EAGAIN;
        return -1;
    }
184
#ifdef HAVE_FORK
185
    if (unlikely(pid != getpid())) {
186 187 188 189 190 191 192
        // we have forked and the file descriptor is closed. Emulate an interupt
        // response.
        //printf("Child process %d signaler_t::wait returning simulating interrupt #2\n", getpid());
        errno = EINTR;
        return -1;
    }
#endif
193 194 195 196 197 198 199 200 201 202
    zmq_assert (rc == 1);
    zmq_assert (pfd.revents & POLLIN);
    return 0;

#elif defined ZMQ_SIGNALER_WAIT_BASED_ON_SELECT

    fd_set fds;
    FD_ZERO (&fds);
    FD_SET (r, &fds);
    struct timeval timeout;
203 204 205 206
    if (timeout_ >= 0) {
        timeout.tv_sec = timeout_ / 1000;
        timeout.tv_usec = timeout_ % 1000 * 1000;
    }
207
#ifdef ZMQ_HAVE_WINDOWS
208 209
    int rc = select (0, &fds, NULL, NULL,
        timeout_ >= 0 ? &timeout : NULL);
210 211
    wsa_assert (rc != SOCKET_ERROR);
#else
212 213
    int rc = select (r + 1, &fds, NULL, NULL,
        timeout_ >= 0 ? &timeout : NULL);
214
    if (unlikely (rc < 0)) {
215
        errno_assert (errno == EINTR);
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        return -1;
    }
#endif
    if (unlikely (rc == 0)) {
        errno = EAGAIN;
        return -1;
    }
    zmq_assert (rc == 1);
    return 0;

#else
#error
#endif
}

void zmq::signaler_t::recv ()
{
    //  Attempt to read a signal.
234 235 236 237
#if defined ZMQ_HAVE_EVENTFD
    uint64_t dummy;
    ssize_t sz = read (r, &dummy, sizeof (dummy));
    errno_assert (sz == sizeof (dummy));
238 239 240 241 242

    //  If we accidentally grabbed the next signal along with the current
    //  one, return it back to the eventfd object.
    if (unlikely (dummy == 2)) {
        const uint64_t inc = 1;
243 244
        ssize_t sz2 = write (w, &inc, sizeof (inc));
        errno_assert (sz2 == sizeof (inc));
245 246 247
        return;
    }

248 249
    zmq_assert (dummy == 1);
#else
250
    unsigned char dummy;
Martin Sustrik's avatar
Martin Sustrik committed
251 252
#if defined ZMQ_HAVE_WINDOWS
    int nbytes = ::recv (r, (char*) &dummy, sizeof (dummy), 0);
253 254 255 256 257 258 259
    wsa_assert (nbytes != SOCKET_ERROR);
#else
    ssize_t nbytes = ::recv (r, &dummy, sizeof (dummy), 0);
    errno_assert (nbytes >= 0);
#endif
    zmq_assert (nbytes == sizeof (dummy));
    zmq_assert (dummy == 0);
260
#endif
261 262
}

263 264 265
#ifdef HAVE_FORK
void zmq::signaler_t::forked()
{
266 267 268
    //  Close file descriptors created in the parent and create new pair
    close (r);
    close (w);
Pieter Hintjens's avatar
Pieter Hintjens committed
269
    make_fdpair (&r, &w);
270 271 272
}
#endif

Pieter Hintjens's avatar
Pieter Hintjens committed
273
//  Returns -1 if we could not make the socket pair successfully
274 275
int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_)
{
276 277
#if defined ZMQ_HAVE_EVENTFD
    fd_t fd = eventfd (0, 0);
Pieter Hintjens's avatar
Pieter Hintjens committed
278 279 280 281 282 283 284 285 286
    if (fd == -1) {
        errno_assert (errno == ENFILE || errno == EMFILE);
        *w_ = *r_ = -1;
        return -1;
    }
    else {
        *w_ = *r_ = fd;
        return 0;
    }
287 288

#elif defined ZMQ_HAVE_WINDOWS
Pieter Hintjens's avatar
Pieter Hintjens committed
289
#   if !defined _WIN32_WCE
290
    // Windows CE does not manage security attributes
Matt Arsenault's avatar
Matt Arsenault committed
291 292 293 294
    SECURITY_DESCRIPTOR sd;
    SECURITY_ATTRIBUTES sa;
    memset (&sd, 0, sizeof (sd));
    memset (&sa, 0, sizeof (sa));
Matthew Metnetsky's avatar
Matthew Metnetsky committed
295 296 297 298 299 300

    InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl(&sd, TRUE, 0, FALSE);

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = &sd;
Pieter Hintjens's avatar
Pieter Hintjens committed
301
#   endif
302

303 304 305 306
    //  This function has to be in a system-wide critical section so that
    //  two instances of the library don't accidentally create signaler
    //  crossing the process boundary.
    //  We'll use named event object to implement the critical section.
Martin Hurton's avatar
Martin Hurton committed
307 308 309
    //  Note that if the event object already exists, the CreateEvent requests
    //  EVENT_ALL_ACCESS access right. If this fails, we try to open
    //  the event object asking for SYNCHRONIZE access only.
310 311 312
    HANDLE sync = NULL;

    //  Create critical section only if using fixed signaler port
313 314 315 316 317
    //  Use problematic Event implementation for compatibility if using old port 5905.
    //  Otherwise use Mutex implementation.
    int event_signaler_port = 5905;

    if (signaler_port == event_signaler_port) {
318 319 320 321 322 323 324 325 326 327 328
#       if !defined _WIN32_WCE
        sync = CreateEvent (&sa, FALSE, TRUE, TEXT ("Global\\zmq-signaler-port-sync"));
#       else
        sync = CreateEvent (NULL, FALSE, TRUE, TEXT ("Global\\zmq-signaler-port-sync"));
#       endif
        if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED)
            sync = OpenEvent (SYNCHRONIZE | EVENT_MODIFY_STATE,
                              FALSE, TEXT ("Global\\zmq-signaler-port-sync"));

        win_assert (sync != NULL);
    }
329 330 331 332 333 334 335 336 337 338 339 340 341 342
    else if (signaler_port != 0) {
        TCHAR mutex_name[64];
        _stprintf (mutex_name, TEXT ("Global\\zmq-signaler-port-%d"), signaler_port);

#       if !defined _WIN32_WCE
        sync = CreateMutex (&sa, FALSE, mutex_name);
#       else
        sync = CreateMutex (NULL, FALSE, mutex_name);
#       endif
        if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED)
            sync = OpenMutex (SYNCHRONIZE, FALSE, mutex_name);

        win_assert (sync != NULL);
    }
343

344 345 346 347 348 349 350
    //  Windows has no 'socketpair' function. CreatePipe is no good as pipe
    //  handles cannot be polled on. Here we create the socketpair by hand.
    *w_ = INVALID_SOCKET;
    *r_ = INVALID_SOCKET;

    //  Create listening socket.
    SOCKET listener;
351
    listener = open_socket (AF_INET, SOCK_STREAM, 0);
352 353 354 355 356 357 358 359 360 361 362 363
    wsa_assert (listener != INVALID_SOCKET);

    //  Set SO_REUSEADDR and TCP_NODELAY on listening socket.
    BOOL so_reuseaddr = 1;
    int rc = setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
        (char *)&so_reuseaddr, sizeof (so_reuseaddr));
    wsa_assert (rc != SOCKET_ERROR);
    BOOL tcp_nodelay = 1;
    rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY,
        (char *)&tcp_nodelay, sizeof (tcp_nodelay));
    wsa_assert (rc != SOCKET_ERROR);

364
    //  Init sockaddr to signaler port.
365 366 367 368
    struct sockaddr_in addr;
    memset (&addr, 0, sizeof (addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
369
    addr.sin_port = htons (signaler_port);
370 371

    //  Create the writer socket.
372
    *w_ = open_socket (AF_INET, SOCK_STREAM, 0);
373 374 375 376 377 378 379
    wsa_assert (*w_ != INVALID_SOCKET);

    //  Set TCP_NODELAY on writer socket.
    rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY,
        (char *)&tcp_nodelay, sizeof (tcp_nodelay));
    wsa_assert (rc != SOCKET_ERROR);

380 381 382
    if (sync != NULL) {
        //  Enter the critical section.
        DWORD dwrc = WaitForSingleObject (sync, INFINITE);
383
        zmq_assert (dwrc == WAIT_OBJECT_0 || dwrc == WAIT_ABANDONED);
384
    }
385 386 387 388

    //  Bind listening socket to signaler port.
    rc = bind (listener, (const struct sockaddr*) &addr, sizeof (addr));

389 390 391 392 393 394
    if (rc != SOCKET_ERROR && signaler_port == 0) {
        //  Retrieve ephemeral port number
        int addrlen = sizeof (addr);
        rc = getsockname (listener, (struct sockaddr*) &addr, &addrlen);
    }

395 396 397 398
    //  Listen for incoming connections.
    if (rc != SOCKET_ERROR)
        rc = listen (listener, 1);

399
    //  Connect writer to the listener.
400 401
    if (rc != SOCKET_ERROR)
        rc = connect (*w_, (struct sockaddr*) &addr, sizeof (addr));
402

403 404
    //  Accept connection from writer.
    if (rc != SOCKET_ERROR)
405
        *r_ = accept (listener, NULL, NULL);
406 407 408 409 410 411

    //  Save errno if error occurred in bind/listen/connect/accept.
    int saved_errno = 0;
    if (*r_ == INVALID_SOCKET)
        saved_errno = WSAGetLastError ();

412
    //  We don't need the listening socket anymore. Close it.
413
    closesocket (listener);
414

415 416
    if (sync != NULL) {
        //  Exit the critical section.
417 418 419 420 421
        BOOL brc;
        if (signaler_port == event_signaler_port)
            brc = SetEvent (sync);
        else
            brc = ReleaseMutex (sync);
422
        win_assert (brc != 0);
423

424 425 426 427
        //  Release the kernel object
        brc = CloseHandle (sync);
        win_assert (brc != 0);
    }
428

429
    if (*r_ != INVALID_SOCKET) {
Pieter Hintjens's avatar
Pieter Hintjens committed
430
#   if !defined _WIN32_WCE
431
        //  On Windows, preventing sockets to be inherited by child processes.
432
        BOOL brc = SetHandleInformation ((HANDLE) *r_, HANDLE_FLAG_INHERIT, 0);
433
        win_assert (brc);
Pieter Hintjens's avatar
Pieter Hintjens committed
434
#   endif
435
        return 0;
Pieter Hintjens's avatar
Pieter Hintjens committed
436 437
    }
    else {
438
        //  Cleanup writer if connection failed
439 440 441 442 443
        if (*w_ != INVALID_SOCKET) {
            rc = closesocket (*w_);
            wsa_assert (rc != SOCKET_ERROR);
            *w_ = INVALID_SOCKET;
        }
444
        //  Set errno from saved value
445
        errno = wsa_error_to_errno (saved_errno);
446 447
        return -1;
    }
448 449 450 451 452 453 454 455 456

#elif defined ZMQ_HAVE_OPENVMS

    //  Whilst OpenVMS supports socketpair - it maps to AF_INET only.  Further,
    //  it does not set the socket options TCP_NODELAY and TCP_NODELACK which
    //  can lead to performance problems.
    //
    //  The bug will be fixed in V5.6 ECO4 and beyond.  In the meantime, we'll
    //  create the socket pair manually.
457
    struct sockaddr_in lcladdr;
458 459 460 461 462
    memset (&lcladdr, 0, sizeof (lcladdr));
    lcladdr.sin_family = AF_INET;
    lcladdr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
    lcladdr.sin_port = 0;

463
    int listener = open_socket (AF_INET, SOCK_STREAM, 0);
464 465 466 467 468 469 470 471 472
    errno_assert (listener != -1);

    int on = 1;
    int rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, &on, sizeof (on));
    errno_assert (rc != -1);

    rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELACK, &on, sizeof (on));
    errno_assert (rc != -1);

Pieter Hintjens's avatar
Pieter Hintjens committed
473
    rc = bind (listener, (struct sockaddr*) &lcladdr, sizeof (lcladdr));
474 475 476 477 478 479 480 481 482 483
    errno_assert (rc != -1);

    socklen_t lcladdr_len = sizeof (lcladdr);

    rc = getsockname (listener, (struct sockaddr*) &lcladdr, &lcladdr_len);
    errno_assert (rc != -1);

    rc = listen (listener, 1);
    errno_assert (rc != -1);

484
    *w_ = open_socket (AF_INET, SOCK_STREAM, 0);
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    errno_assert (*w_ != -1);

    rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, &on, sizeof (on));
    errno_assert (rc != -1);

    rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELACK, &on, sizeof (on));
    errno_assert (rc != -1);

    rc = connect (*w_, (struct sockaddr*) &lcladdr, sizeof (lcladdr));
    errno_assert (rc != -1);

    *r_ = accept (listener, NULL, NULL);
    errno_assert (*r_ != -1);

    close (listener);

    return 0;

Pieter Hintjens's avatar
Pieter Hintjens committed
503 504
#else
    // All other implementations support socketpair()
505 506
    int sv [2];
    int rc = socketpair (AF_UNIX, SOCK_STREAM, 0, sv);
Pieter Hintjens's avatar
Pieter Hintjens committed
507 508
    if (rc == -1) {
        errno_assert (errno == ENFILE || errno == EMFILE);
509
        *w_ = *r_ = -1;
Pieter Hintjens's avatar
Pieter Hintjens committed
510 511 512 513 514 515 516
        return -1;
    }
    else {
        *w_ = sv [0];
        *r_ = sv [1];
        return 0;
    }
517 518 519 520 521 522 523 524 525 526
#endif
}

#if defined ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#undef ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#endif
#if defined ZMQ_SIGNALER_WAIT_BASED_ON_POLL
#undef ZMQ_SIGNALER_WAIT_BASED_ON_POLL
#endif