select.cpp 15.5 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 33
#include "select.hpp"
#if defined ZMQ_USE_SELECT

34
#if defined ZMQ_HAVE_WINDOWS
Martin Sustrik's avatar
Martin Sustrik committed
35
#elif defined ZMQ_HAVE_HPUX
Martin Sustrik's avatar
Martin Sustrik committed
36 37 38
#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
Martin Sustrik's avatar
Martin Sustrik committed
39
#elif defined ZMQ_HAVE_OPENVMS
Martin Sustrik's avatar
Martin Sustrik committed
40 41 42 43 44 45 46 47 48 49
#include <sys/types.h>
#include <sys/time.h>
#else
#include <sys/select.h>
#endif

#include "err.hpp"
#include "config.hpp"
#include "i_poll_events.hpp"

50
zmq::select_t::select_t (const zmq::ctx_t &ctx_) :
51 52 53 54 55 56
    ctx (ctx_),
#if defined ZMQ_HAVE_WINDOWS
    //  Fine as long as map is not cleared.
    current_family_entry_it (family_entries.end ()),
#else
    maxfd (retired_fd),
57
    retired (false),
58
#endif
Martin Sustrik's avatar
Martin Sustrik committed
59 60 61 62
    stopping (false)
{
}

63 64
zmq::select_t::~select_t ()
{
65
    worker.stop ();
66 67
}

68
zmq::select_t::handle_t zmq::select_t::add_fd (fd_t fd_, i_poll_events *events_)
Martin Sustrik's avatar
Martin Sustrik committed
69
{
70 71 72
    fd_entry_t fd_entry;
    fd_entry.fd = fd_;
    fd_entry.events = events_;
73

74 75 76 77 78 79 80 81 82
#if defined ZMQ_HAVE_WINDOWS
    u_short family = get_fd_family (fd_);
    wsa_assert (family != AF_UNSPEC);
    family_entry_t& family_entry = family_entries [family];
    family_entry.fd_entries.push_back (fd_entry);
    FD_SET (fd_, &family_entry.fds_set.error);
#else
    fd_entries.push_back (fd_entry);
    FD_SET (fd_, &fds_set.error);
Martin Sustrik's avatar
Martin Sustrik committed
83 84 85

    if (fd_ > maxfd)
        maxfd = fd_;
86
#endif
Martin Sustrik's avatar
Martin Sustrik committed
87

88
    adjust_load (1);
Martin Sustrik's avatar
Martin Sustrik committed
89

90
    return fd_;
Martin Sustrik's avatar
Martin Sustrik committed
91 92
}

Martin Sustrik's avatar
Martin Sustrik committed
93
void zmq::select_t::rm_fd (handle_t handle_)
Martin Sustrik's avatar
Martin Sustrik committed
94
{
95 96 97 98 99 100 101 102 103
#if defined ZMQ_HAVE_WINDOWS
    u_short family = get_fd_family (handle_);
    wsa_assert (family != AF_UNSPEC);

    family_entries_t::iterator family_entry_it = family_entries.find (family);
    family_entry_t& family_entry = family_entry_it->second;

    if (family_entry_it != current_family_entry_it) {
        //  Family is not currently being iterated and can be safely
104 105
        //  modified in-place. So later it can be skipped without
        //  re-verifying its content.
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        fd_entries_t::iterator fd_entry_it;
        for (fd_entry_it = family_entry.fd_entries.begin ();
              fd_entry_it != family_entry.fd_entries.end (); ++fd_entry_it)
            if (fd_entry_it->fd == handle_)
                break;
        zmq_assert (fd_entry_it != family_entry.fd_entries.end ());

        family_entry.fd_entries.erase (fd_entry_it);
        family_entry.fds_set.remove_fd (handle_);
    } else {
        //  Otherwise mark removed entries as retired. It will be cleaned up
        //  at the end of the iteration. See zmq::select_t::loop
        fd_entries_t::iterator fd_entry_it;
        for (fd_entry_it = family_entry.fd_entries.begin ();
              fd_entry_it != family_entry.fd_entries.end (); ++fd_entry_it)
            if (fd_entry_it->fd == handle_)
                break;
        zmq_assert (fd_entry_it != family_entry.fd_entries.end ());

        fd_entry_it->fd = retired_fd;
        family_entry.fds_set.remove_fd (handle_);
        family_entry.retired = true;
    }
#else
    fd_entries_t::iterator fd_entry_it;
    for (fd_entry_it = fd_entries.begin ();
          fd_entry_it != fd_entries.end (); ++fd_entry_it)
        if (fd_entry_it->fd == handle_)
Martin Sustrik's avatar
Martin Sustrik committed
134
            break;
135
    zmq_assert (fd_entry_it != fd_entries.end ());
Martin Sustrik's avatar
Martin Sustrik committed
136

137 138
    fd_entry_it->fd = retired_fd;
    fds_set.remove_fd (handle_);
Martin Sustrik's avatar
Martin Sustrik committed
139

140
    if (handle_ == maxfd) {
Martin Sustrik's avatar
Martin Sustrik committed
141
        maxfd = retired_fd;
142 143 144 145
        for (fd_entry_it = fd_entries.begin (); fd_entry_it != fd_entries.end ();
              ++fd_entry_it)
            if (fd_entry_it->fd > maxfd)
                maxfd = fd_entry_it->fd;
Martin Sustrik's avatar
Martin Sustrik committed
146 147
    }

148 149
    retired = true;
#endif
150
    adjust_load (-1);
Martin Sustrik's avatar
Martin Sustrik committed
151 152
}

Martin Sustrik's avatar
Martin Sustrik committed
153
void zmq::select_t::set_pollin (handle_t handle_)
Martin Sustrik's avatar
Martin Sustrik committed
154
{
155 156 157 158 159 160 161
#if defined ZMQ_HAVE_WINDOWS
    u_short family = get_fd_family (handle_);
    wsa_assert (family != AF_UNSPEC);
    FD_SET (handle_, &family_entries [family].fds_set.read);
#else
    FD_SET (handle_, &fds_set.read);
#endif
Martin Sustrik's avatar
Martin Sustrik committed
162 163
}

Martin Sustrik's avatar
Martin Sustrik committed
164
void zmq::select_t::reset_pollin (handle_t handle_)
Martin Sustrik's avatar
Martin Sustrik committed
165
{
166 167 168 169 170 171 172
#if defined ZMQ_HAVE_WINDOWS
    u_short family = get_fd_family (handle_);
    wsa_assert (family != AF_UNSPEC);
    FD_CLR (handle_, &family_entries [family].fds_set.read);
#else
    FD_CLR (handle_, &fds_set.read);
#endif
Martin Sustrik's avatar
Martin Sustrik committed
173 174
}

Martin Sustrik's avatar
Martin Sustrik committed
175
void zmq::select_t::set_pollout (handle_t handle_)
Martin Sustrik's avatar
Martin Sustrik committed
176
{
177 178 179 180 181 182 183
#if defined ZMQ_HAVE_WINDOWS
    u_short family = get_fd_family (handle_);
    wsa_assert (family != AF_UNSPEC);
    FD_SET (handle_, &family_entries [family].fds_set.write);
#else
    FD_SET (handle_, &fds_set.write);
#endif
Martin Sustrik's avatar
Martin Sustrik committed
184 185
}

Martin Sustrik's avatar
Martin Sustrik committed
186
void zmq::select_t::reset_pollout (handle_t handle_)
Martin Sustrik's avatar
Martin Sustrik committed
187
{
188 189 190 191 192 193 194
#if defined ZMQ_HAVE_WINDOWS
    u_short family = get_fd_family (handle_);
    wsa_assert (family != AF_UNSPEC);
    FD_CLR (handle_, &family_entries [family].fds_set.write);
#else
    FD_CLR (handle_, &fds_set.write);
#endif
Martin Sustrik's avatar
Martin Sustrik committed
195 196
}

Martin Sustrik's avatar
Martin Sustrik committed
197
void zmq::select_t::start ()
Martin Sustrik's avatar
Martin Sustrik committed
198
{
199
    ctx.start_thread (worker, worker_routine, this);
Martin Sustrik's avatar
Martin Sustrik committed
200 201
}

Martin Sustrik's avatar
Martin Sustrik committed
202
void zmq::select_t::stop ()
Martin Sustrik's avatar
Martin Sustrik committed
203 204 205 206
{
    stopping = true;
}

Richard Newton's avatar
Richard Newton committed
207
int zmq::select_t::max_fds ()
208 209 210 211
{
    return FD_SETSIZE;
}

Martin Sustrik's avatar
Martin Sustrik committed
212
void zmq::select_t::loop ()
Martin Sustrik's avatar
Martin Sustrik committed
213 214
{
    while (!stopping) {
215
        //  Execute any due timers.
216
        int timeout = (int) execute_timers ();
217

218 219
#if defined ZMQ_HAVE_OSX
        struct timeval tv = { (long) (timeout / 1000), timeout % 1000 * 1000 };
220
#else
221
        struct timeval tv = { (long) (timeout / 1000), (long) (timeout % 1000 * 1000) };
222
#endif
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

        int rc = 0;

#if defined ZMQ_HAVE_WINDOWS
        /*
            On Windows select does not allow to mix descriptors from different
            service providers. It seems to work for AF_INET and AF_INET6,
            but fails for AF_INET and VMCI. The workaround is to use
            WSAEventSelect and WSAWaitForMultipleEvents to wait, then use
            select to find out what actually changed. WSAWaitForMultipleEvents
            cannot be used alone, because it does not support more than 64 events
            which is not enough.

            To reduce unncessary overhead, WSA is only used when there are more
            than one family. Moreover, AF_INET and AF_INET6 are considered the same
            family because Windows seems to handle them properly.
            See get_fd_family for details.
        */
        wsa_events_t wsa_events;

        //  If there is just one family, there is no reason to use WSA events.
        if (family_entries.size () > 1) {
            for (family_entries_t::iterator family_entry_it = family_entries.begin ();
                  family_entry_it != family_entries.end (); ++family_entry_it) {
                family_entry_t& family_entry = family_entry_it->second;

                for (fd_entries_t::iterator fd_entry_it = family_entry.fd_entries.begin ();
                      fd_entry_it != family_entry.fd_entries.end (); ++fd_entry_it) {
                    fd_t fd = fd_entry_it->fd;

                    //  http://stackoverflow.com/q/35043420/188530
                    if (FD_ISSET (fd, &family_entry.fds_set.read) &&
                          FD_ISSET (fd, &family_entry.fds_set.write))
                        rc = WSAEventSelect (fd, wsa_events.events [3],
                            FD_READ | FD_ACCEPT | FD_CLOSE | FD_WRITE | FD_CONNECT | FD_OOB);
                    else if (FD_ISSET (fd, &family_entry.fds_set.read))
                        rc = WSAEventSelect (fd, wsa_events.events [0],
                            FD_READ | FD_ACCEPT | FD_CLOSE | FD_OOB);
                    else if (FD_ISSET (fd, &family_entry.fds_set.write))
                        rc = WSAEventSelect (fd, wsa_events.events [1],
                            FD_WRITE | FD_CONNECT | FD_OOB);
                    else if (FD_ISSET (fd, &family_entry.fds_set.error))
                        rc = WSAEventSelect (fd, wsa_events.events [2],
                            FD_OOB);
                    else
                        rc = 0;

                    wsa_assert (rc != SOCKET_ERROR);
                }
            }
        }
#endif

#if defined ZMQ_HAVE_WINDOWS
        if (family_entries.size () > 1) {
            rc = WSAWaitForMultipleEvents (4, wsa_events.events, FALSE,
                timeout ? timeout : INFINITE, FALSE);
280
            wsa_assert (rc != (int)WSA_WAIT_FAILED);
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
            zmq_assert (rc != WSA_WAIT_IO_COMPLETION);

            if (rc == WSA_WAIT_TIMEOUT)
                continue;
        }

        for (current_family_entry_it = family_entries.begin ();
              current_family_entry_it != family_entries.end (); ++current_family_entry_it) {
            family_entry_t& family_entry = current_family_entry_it->second;

            //  select will fail when run with empty sets.
            if (family_entry.fd_entries.empty ())
                continue;

            fds_set_t local_fds_set = family_entry.fds_set;

            if (family_entries.size () > 1) {
                //  There is no reason to wait again after WSAWaitForMultipleEvents.
                //  Simply collect what is ready.
                struct timeval tv_nodelay = { 0, 0 };
                rc = select (0, &local_fds_set.read, &local_fds_set.write, &local_fds_set.error,
                    &tv_nodelay);
            }
            else
                rc = select (0, &local_fds_set.read, &local_fds_set.write,
                    &local_fds_set.error, timeout > 0 ? &tv : NULL);

            wsa_assert (rc != SOCKET_ERROR);

            //  Size is cached to avoid iteration through recently added descriptors.
            for (fd_entries_t::size_type i = 0, size = family_entry.fd_entries.size (); i < size && rc > 0; ++i) {

313
                if (family_entry.fd_entries[i].fd == retired_fd)
314 315
                    continue;

316 317
                if (FD_ISSET(family_entry.fd_entries[i].fd, &local_fds_set.read)) {
                    family_entry.fd_entries[i].events->in_event();
318 319 320
                    --rc;
                }

321
                if (family_entry.fd_entries[i].fd == retired_fd || rc == 0)
322 323
                    continue;

324 325
                if (FD_ISSET(family_entry.fd_entries[i].fd, &local_fds_set.write)) {
                    family_entry.fd_entries[i].events->out_event();
326 327 328
                    --rc;
                }

329
                if (family_entry.fd_entries[i].fd == retired_fd || rc == 0)
330 331
                    continue;

332 333
                if (FD_ISSET(family_entry.fd_entries[i].fd, &local_fds_set.error)) {
                    family_entry.fd_entries[i].events->in_event();
334 335 336 337 338 339 340 341 342 343
                    --rc;
                }
            }

            if (family_entry.retired) {
                family_entry.retired = false;
                family_entry.fd_entries.erase (std::remove_if (family_entry.fd_entries.begin (),
                    family_entry.fd_entries.end (), is_retired_fd), family_entry.fd_entries.end ());
            }
        }
Martin Sustrik's avatar
Martin Sustrik committed
344
#else
345 346 347 348
        fds_set_t local_fds_set = fds_set;
        rc = select (maxfd + 1, &local_fds_set.read, &local_fds_set.write,
            &local_fds_set.error, timeout ? &tv : NULL);

Martin Hurton's avatar
Martin Hurton committed
349 350
        if (rc == -1) {
            errno_assert (errno == EINTR);
Martin Sustrik's avatar
Martin Sustrik committed
351
            continue;
Martin Hurton's avatar
Martin Hurton committed
352
        }
Martin Sustrik's avatar
Martin Sustrik committed
353

354 355
        //  Size is cached to avoid iteration through just added descriptors.
        for (fd_entries_t::size_type i = 0, size = fd_entries.size (); i < size && rc > 0; ++i) {
356
            if (fd_entries [i].fd == retired_fd)
Martin Sustrik's avatar
Martin Sustrik committed
357
                continue;
358

359 360
            if (FD_ISSET (fd_entries [i].fd, &local_fds_set.read)) {
                fd_entries [i].events->in_event ();
361 362 363
                --rc;
            }

364
            if (fd_entries [i].fd == retired_fd || rc == 0)
Martin Sustrik's avatar
Martin Sustrik committed
365
                continue;
366

367 368
            if (FD_ISSET (fd_entries [i].fd, &local_fds_set.write)) {
                fd_entries [i].events->out_event ();
369 370 371
                --rc;
            }

372
            if (fd_entries [i].fd == retired_fd || rc == 0)
Martin Sustrik's avatar
Martin Sustrik committed
373
                continue;
374

375 376
            if (FD_ISSET (fd_entries [i].fd, &local_fds_set.error)) {
                fd_entries [i].events->in_event ();
377 378
                --rc;
            }
Martin Sustrik's avatar
Martin Sustrik committed
379 380 381 382
        }

        if (retired) {
            retired = false;
383 384
            fd_entries.erase (std::remove_if (fd_entries.begin (), fd_entries.end (),
                is_retired_fd), fd_entries.end ());
Martin Sustrik's avatar
Martin Sustrik committed
385
        }
386
#endif
Martin Sustrik's avatar
Martin Sustrik committed
387 388 389
    }
}

Martin Sustrik's avatar
Martin Sustrik committed
390
void zmq::select_t::worker_routine (void *arg_)
Martin Sustrik's avatar
Martin Sustrik committed
391 392 393
{
    ((select_t*) arg_)->loop ();
}
394

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
zmq::select_t::fds_set_t::fds_set_t ()
{
    FD_ZERO (&read);
    FD_ZERO (&write);
    FD_ZERO (&error);
}

zmq::select_t::fds_set_t::fds_set_t (const fds_set_t& other_)
{
    memcpy (&read, &other_.read, sizeof other_.read);
    memcpy (&write, &other_.write, sizeof other_.write);
    memcpy (&error, &other_.error, sizeof other_.error);
}

zmq::select_t::fds_set_t& zmq::select_t::fds_set_t::operator= (const fds_set_t& other_)
{
    memcpy (&read, &other_.read, sizeof other_.read);
    memcpy (&write, &other_.write, sizeof other_.write);
    memcpy (&error, &other_.error, sizeof other_.error);
    return *this;
}

void zmq::select_t::fds_set_t::remove_fd (const fd_t& fd_)
{
    FD_CLR (fd_, &read);
    FD_CLR (fd_, &write);
    FD_CLR (fd_, &error);
}

424 425 426 427 428
bool zmq::select_t::is_retired_fd (const fd_entry_t &entry)
{
    return (entry.fd == retired_fd);
}

429 430 431
#if defined ZMQ_HAVE_WINDOWS
u_short zmq::select_t::get_fd_family (fd_t fd_)
{
432 433 434
    //  Use sockaddr_storage instead of sockaddr to accomodate differect structure sizes
    sockaddr_storage addr = { 0 };
    int addr_size = sizeof addr;
435

436 437
    int type;
    int type_length = sizeof(int);
438

439 440 441 442 443 444 445 446 447 448 449
    int rc = getsockopt(fd_, SOL_SOCKET, SO_TYPE, (char*) &type, &type_length);

    if (rc == 0) {
        if (type == SOCK_DGRAM)
            return AF_INET;
        else {
            rc = getsockname(fd_, (sockaddr *)&addr, &addr_size);

            //  AF_INET and AF_INET6 can be mixed in select
            //  TODO: If proven otherwise, should simply return addr.sa_family
            if (rc != SOCKET_ERROR)
450
                return addr.ss_family == AF_INET6 ? AF_INET : addr.ss_family;
451
        }
452
    }
453

454
    return AF_UNSPEC;
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
}

zmq::select_t::family_entry_t::family_entry_t () :
    retired (false)
{
}


zmq::select_t::wsa_events_t::wsa_events_t ()
{
    events [0] = WSACreateEvent ();
    wsa_assert (events [0] != WSA_INVALID_EVENT);
    events [1] = WSACreateEvent ();
    wsa_assert (events [1] != WSA_INVALID_EVENT);
    events [2] = WSACreateEvent ();
    wsa_assert (events [2] != WSA_INVALID_EVENT);
    events [3] = WSACreateEvent ();
    wsa_assert (events [3] != WSA_INVALID_EVENT);
}

zmq::select_t::wsa_events_t::~wsa_events_t ()
{
    wsa_assert (WSACloseEvent (events [0]));
    wsa_assert (WSACloseEvent (events [1]));
    wsa_assert (WSACloseEvent (events [2]));
    wsa_assert (WSACloseEvent (events [3]));
}
#endif

484
#endif