selectmodule.c 67.8 KB
Newer Older
1
/* select - Module containing unix select(2) call.
2 3 4
   Under Unix, the file descriptors are small integers.
   Under Win32, select only exists for sockets, and sockets may
   have any value except INVALID_SOCKET.
5
*/
6

7
#include "Python.h"
Christian Heimes's avatar
Christian Heimes committed
8
#include <structmember.h>
9

10 11 12 13 14 15 16 17
#ifdef HAVE_SYS_DEVPOLL_H
#include <sys/resource.h>
#include <sys/devpoll.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif

18 19 20 21 22 23 24
#ifdef __APPLE__
    /* Perform runtime testing for a broken poll on OSX to make it easier
     * to use the same binary on multiple releases of the OS.
     */
#undef HAVE_BROKEN_POLL
#endif

25 26 27 28 29 30 31 32
/* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined.
   64 is too small (too many people have bumped into that limit).
   Here we boost it.
   Users who want even more than the boosted limit should #define
   FD_SETSIZE higher before this; e.g., via compiler /D switch.
*/
#if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
#define FD_SETSIZE 512
33
#endif
34

Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
35
#if defined(HAVE_POLL_H)
36
#include <poll.h>
Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
37 38
#elif defined(HAVE_SYS_POLL_H)
#include <sys/poll.h>
39
#endif
Guido van Rossum's avatar
Guido van Rossum committed
40

41 42
#ifdef __sgi
/* This is missing from unistd.h */
43
extern void bzero(void *, int);
44 45
#endif

46
#ifdef HAVE_SYS_TYPES_H
47
#include <sys/types.h>
48
#endif
49

50
#ifdef MS_WINDOWS
51
#  define WIN32_LEAN_AND_MEAN
52
#  include <winsock.h>
53
#else
54
#  define SOCKET int
Skip Montanaro's avatar
Skip Montanaro committed
55
#  if defined(__VMS)
56 57
#    include <socket.h>
#  endif
58
#endif
59

60 61
/* list of Python objects and their file descriptor */
typedef struct {
62 63 64
    PyObject *obj;                           /* owned reference */
    SOCKET fd;
    int sentinel;                            /* -1 == sentinel */
65 66
} pylist;

67
static void
68
reap_obj(pylist fd2obj[FD_SETSIZE + 1])
69
{
70 71 72 73 74 75
    int i;
    for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
        Py_XDECREF(fd2obj[i].obj);
        fd2obj[i].obj = NULL;
    }
    fd2obj[0].sentinel = -1;
76 77 78
}


79 80 81
/* returns -1 and sets the Python exception if an error occurred, otherwise
   returns a number >= 0
*/
82
static int
83
seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
84
{
85 86
    int max = -1;
    int index = 0;
87
    Py_ssize_t i, len = -1;
88 89 90 91 92 93
    PyObject* fast_seq = NULL;
    PyObject* o = NULL;

    fd2obj[0].obj = (PyObject*)0;            /* set list to zero size */
    FD_ZERO(set);

94
    fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
95 96
    if (!fast_seq)
        return -1;
97

98
    len = PySequence_Fast_GET_SIZE(fast_seq);
99

100 101
    for (i = 0; i < len; i++)  {
        SOCKET v;
102

103 104
        /* any intervening fileno() calls could decr this refcnt */
        if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
105
            goto finally;
106

107 108 109
        Py_INCREF(o);
        v = PyObject_AsFileDescriptor( o );
        if (v == -1) goto finally;
110

111
#if defined(_MSC_VER)
112
        max = 0;                             /* not used for Win32 */
113
#else  /* !_MSC_VER */
114
        if (!_PyIsSelectable_fd(v)) {
115 116 117 118 119 120
            PyErr_SetString(PyExc_ValueError,
                        "filedescriptor out of range in select()");
            goto finally;
        }
        if (v > max)
            max = v;
121
#endif /* _MSC_VER */
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        FD_SET(v, set);

        /* add object and its file descriptor to the list */
        if (index >= FD_SETSIZE) {
            PyErr_SetString(PyExc_ValueError,
                          "too many file descriptors in select()");
            goto finally;
        }
        fd2obj[index].obj = o;
        fd2obj[index].fd = v;
        fd2obj[index].sentinel = 0;
        fd2obj[++index].sentinel = -1;
    }
    Py_DECREF(fast_seq);
    return max+1;
137 138

  finally:
139 140 141
    Py_XDECREF(o);
    Py_DECREF(fast_seq);
    return -1;
142 143
}

144 145
/* returns NULL and sets the Python exception if an error occurred */
static PyObject *
146
set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
147
{
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    int i, j, count=0;
    PyObject *list, *o;
    SOCKET fd;

    for (j = 0; fd2obj[j].sentinel >= 0; j++) {
        if (FD_ISSET(fd2obj[j].fd, set))
            count++;
    }
    list = PyList_New(count);
    if (!list)
        return NULL;

    i = 0;
    for (j = 0; fd2obj[j].sentinel >= 0; j++) {
        fd = fd2obj[j].fd;
        if (FD_ISSET(fd, set)) {
            o = fd2obj[j].obj;
            fd2obj[j].obj = NULL;
            /* transfer ownership */
            if (PyList_SetItem(list, i, o) < 0)
                goto finally;

            i++;
        }
    }
    return list;
174
  finally:
175 176
    Py_DECREF(list);
    return NULL;
177
}
178

179 180 181 182 183
#undef SELECT_USES_HEAP
#if FD_SETSIZE > 1024
#define SELECT_USES_HEAP
#endif /* FD_SETSIZE > 1024 */

184
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
185
select_select(PyObject *self, PyObject *args)
186
{
187
#ifdef SELECT_USES_HEAP
188
    pylist *rfd2obj, *wfd2obj, *efd2obj;
189
#else  /* !SELECT_USES_HEAP */
190 191 192 193 194 195 196 197 198
    /* XXX: All this should probably be implemented as follows:
     * - find the highest descriptor we're interested in
     * - add one
     * - that's the size
     * See: Stevens, APitUE, $12.5.1
     */
    pylist rfd2obj[FD_SETSIZE + 1];
    pylist wfd2obj[FD_SETSIZE + 1];
    pylist efd2obj[FD_SETSIZE + 1];
199
#endif /* SELECT_USES_HEAP */
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    PyObject *ifdlist, *ofdlist, *efdlist;
    PyObject *ret = NULL;
    PyObject *tout = Py_None;
    fd_set ifdset, ofdset, efdset;
    struct timeval tv, *tvp;
    int imax, omax, emax, max;
    int n;

    /* convert arguments */
    if (!PyArg_UnpackTuple(args, "select", 3, 4,
                          &ifdlist, &ofdlist, &efdlist, &tout))
        return NULL;

    if (tout == Py_None)
        tvp = (struct timeval *)0;
    else if (!PyNumber_Check(tout)) {
        PyErr_SetString(PyExc_TypeError,
                        "timeout must be a float or None");
        return NULL;
    }
    else {
221 222 223 224 225 226 227 228 229
#ifdef MS_WINDOWS
        time_t sec;
        if (_PyTime_ObjectToTimeval(tout, &sec, &tv.tv_usec) == -1)
            return NULL;
        assert(sizeof(tv.tv_sec) == sizeof(long));
#if SIZEOF_TIME_T > SIZEOF_LONG
        if (sec > LONG_MAX) {
            PyErr_SetString(PyExc_OverflowError,
                            "timeout is too large");
230
            return NULL;
231 232 233 234
        }
#endif
        tv.tv_sec = (long)sec;
#else
235 236
        /* 64-bit OS X has struct timeval.tv_usec as an int (and thus still 4
           bytes as required), but no longer defined by a long. */
237
        long tv_usec;
238
        if (_PyTime_ObjectToTimeval(tout, &tv.tv_sec, &tv_usec) == -1)
239
            return NULL;
240
        tv.tv_usec = tv_usec;
241
#endif
242 243
        if (tv.tv_sec < 0) {
            PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
244 245 246 247
            return NULL;
        }
        tvp = &tv;
    }
248 249


250
#ifdef SELECT_USES_HEAP
251 252 253 254 255 256 257 258 259 260
    /* Allocate memory for the lists */
    rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
    wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
    efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
    if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
        if (rfd2obj) PyMem_DEL(rfd2obj);
        if (wfd2obj) PyMem_DEL(wfd2obj);
        if (efd2obj) PyMem_DEL(efd2obj);
        return PyErr_NoMemory();
    }
261
#endif /* SELECT_USES_HEAP */
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    /* Convert sequences to fd_sets, and get maximum fd number
     * propagates the Python exception set in seq2set()
     */
    rfd2obj[0].sentinel = -1;
    wfd2obj[0].sentinel = -1;
    efd2obj[0].sentinel = -1;
    if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
        goto finally;
    if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
        goto finally;
    if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
        goto finally;
    max = imax;
    if (omax > max) max = omax;
    if (emax > max) max = emax;

    Py_BEGIN_ALLOW_THREADS
    n = select(max, &ifdset, &ofdset, &efdset, tvp);
    Py_END_ALLOW_THREADS
281

282
#ifdef MS_WINDOWS
283
    if (n == SOCKET_ERROR) {
284
        PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
285
    }
286
#else
287
    if (n < 0) {
288
        PyErr_SetFromErrno(PyExc_OSError);
289
    }
290
#endif
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    else {
        /* any of these three calls can raise an exception.  it's more
           convenient to test for this after all three calls... but
           is that acceptable?
        */
        ifdlist = set2list(&ifdset, rfd2obj);
        ofdlist = set2list(&ofdset, wfd2obj);
        efdlist = set2list(&efdset, efd2obj);
        if (PyErr_Occurred())
            ret = NULL;
        else
            ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);

        Py_DECREF(ifdlist);
        Py_DECREF(ofdlist);
        Py_DECREF(efdlist);
    }

309
  finally:
310 311 312
    reap_obj(rfd2obj);
    reap_obj(wfd2obj);
    reap_obj(efd2obj);
313
#ifdef SELECT_USES_HEAP
314 315 316
    PyMem_DEL(rfd2obj);
    PyMem_DEL(wfd2obj);
    PyMem_DEL(efd2obj);
317
#endif /* SELECT_USES_HEAP */
318
    return ret;
319 320
}

321
#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
322
/*
323 324 325 326
 * poll() support
 */

typedef struct {
327 328 329 330 331
    PyObject_HEAD
    PyObject *dict;
    int ufd_uptodate;
    int ufd_len;
    struct pollfd *ufds;
332 333
} pollObject;

334
static PyTypeObject poll_Type;
335

336
/* Update the malloc'ed array of pollfds to match the dictionary
337 338 339 340 341 342
   contained within a pollObject.  Return 1 on success, 0 on an error.
*/

static int
update_ufd_array(pollObject *self)
{
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    Py_ssize_t i, pos;
    PyObject *key, *value;
    struct pollfd *old_ufds = self->ufds;

    self->ufd_len = PyDict_Size(self->dict);
    PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
    if (self->ufds == NULL) {
        self->ufds = old_ufds;
        PyErr_NoMemory();
        return 0;
    }

    i = pos = 0;
    while (PyDict_Next(self->dict, &pos, &key, &value)) {
        self->ufds[i].fd = PyLong_AsLong(key);
        self->ufds[i].events = (short)PyLong_AsLong(value);
        i++;
    }
    self->ufd_uptodate = 1;
    return 1;
363 364
}

365
PyDoc_STRVAR(poll_register_doc,
366 367
"register(fd [, eventmask] ) -> None\n\n\
Register a file descriptor with the polling object.\n\
368 369
fd -- either an integer, or an object with a fileno() method returning an\n\
      int.\n\
370
events -- an optional bitmask describing the type of events to check for");
371 372

static PyObject *
373
poll_register(pollObject *self, PyObject *args)
374
{
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    PyObject *o, *key, *value;
    int fd, events = POLLIN | POLLPRI | POLLOUT;
    int err;

    if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) {
        return NULL;
    }

    fd = PyObject_AsFileDescriptor(o);
    if (fd == -1) return NULL;

    /* Add entry to the internal dictionary: the key is the
       file descriptor, and the value is the event mask. */
    key = PyLong_FromLong(fd);
    if (key == NULL)
        return NULL;
    value = PyLong_FromLong(events);
    if (value == NULL) {
        Py_DECREF(key);
        return NULL;
    }
    err = PyDict_SetItem(self->dict, key, value);
    Py_DECREF(key);
    Py_DECREF(value);
    if (err < 0)
        return NULL;

    self->ufd_uptodate = 0;

    Py_INCREF(Py_None);
    return Py_None;
406 407
}

Christian Heimes's avatar
Christian Heimes committed
408 409
PyDoc_STRVAR(poll_modify_doc,
"modify(fd, eventmask) -> None\n\n\
Christian Heimes's avatar
Christian Heimes committed
410
Modify an already registered file descriptor.\n\
Christian Heimes's avatar
Christian Heimes committed
411 412 413 414 415 416 417
fd -- either an integer, or an object with a fileno() method returning an\n\
      int.\n\
events -- an optional bitmask describing the type of events to check for");

static PyObject *
poll_modify(pollObject *self, PyObject *args)
{
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    PyObject *o, *key, *value;
    int fd, events;
    int err;

    if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) {
        return NULL;
    }

    fd = PyObject_AsFileDescriptor(o);
    if (fd == -1) return NULL;

    /* Modify registered fd */
    key = PyLong_FromLong(fd);
    if (key == NULL)
        return NULL;
    if (PyDict_GetItem(self->dict, key) == NULL) {
        errno = ENOENT;
435
        PyErr_SetFromErrno(PyExc_OSError);
436
        Py_DECREF(key);
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
        return NULL;
    }
    value = PyLong_FromLong(events);
    if (value == NULL) {
        Py_DECREF(key);
        return NULL;
    }
    err = PyDict_SetItem(self->dict, key, value);
    Py_DECREF(key);
    Py_DECREF(value);
    if (err < 0)
        return NULL;

    self->ufd_uptodate = 0;

    Py_INCREF(Py_None);
    return Py_None;
Christian Heimes's avatar
Christian Heimes committed
454 455 456
}


457
PyDoc_STRVAR(poll_unregister_doc,
458
"unregister(fd) -> None\n\n\
459
Remove a file descriptor being tracked by the polling object.");
460 461

static PyObject *
462
poll_unregister(pollObject *self, PyObject *o)
463
{
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    PyObject *key;
    int fd;

    fd = PyObject_AsFileDescriptor( o );
    if (fd == -1)
        return NULL;

    /* Check whether the fd is already in the array */
    key = PyLong_FromLong(fd);
    if (key == NULL)
        return NULL;

    if (PyDict_DelItem(self->dict, key) == -1) {
        Py_DECREF(key);
        /* This will simply raise the KeyError set by PyDict_DelItem
           if the file descriptor isn't registered. */
        return NULL;
    }

    Py_DECREF(key);
    self->ufd_uptodate = 0;

    Py_INCREF(Py_None);
    return Py_None;
488 489
}

490
PyDoc_STRVAR(poll_poll_doc,
491 492
"poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
Polls the set of registered file descriptors, returning a list containing \n\
493
any descriptors that have events or errors to report.");
494 495

static PyObject *
496
poll_poll(pollObject *self, PyObject *args)
497
{
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    PyObject *result_list = NULL, *tout = NULL;
    int timeout = 0, poll_result, i, j;
    PyObject *value = NULL, *num = NULL;

    if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {
        return NULL;
    }

    /* Check values for timeout */
    if (tout == NULL || tout == Py_None)
        timeout = -1;
    else if (!PyNumber_Check(tout)) {
        PyErr_SetString(PyExc_TypeError,
                        "timeout must be an integer or None");
        return NULL;
    }
    else {
        tout = PyNumber_Long(tout);
        if (!tout)
            return NULL;
        timeout = PyLong_AsLong(tout);
        Py_DECREF(tout);
        if (timeout == -1 && PyErr_Occurred())
            return NULL;
    }

    /* Ensure the ufd array is up to date */
    if (!self->ufd_uptodate)
        if (update_ufd_array(self) == 0)
            return NULL;

    /* call poll() */
    Py_BEGIN_ALLOW_THREADS
    poll_result = poll(self->ufds, self->ufd_len, timeout);
    Py_END_ALLOW_THREADS

    if (poll_result < 0) {
535
        PyErr_SetFromErrno(PyExc_OSError);
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
        return NULL;
    }

    /* build the result list */

    result_list = PyList_New(poll_result);
    if (!result_list)
        return NULL;
    else {
        for (i = 0, j = 0; j < poll_result; j++) {
            /* skip to the next fired descriptor */
            while (!self->ufds[i].revents) {
                i++;
            }
            /* if we hit a NULL return, set value to NULL
               and break out of loop; code at end will
               clean up result_list */
            value = PyTuple_New(2);
            if (value == NULL)
                goto error;
            num = PyLong_FromLong(self->ufds[i].fd);
            if (num == NULL) {
                Py_DECREF(value);
                goto error;
            }
            PyTuple_SET_ITEM(value, 0, num);

            /* The &0xffff is a workaround for AIX.  'revents'
               is a 16-bit short, and IBM assigned POLLNVAL
               to be 0x8000, so the conversion to int results
               in a negative number. See SF bug #923315. */
            num = PyLong_FromLong(self->ufds[i].revents & 0xffff);
            if (num == NULL) {
                Py_DECREF(value);
                goto error;
            }
            PyTuple_SET_ITEM(value, 1, num);
            if ((PyList_SetItem(result_list, j, value)) == -1) {
                Py_DECREF(value);
                goto error;
            }
            i++;
        }
    }
    return result_list;
581 582

  error:
583 584
    Py_DECREF(result_list);
    return NULL;
585 586 587
}

static PyMethodDef poll_methods[] = {
588 589 590 591 592 593 594 595 596
    {"register",        (PyCFunction)poll_register,
     METH_VARARGS,  poll_register_doc},
    {"modify",          (PyCFunction)poll_modify,
     METH_VARARGS,  poll_modify_doc},
    {"unregister",      (PyCFunction)poll_unregister,
     METH_O,        poll_unregister_doc},
    {"poll",            (PyCFunction)poll_poll,
     METH_VARARGS,  poll_poll_doc},
    {NULL,              NULL}           /* sentinel */
597 598 599
};

static pollObject *
600
newPollObject(void)
601
{
602 603 604 605 606 607 608 609 610 611 612 613 614 615
    pollObject *self;
    self = PyObject_New(pollObject, &poll_Type);
    if (self == NULL)
        return NULL;
    /* ufd_uptodate is a Boolean, denoting whether the
       array pointed to by ufds matches the contents of the dictionary. */
    self->ufd_uptodate = 0;
    self->ufds = NULL;
    self->dict = PyDict_New();
    if (self->dict == NULL) {
        Py_DECREF(self);
        return NULL;
    }
    return self;
616 617 618 619 620
}

static void
poll_dealloc(pollObject *self)
{
621 622 623 624
    if (self->ufds != NULL)
        PyMem_DEL(self->ufds);
    Py_XDECREF(self->dict);
    PyObject_Del(self);
625 626
}

627
static PyTypeObject poll_Type = {
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
    /* The ob_type field must be initialized in the module init function
     * to be portable to Windows without using C++. */
    PyVarObject_HEAD_INIT(NULL, 0)
    "select.poll",              /*tp_name*/
    sizeof(pollObject),         /*tp_basicsize*/
    0,                          /*tp_itemsize*/
    /* methods */
    (destructor)poll_dealloc, /*tp_dealloc*/
    0,                          /*tp_print*/
    0,                          /*tp_getattr*/
    0,                      /*tp_setattr*/
    0,                          /*tp_reserved*/
    0,                          /*tp_repr*/
    0,                          /*tp_as_number*/
    0,                          /*tp_as_sequence*/
    0,                          /*tp_as_mapping*/
    0,                          /*tp_hash*/
    0,                          /*tp_call*/
    0,                          /*tp_str*/
    0,                          /*tp_getattro*/
    0,                          /*tp_setattro*/
    0,                          /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT,         /*tp_flags*/
    0,                          /*tp_doc*/
    0,                          /*tp_traverse*/
    0,                          /*tp_clear*/
    0,                          /*tp_richcompare*/
    0,                          /*tp_weaklistoffset*/
    0,                          /*tp_iter*/
    0,                          /*tp_iternext*/
    poll_methods,               /*tp_methods*/
659 660
};

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
#ifdef HAVE_SYS_DEVPOLL_H
typedef struct {
    PyObject_HEAD
    int fd_devpoll;
    int max_n_fds;
    int n_fds;
    struct pollfd *fds;
} devpollObject;

static PyTypeObject devpoll_Type;

static int devpoll_flush(devpollObject *self)
{
    int size, n;

    if (!self->n_fds) return 0;

    size = sizeof(struct pollfd)*self->n_fds;
    self->n_fds = 0;

    Py_BEGIN_ALLOW_THREADS
    n = write(self->fd_devpoll, self->fds, size);
    Py_END_ALLOW_THREADS

    if (n == -1 ) {
        PyErr_SetFromErrno(PyExc_IOError);
        return -1;
    }
    if (n < size) {
        /*
        ** Data writed to /dev/poll is a binary data structure. It is not
        ** clear what to do if a partial write occurred. For now, raise
        ** an exception and see if we actually found this problem in
        ** the wild.
        ** See http://bugs.python.org/issue6397.
        */
        PyErr_Format(PyExc_IOError, "failed to write all pollfds. "
                "Please, report at http://bugs.python.org/. "
                "Data to report: Size tried: %d, actual size written: %d.",
                size, n);
        return -1;
    }
    return 0;
}

static PyObject *
internal_devpoll_register(devpollObject *self, PyObject *args, int remove)
{
    PyObject *o;
    int fd, events = POLLIN | POLLPRI | POLLOUT;

    if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) {
        return NULL;
    }

    fd = PyObject_AsFileDescriptor(o);
    if (fd == -1) return NULL;

    if (remove) {
        self->fds[self->n_fds].fd = fd;
        self->fds[self->n_fds].events = POLLREMOVE;

        if (++self->n_fds == self->max_n_fds) {
            if (devpoll_flush(self))
                return NULL;
        }
    }

    self->fds[self->n_fds].fd = fd;
    self->fds[self->n_fds].events = events;

    if (++self->n_fds == self->max_n_fds) {
        if (devpoll_flush(self))
            return NULL;
    }

    Py_RETURN_NONE;
}

PyDoc_STRVAR(devpoll_register_doc,
"register(fd [, eventmask] ) -> None\n\n\
Register a file descriptor with the polling object.\n\
fd -- either an integer, or an object with a fileno() method returning an\n\
      int.\n\
events -- an optional bitmask describing the type of events to check for");

static PyObject *
devpoll_register(devpollObject *self, PyObject *args)
{
    return internal_devpoll_register(self, args, 0);
}

PyDoc_STRVAR(devpoll_modify_doc,
"modify(fd[, eventmask]) -> None\n\n\
Modify a possible already registered file descriptor.\n\
fd -- either an integer, or an object with a fileno() method returning an\n\
      int.\n\
events -- an optional bitmask describing the type of events to check for");

static PyObject *
devpoll_modify(devpollObject *self, PyObject *args)
{
    return internal_devpoll_register(self, args, 1);
}


PyDoc_STRVAR(devpoll_unregister_doc,
"unregister(fd) -> None\n\n\
Remove a file descriptor being tracked by the polling object.");

static PyObject *
devpoll_unregister(devpollObject *self, PyObject *o)
{
    int fd;

    fd = PyObject_AsFileDescriptor( o );
    if (fd == -1)
        return NULL;

    self->fds[self->n_fds].fd = fd;
    self->fds[self->n_fds].events = POLLREMOVE;

    if (++self->n_fds == self->max_n_fds) {
        if (devpoll_flush(self))
            return NULL;
    }

    Py_RETURN_NONE;
}

PyDoc_STRVAR(devpoll_poll_doc,
"poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
Polls the set of registered file descriptors, returning a list containing \n\
any descriptors that have events or errors to report.");

static PyObject *
devpoll_poll(devpollObject *self, PyObject *args)
{
    struct dvpoll dvp;
    PyObject *result_list = NULL, *tout = NULL;
    int poll_result, i;
    long timeout;
    PyObject *value, *num1, *num2;

    if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {
        return NULL;
    }

    /* Check values for timeout */
    if (tout == NULL || tout == Py_None)
        timeout = -1;
    else if (!PyNumber_Check(tout)) {
        PyErr_SetString(PyExc_TypeError,
                        "timeout must be an integer or None");
        return NULL;
    }
    else {
        tout = PyNumber_Long(tout);
        if (!tout)
            return NULL;
        timeout = PyLong_AsLong(tout);
        Py_DECREF(tout);
        if (timeout == -1 && PyErr_Occurred())
            return NULL;
    }

    if ((timeout < -1) || (timeout > INT_MAX)) {
        PyErr_SetString(PyExc_OverflowError,
                        "timeout is out of range");
        return NULL;
    }

    if (devpoll_flush(self))
        return NULL;

    dvp.dp_fds = self->fds;
    dvp.dp_nfds = self->max_n_fds;
    dvp.dp_timeout = timeout;

    /* call devpoll() */
    Py_BEGIN_ALLOW_THREADS
    poll_result = ioctl(self->fd_devpoll, DP_POLL, &dvp);
    Py_END_ALLOW_THREADS

    if (poll_result < 0) {
        PyErr_SetFromErrno(PyExc_IOError);
        return NULL;
    }

    /* build the result list */

    result_list = PyList_New(poll_result);
    if (!result_list)
        return NULL;
    else {
        for (i = 0; i < poll_result; i++) {
            num1 = PyLong_FromLong(self->fds[i].fd);
            num2 = PyLong_FromLong(self->fds[i].revents);
            if ((num1 == NULL) || (num2 == NULL)) {
                Py_XDECREF(num1);
                Py_XDECREF(num2);
                goto error;
            }
            value = PyTuple_Pack(2, num1, num2);
            Py_DECREF(num1);
            Py_DECREF(num2);
            if (value == NULL)
                goto error;
            if ((PyList_SetItem(result_list, i, value)) == -1) {
                Py_DECREF(value);
                goto error;
            }
        }
    }

    return result_list;

  error:
    Py_DECREF(result_list);
    return NULL;
}

static PyMethodDef devpoll_methods[] = {
    {"register",        (PyCFunction)devpoll_register,
     METH_VARARGS,  devpoll_register_doc},
    {"modify",          (PyCFunction)devpoll_modify,
     METH_VARARGS,  devpoll_modify_doc},
    {"unregister",      (PyCFunction)devpoll_unregister,
     METH_O,        devpoll_unregister_doc},
    {"poll",            (PyCFunction)devpoll_poll,
     METH_VARARGS,  devpoll_poll_doc},
    {NULL,              NULL}           /* sentinel */
};

static devpollObject *
newDevPollObject(void)
{
    devpollObject *self;
    int fd_devpoll, limit_result;
    struct pollfd *fds;
    struct rlimit limit;

    Py_BEGIN_ALLOW_THREADS
    /*
    ** If we try to process more that getrlimit()
    ** fds, the kernel will give an error, so
    ** we set the limit here. It is a dynamic
    ** value, because we can change rlimit() anytime.
    */
    limit_result = getrlimit(RLIMIT_NOFILE, &limit);
    if (limit_result != -1)
        fd_devpoll = open("/dev/poll", O_RDWR);
    Py_END_ALLOW_THREADS

    if (limit_result == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }
    if (fd_devpoll == -1) {
        PyErr_SetFromErrnoWithFilename(PyExc_IOError, "/dev/poll");
        return NULL;
    }

    fds = PyMem_NEW(struct pollfd, limit.rlim_cur);
    if (fds == NULL) {
        close(fd_devpoll);
        PyErr_NoMemory();
        return NULL;
    }

    self = PyObject_New(devpollObject, &devpoll_Type);
    if (self == NULL) {
        close(fd_devpoll);
        PyMem_DEL(fds);
        return NULL;
    }
    self->fd_devpoll = fd_devpoll;
    self->max_n_fds = limit.rlim_cur;
    self->n_fds = 0;
    self->fds = fds;

    return self;
}

static void
devpoll_dealloc(devpollObject *self)
{
    Py_BEGIN_ALLOW_THREADS
    close(self->fd_devpoll);
    Py_END_ALLOW_THREADS

    PyMem_DEL(self->fds);

    PyObject_Del(self);
}

static PyTypeObject devpoll_Type = {
    /* The ob_type field must be initialized in the module init function
     * to be portable to Windows without using C++. */
    PyVarObject_HEAD_INIT(NULL, 0)
    "select.devpoll",           /*tp_name*/
    sizeof(devpollObject),      /*tp_basicsize*/
    0,                          /*tp_itemsize*/
    /* methods */
    (destructor)devpoll_dealloc, /*tp_dealloc*/
    0,                          /*tp_print*/
    0,                          /*tp_getattr*/
    0,                          /*tp_setattr*/
    0,                          /*tp_reserved*/
    0,                          /*tp_repr*/
    0,                          /*tp_as_number*/
    0,                          /*tp_as_sequence*/
    0,                          /*tp_as_mapping*/
    0,                          /*tp_hash*/
    0,                          /*tp_call*/
    0,                          /*tp_str*/
    0,                          /*tp_getattro*/
    0,                          /*tp_setattro*/
    0,                          /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT,         /*tp_flags*/
    0,                          /*tp_doc*/
    0,                          /*tp_traverse*/
    0,                          /*tp_clear*/
    0,                          /*tp_richcompare*/
    0,                          /*tp_weaklistoffset*/
    0,                          /*tp_iter*/
    0,                          /*tp_iternext*/
    devpoll_methods,            /*tp_methods*/
};
#endif  /* HAVE_SYS_DEVPOLL_H */



994
PyDoc_STRVAR(poll_doc,
995
"Returns a polling object, which supports registering and\n\
996
unregistering file descriptors, and then polling them for I/O events.");
997 998

static PyObject *
999
select_poll(PyObject *self, PyObject *unused)
1000
{
1001
    return (PyObject *)newPollObject();
1002
}
1003

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
#ifdef HAVE_SYS_DEVPOLL_H
PyDoc_STRVAR(devpoll_doc,
"Returns a polling object, which supports registering and\n\
unregistering file descriptors, and then polling them for I/O events.");

static PyObject *
select_devpoll(PyObject *self, PyObject *unused)
{
    return (PyObject *)newDevPollObject();
}
#endif


1017
#ifdef __APPLE__
1018
/*
1019 1020 1021 1022 1023 1024
 * On some systems poll() sets errno on invalid file descriptors. We test
 * for this at runtime because this bug may be fixed or introduced between
 * OS releases.
 */
static int select_have_broken_poll(void)
{
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
    int poll_test;
    int filedes[2];

    struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };

    /* Create a file descriptor to make invalid */
    if (pipe(filedes) < 0) {
        return 1;
    }
    poll_struct.fd = filedes[0];
    close(filedes[0]);
    close(filedes[1]);
    poll_test = poll(&poll_struct, 1, 0);
    if (poll_test < 0) {
        return 1;
    } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
        return 1;
    }
    return 0;
1044 1045 1046 1047
}
#endif /* __APPLE__ */

#endif /* HAVE_POLL */
1048

Christian Heimes's avatar
Christian Heimes committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
#ifdef HAVE_EPOLL
/* **************************************************************************
 *                      epoll interface for Linux 2.6
 *
 * Written by Christian Heimes
 * Inspired by Twisted's _epoll.pyx and select.poll()
 */

#ifdef HAVE_SYS_EPOLL_H
#include <sys/epoll.h>
#endif

typedef struct {
1062 1063
    PyObject_HEAD
    SOCKET epfd;                        /* epoll control file descriptor */
Christian Heimes's avatar
Christian Heimes committed
1064 1065 1066 1067 1068 1069 1070 1071
} pyEpoll_Object;

static PyTypeObject pyEpoll_Type;
#define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type))

static PyObject *
pyepoll_err_closed(void)
{
1072 1073
    PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd");
    return NULL;
Christian Heimes's avatar
Christian Heimes committed
1074 1075 1076 1077 1078
}

static int
pyepoll_internal_close(pyEpoll_Object *self)
{
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    int save_errno = 0;
    if (self->epfd >= 0) {
        int epfd = self->epfd;
        self->epfd = -1;
        Py_BEGIN_ALLOW_THREADS
        if (close(epfd) < 0)
            save_errno = errno;
        Py_END_ALLOW_THREADS
    }
    return save_errno;
Christian Heimes's avatar
Christian Heimes committed
1089 1090 1091
}

static PyObject *
1092
newPyEpoll_Object(PyTypeObject *type, int sizehint, int flags, SOCKET fd)
Christian Heimes's avatar
Christian Heimes committed
1093
{
1094 1095 1096 1097 1098 1099 1100 1101 1102
    pyEpoll_Object *self;

    assert(type != NULL && type->tp_alloc != NULL);
    self = (pyEpoll_Object *) type->tp_alloc(type, 0);
    if (self == NULL)
        return NULL;

    if (fd == -1) {
        Py_BEGIN_ALLOW_THREADS
1103
#ifdef HAVE_EPOLL_CREATE1
1104 1105 1106
        if (flags)
            self->epfd = epoll_create1(flags);
        else
1107
#endif
1108
        self->epfd = epoll_create(sizehint);
1109 1110 1111 1112 1113 1114 1115
        Py_END_ALLOW_THREADS
    }
    else {
        self->epfd = fd;
    }
    if (self->epfd < 0) {
        Py_DECREF(self);
1116
        PyErr_SetFromErrno(PyExc_OSError);
1117 1118 1119
        return NULL;
    }
    return (PyObject *)self;
Christian Heimes's avatar
Christian Heimes committed
1120 1121 1122 1123 1124 1125
}


static PyObject *
pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
1126
    int flags = 0, sizehint = FD_SETSIZE - 1;
1127
    static char *kwlist[] = {"sizehint", "flags", NULL};
Christian Heimes's avatar
Christian Heimes committed
1128

1129 1130 1131 1132 1133
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:epoll", kwlist,
                                     &sizehint, &flags))
        return NULL;
    if (sizehint < 0) {
        PyErr_SetString(PyExc_ValueError, "negative sizehint");
1134
        return NULL;
1135
    }
Christian Heimes's avatar
Christian Heimes committed
1136

1137
    return newPyEpoll_Object(type, sizehint, flags, -1);
Christian Heimes's avatar
Christian Heimes committed
1138 1139 1140 1141 1142 1143
}


static void
pyepoll_dealloc(pyEpoll_Object *self)
{
1144 1145
    (void)pyepoll_internal_close(self);
    Py_TYPE(self)->tp_free(self);
Christian Heimes's avatar
Christian Heimes committed
1146 1147 1148 1149 1150
}

static PyObject*
pyepoll_close(pyEpoll_Object *self)
{
1151 1152
    errno = pyepoll_internal_close(self);
    if (errno < 0) {
1153
        PyErr_SetFromErrno(PyExc_OSError);
1154 1155 1156
        return NULL;
    }
    Py_RETURN_NONE;
Christian Heimes's avatar
Christian Heimes committed
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
}

PyDoc_STRVAR(pyepoll_close_doc,
"close() -> None\n\
\n\
Close the epoll control file descriptor. Further operations on the epoll\n\
object will raise an exception.");

static PyObject*
pyepoll_get_closed(pyEpoll_Object *self)
{
1168 1169 1170 1171
    if (self->epfd < 0)
        Py_RETURN_TRUE;
    else
        Py_RETURN_FALSE;
Christian Heimes's avatar
Christian Heimes committed
1172 1173 1174 1175 1176
}

static PyObject*
pyepoll_fileno(pyEpoll_Object *self)
{
1177 1178 1179
    if (self->epfd < 0)
        return pyepoll_err_closed();
    return PyLong_FromLong(self->epfd);
Christian Heimes's avatar
Christian Heimes committed
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
}

PyDoc_STRVAR(pyepoll_fileno_doc,
"fileno() -> int\n\
\n\
Return the epoll control file descriptor.");

static PyObject*
pyepoll_fromfd(PyObject *cls, PyObject *args)
{
1190
    SOCKET fd;
Christian Heimes's avatar
Christian Heimes committed
1191

1192 1193
    if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
        return NULL;
Christian Heimes's avatar
Christian Heimes committed
1194

1195
    return newPyEpoll_Object((PyTypeObject*)cls, FD_SETSIZE - 1, 0, fd);
Christian Heimes's avatar
Christian Heimes committed
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
}

PyDoc_STRVAR(pyepoll_fromfd_doc,
"fromfd(fd) -> epoll\n\
\n\
Create an epoll object from a given control fd.");

static PyObject *
pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events)
{
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
    struct epoll_event ev;
    int result;
    int fd;

    if (epfd < 0)
        return pyepoll_err_closed();

    fd = PyObject_AsFileDescriptor(pfd);
    if (fd == -1) {
        return NULL;
    }

    switch(op) {
        case EPOLL_CTL_ADD:
        case EPOLL_CTL_MOD:
        ev.events = events;
        ev.data.fd = fd;
        Py_BEGIN_ALLOW_THREADS
        result = epoll_ctl(epfd, op, fd, &ev);
        Py_END_ALLOW_THREADS
        break;
        case EPOLL_CTL_DEL:
        /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
         * operation required a non-NULL pointer in event, even
         * though this argument is ignored. */
        Py_BEGIN_ALLOW_THREADS
        result = epoll_ctl(epfd, op, fd, &ev);
        if (errno == EBADF) {
            /* fd already closed */
            result = 0;
            errno = 0;
        }
        Py_END_ALLOW_THREADS
        break;
        default:
        result = -1;
        errno = EINVAL;
    }

    if (result < 0) {
1246
        PyErr_SetFromErrno(PyExc_OSError);
1247 1248 1249
        return NULL;
    }
    Py_RETURN_NONE;
Christian Heimes's avatar
Christian Heimes committed
1250 1251 1252 1253 1254
}

static PyObject *
pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
1255 1256 1257
    PyObject *pfd;
    unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;
    static char *kwlist[] = {"fd", "eventmask", NULL};
Christian Heimes's avatar
Christian Heimes committed
1258

1259 1260 1261 1262
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
                                     &pfd, &events)) {
        return NULL;
    }
Christian Heimes's avatar
Christian Heimes committed
1263

1264
    return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
Christian Heimes's avatar
Christian Heimes committed
1265 1266 1267
}

PyDoc_STRVAR(pyepoll_register_doc,
1268
"register(fd[, eventmask]) -> None\n\
Christian Heimes's avatar
Christian Heimes committed
1269
\n\
1270
Registers a new fd or raises an OSError if the fd is already registered.\n\
Christian Heimes's avatar
Christian Heimes committed
1271 1272
fd is the target file descriptor of the operation.\n\
events is a bit set composed of the various EPOLL constants; the default\n\
Christian Heimes's avatar
Christian Heimes committed
1273 1274 1275 1276 1277 1278 1279
is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\
\n\
The epoll interface supports all file descriptors that support poll.");

static PyObject *
pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
1280 1281 1282
    PyObject *pfd;
    unsigned int events;
    static char *kwlist[] = {"fd", "eventmask", NULL};
Christian Heimes's avatar
Christian Heimes committed
1283

1284 1285 1286 1287
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
                                     &pfd, &events)) {
        return NULL;
    }
Christian Heimes's avatar
Christian Heimes committed
1288

1289
    return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
Christian Heimes's avatar
Christian Heimes committed
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
}

PyDoc_STRVAR(pyepoll_modify_doc,
"modify(fd, eventmask) -> None\n\
\n\
fd is the target file descriptor of the operation\n\
events is a bit set composed of the various EPOLL constants");

static PyObject *
pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
1301 1302
    PyObject *pfd;
    static char *kwlist[] = {"fd", NULL};
Christian Heimes's avatar
Christian Heimes committed
1303

1304 1305 1306 1307
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
                                     &pfd)) {
        return NULL;
    }
Christian Heimes's avatar
Christian Heimes committed
1308

1309
    return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
Christian Heimes's avatar
Christian Heimes committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
}

PyDoc_STRVAR(pyepoll_unregister_doc,
"unregister(fd) -> None\n\
\n\
fd is the target file descriptor of the operation.");

static PyObject *
pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
    double dtimeout = -1.;
    int timeout;
    int maxevents = -1;
    int nfds, i;
    PyObject *elist = NULL, *etuple = NULL;
    struct epoll_event *evs = NULL;
    static char *kwlist[] = {"timeout", "maxevents", NULL};

    if (self->epfd < 0)
        return pyepoll_err_closed();

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist,
                                     &dtimeout, &maxevents)) {
        return NULL;
    }

    if (dtimeout < 0) {
        timeout = -1;
    }
    else if (dtimeout * 1000.0 > INT_MAX) {
        PyErr_SetString(PyExc_OverflowError,
                        "timeout is too large");
        return NULL;
    }
    else {
        timeout = (int)(dtimeout * 1000.0);
    }

    if (maxevents == -1) {
        maxevents = FD_SETSIZE-1;
    }
    else if (maxevents < 1) {
        PyErr_Format(PyExc_ValueError,
                     "maxevents must be greater than 0, got %d",
                     maxevents);
        return NULL;
    }

    evs = PyMem_New(struct epoll_event, maxevents);
    if (evs == NULL) {
        Py_DECREF(self);
        PyErr_NoMemory();
        return NULL;
    }

    Py_BEGIN_ALLOW_THREADS
    nfds = epoll_wait(self->epfd, evs, maxevents, timeout);
    Py_END_ALLOW_THREADS
    if (nfds < 0) {
1369
        PyErr_SetFromErrno(PyExc_OSError);
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
        goto error;
    }

    elist = PyList_New(nfds);
    if (elist == NULL) {
        goto error;
    }

    for (i = 0; i < nfds; i++) {
        etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
        if (etuple == NULL) {
            Py_CLEAR(elist);
            goto error;
        }
        PyList_SET_ITEM(elist, i, etuple);
    }
Christian Heimes's avatar
Christian Heimes committed
1386

Christian Heimes's avatar
Christian Heimes committed
1387
    error:
1388 1389
    PyMem_Free(evs);
    return elist;
Christian Heimes's avatar
Christian Heimes committed
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
}

PyDoc_STRVAR(pyepoll_poll_doc,
"poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\
\n\
Wait for events on the epoll file descriptor for a maximum time of timeout\n\
in seconds (as float). -1 makes poll wait indefinitely.\n\
Up to maxevents are returned to the caller.");

static PyMethodDef pyepoll_methods[] = {
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
    {"fromfd",          (PyCFunction)pyepoll_fromfd,
     METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},
    {"close",           (PyCFunction)pyepoll_close,     METH_NOARGS,
     pyepoll_close_doc},
    {"fileno",          (PyCFunction)pyepoll_fileno,    METH_NOARGS,
     pyepoll_fileno_doc},
    {"modify",          (PyCFunction)pyepoll_modify,
     METH_VARARGS | METH_KEYWORDS,      pyepoll_modify_doc},
    {"register",        (PyCFunction)pyepoll_register,
     METH_VARARGS | METH_KEYWORDS,      pyepoll_register_doc},
    {"unregister",      (PyCFunction)pyepoll_unregister,
     METH_VARARGS | METH_KEYWORDS,      pyepoll_unregister_doc},
    {"poll",            (PyCFunction)pyepoll_poll,
     METH_VARARGS | METH_KEYWORDS,      pyepoll_poll_doc},
    {NULL,      NULL},
Christian Heimes's avatar
Christian Heimes committed
1415 1416 1417
};

static PyGetSetDef pyepoll_getsetlist[] = {
1418 1419 1420
    {"closed", (getter)pyepoll_get_closed, NULL,
     "True if the epoll handler is closed"},
    {0},
Christian Heimes's avatar
Christian Heimes committed
1421 1422 1423
};

PyDoc_STRVAR(pyepoll_doc,
1424
"select.epoll(sizehint=-1, flags=0)\n\
Christian Heimes's avatar
Christian Heimes committed
1425 1426 1427 1428 1429 1430 1431 1432
\n\
Returns an epolling object\n\
\n\
sizehint must be a positive integer or -1 for the default size. The\n\
sizehint is used to optimize internal data structures. It doesn't limit\n\
the maximum number of monitored events.");

static PyTypeObject pyEpoll_Type = {
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
    PyVarObject_HEAD_INIT(NULL, 0)
    "select.epoll",                                     /* tp_name */
    sizeof(pyEpoll_Object),                             /* tp_basicsize */
    0,                                                  /* tp_itemsize */
    (destructor)pyepoll_dealloc,                        /* tp_dealloc */
    0,                                                  /* tp_print */
    0,                                                  /* tp_getattr */
    0,                                                  /* tp_setattr */
    0,                                                  /* tp_reserved */
    0,                                                  /* tp_repr */
    0,                                                  /* tp_as_number */
    0,                                                  /* tp_as_sequence */
    0,                                                  /* tp_as_mapping */
    0,                                                  /* tp_hash */
    0,                                                  /* tp_call */
    0,                                                  /* tp_str */
    PyObject_GenericGetAttr,                            /* tp_getattro */
    0,                                                  /* tp_setattro */
    0,                                                  /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                                 /* tp_flags */
    pyepoll_doc,                                        /* tp_doc */
    0,                                                  /* tp_traverse */
    0,                                                  /* tp_clear */
    0,                                                  /* tp_richcompare */
    0,                                                  /* tp_weaklistoffset */
    0,                                                  /* tp_iter */
    0,                                                  /* tp_iternext */
    pyepoll_methods,                                    /* tp_methods */
    0,                                                  /* tp_members */
    pyepoll_getsetlist,                                 /* tp_getset */
    0,                                                  /* tp_base */
    0,                                                  /* tp_dict */
    0,                                                  /* tp_descr_get */
    0,                                                  /* tp_descr_set */
    0,                                                  /* tp_dictoffset */
    0,                                                  /* tp_init */
    0,                                                  /* tp_alloc */
    pyepoll_new,                                        /* tp_new */
    0,                                                  /* tp_free */
Christian Heimes's avatar
Christian Heimes committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
};

#endif /* HAVE_EPOLL */

#ifdef HAVE_KQUEUE
/* **************************************************************************
 *                      kqueue interface for BSD
 *
 * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifdef HAVE_SYS_EVENT_H
#include <sys/event.h>
#endif

PyDoc_STRVAR(kqueue_event_doc,
Benjamin Peterson's avatar
Benjamin Peterson committed
1510
"kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\
Christian Heimes's avatar
Christian Heimes committed
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
\n\
This object is the equivalent of the struct kevent for the C API.\n\
\n\
See the kqueue manpage for more detailed information about the meaning\n\
of the arguments.\n\
\n\
One minor note: while you might hope that udata could store a\n\
reference to a python object, it cannot, because it is impossible to\n\
keep a proper reference count of the object once it's passed into the\n\
kernel. Therefore, I have restricted it to only storing an integer.  I\n\
recommend ignoring it and simply using the 'ident' field to key off\n\
of. You could also set up a dictionary on the python side to store a\n\
udata->object mapping.");

typedef struct {
1526 1527
    PyObject_HEAD
    struct kevent e;
Christian Heimes's avatar
Christian Heimes committed
1528 1529 1530 1531 1532 1533 1534
} kqueue_event_Object;

static PyTypeObject kqueue_event_Type;

#define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type))

typedef struct {
1535 1536
    PyObject_HEAD
    SOCKET kqfd;                /* kqueue control fd */
Christian Heimes's avatar
Christian Heimes committed
1537 1538 1539 1540 1541 1542
} kqueue_queue_Object;

static PyTypeObject kqueue_queue_Type;

#define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type))

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
#if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P)
#   error uintptr_t does not match void *!
#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG)
#   define T_UINTPTRT         T_ULONGLONG
#   define T_INTPTRT          T_LONGLONG
#   define PyLong_AsUintptr_t PyLong_AsUnsignedLongLong
#   define UINTPTRT_FMT_UNIT  "K"
#   define INTPTRT_FMT_UNIT   "L"
#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG)
#   define T_UINTPTRT         T_ULONG
#   define T_INTPTRT          T_LONG
#   define PyLong_AsUintptr_t PyLong_AsUnsignedLong
#   define UINTPTRT_FMT_UNIT  "k"
#   define INTPTRT_FMT_UNIT   "l"
#elif (SIZEOF_UINTPTR_T == SIZEOF_INT)
#   define T_UINTPTRT         T_UINT
#   define T_INTPTRT          T_INT
#   define PyLong_AsUintptr_t PyLong_AsUnsignedLong
#   define UINTPTRT_FMT_UNIT  "I"
#   define INTPTRT_FMT_UNIT   "i"
#else
#   error uintptr_t does not match int, long, or long long!
#endif

Christian Heimes's avatar
Christian Heimes committed
1567 1568 1569 1570 1571 1572 1573
/* Unfortunately, we can't store python objects in udata, because
 * kevents in the kernel can be removed without warning, which would
 * forever lose the refcount on the object stored with it.
 */

#define KQ_OFF(x) offsetof(kqueue_event_Object, x)
static struct PyMemberDef kqueue_event_members[] = {
1574 1575 1576 1577 1578 1579 1580
    {"ident",           T_UINTPTRT,     KQ_OFF(e.ident)},
    {"filter",          T_SHORT,        KQ_OFF(e.filter)},
    {"flags",           T_USHORT,       KQ_OFF(e.flags)},
    {"fflags",          T_UINT,         KQ_OFF(e.fflags)},
    {"data",            T_INTPTRT,      KQ_OFF(e.data)},
    {"udata",           T_UINTPTRT,     KQ_OFF(e.udata)},
    {NULL} /* Sentinel */
Christian Heimes's avatar
Christian Heimes committed
1581 1582 1583 1584
};
#undef KQ_OFF

static PyObject *
1585

Christian Heimes's avatar
Christian Heimes committed
1586 1587
kqueue_event_repr(kqueue_event_Object *s)
{
1588 1589 1590 1591 1592 1593 1594 1595
    char buf[1024];
    PyOS_snprintf(
        buf, sizeof(buf),
        "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
        "data=0x%zd udata=%p>",
        (size_t)(s->e.ident), s->e.filter, s->e.flags,
        s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata);
    return PyUnicode_FromString(buf);
Christian Heimes's avatar
Christian Heimes committed
1596 1597 1598 1599 1600
}

static int
kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds)
{
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
    PyObject *pfd;
    static char *kwlist[] = {"ident", "filter", "flags", "fflags",
                             "data", "udata", NULL};
    static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent";

    EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */

    if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
        &pfd, &(self->e.filter), &(self->e.flags),
        &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
        return -1;
    }

    if (PyLong_Check(pfd)) {
        self->e.ident = PyLong_AsUintptr_t(pfd);
    }
    else {
        self->e.ident = PyObject_AsFileDescriptor(pfd);
    }
    if (PyErr_Occurred()) {
        return -1;
    }
    return 0;
Christian Heimes's avatar
Christian Heimes committed
1624 1625 1626 1627
}

static PyObject *
kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o,
1628
                         int op)
Christian Heimes's avatar
Christian Heimes committed
1629
{
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
    Py_intptr_t result = 0;

    if (!kqueue_event_Check(o)) {
        if (op == Py_EQ || op == Py_NE) {
            PyObject *res = op == Py_EQ ? Py_False : Py_True;
            Py_INCREF(res);
            return res;
        }
        PyErr_Format(PyExc_TypeError,
            "can't compare %.200s to %.200s",
            Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name);
        return NULL;
    }
    if (((result = s->e.ident - o->e.ident) == 0) &&
        ((result = s->e.filter - o->e.filter) == 0) &&
        ((result = s->e.flags - o->e.flags) == 0) &&
        ((result = s->e.fflags - o->e.fflags) == 0) &&
        ((result = s->e.data - o->e.data) == 0) &&
        ((result = s->e.udata - o->e.udata) == 0)
       ) {
        result = 0;
    }

    switch (op) {
        case Py_EQ:
        result = (result == 0);
        break;
        case Py_NE:
        result = (result != 0);
        break;
        case Py_LE:
        result = (result <= 0);
        break;
        case Py_GE:
        result = (result >= 0);
        break;
        case Py_LT:
        result = (result < 0);
        break;
        case Py_GT:
        result = (result > 0);
        break;
    }
    return PyBool_FromLong((long)result);
Christian Heimes's avatar
Christian Heimes committed
1674 1675 1676
}

static PyTypeObject kqueue_event_Type = {
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
    PyVarObject_HEAD_INIT(NULL, 0)
    "select.kevent",                                    /* tp_name */
    sizeof(kqueue_event_Object),                        /* tp_basicsize */
    0,                                                  /* tp_itemsize */
    0,                                                  /* tp_dealloc */
    0,                                                  /* tp_print */
    0,                                                  /* tp_getattr */
    0,                                                  /* tp_setattr */
    0,                                                  /* tp_reserved */
    (reprfunc)kqueue_event_repr,                        /* tp_repr */
    0,                                                  /* tp_as_number */
    0,                                                  /* tp_as_sequence */
    0,                                                  /* tp_as_mapping */
    0,                                                  /* tp_hash */
    0,                                                  /* tp_call */
    0,                                                  /* tp_str */
    0,                                                  /* tp_getattro */
    0,                                                  /* tp_setattro */
    0,                                                  /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                                 /* tp_flags */
    kqueue_event_doc,                                   /* tp_doc */
    0,                                                  /* tp_traverse */
    0,                                                  /* tp_clear */
    (richcmpfunc)kqueue_event_richcompare,              /* tp_richcompare */
    0,                                                  /* tp_weaklistoffset */
    0,                                                  /* tp_iter */
    0,                                                  /* tp_iternext */
    0,                                                  /* tp_methods */
    kqueue_event_members,                               /* tp_members */
    0,                                                  /* tp_getset */
    0,                                                  /* tp_base */
    0,                                                  /* tp_dict */
    0,                                                  /* tp_descr_get */
    0,                                                  /* tp_descr_set */
    0,                                                  /* tp_dictoffset */
    (initproc)kqueue_event_init,                        /* tp_init */
    0,                                                  /* tp_alloc */
    0,                                                  /* tp_new */
    0,                                                  /* tp_free */
Christian Heimes's avatar
Christian Heimes committed
1716 1717 1718 1719 1720
};

static PyObject *
kqueue_queue_err_closed(void)
{
1721 1722
    PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd");
    return NULL;
Christian Heimes's avatar
Christian Heimes committed
1723 1724 1725 1726 1727
}

static int
kqueue_queue_internal_close(kqueue_queue_Object *self)
{
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
    int save_errno = 0;
    if (self->kqfd >= 0) {
        int kqfd = self->kqfd;
        self->kqfd = -1;
        Py_BEGIN_ALLOW_THREADS
        if (close(kqfd) < 0)
            save_errno = errno;
        Py_END_ALLOW_THREADS
    }
    return save_errno;
Christian Heimes's avatar
Christian Heimes committed
1738 1739 1740 1741 1742
}

static PyObject *
newKqueue_Object(PyTypeObject *type, SOCKET fd)
{
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
    kqueue_queue_Object *self;
    assert(type != NULL && type->tp_alloc != NULL);
    self = (kqueue_queue_Object *) type->tp_alloc(type, 0);
    if (self == NULL) {
        return NULL;
    }

    if (fd == -1) {
        Py_BEGIN_ALLOW_THREADS
        self->kqfd = kqueue();
        Py_END_ALLOW_THREADS
    }
    else {
        self->kqfd = fd;
    }
    if (self->kqfd < 0) {
        Py_DECREF(self);
1760
        PyErr_SetFromErrno(PyExc_OSError);
1761 1762 1763
        return NULL;
    }
    return (PyObject *)self;
Christian Heimes's avatar
Christian Heimes committed
1764 1765 1766 1767 1768 1769
}

static PyObject *
kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{

1770 1771 1772 1773 1774 1775
    if ((args != NULL && PyObject_Size(args)) ||
                    (kwds != NULL && PyObject_Size(kwds))) {
        PyErr_SetString(PyExc_ValueError,
                        "select.kqueue doesn't accept arguments");
        return NULL;
    }
Christian Heimes's avatar
Christian Heimes committed
1776

1777
    return newKqueue_Object(type, -1);
Christian Heimes's avatar
Christian Heimes committed
1778 1779 1780 1781 1782
}

static void
kqueue_queue_dealloc(kqueue_queue_Object *self)
{
1783 1784
    kqueue_queue_internal_close(self);
    Py_TYPE(self)->tp_free(self);
Christian Heimes's avatar
Christian Heimes committed
1785 1786 1787 1788 1789
}

static PyObject*
kqueue_queue_close(kqueue_queue_Object *self)
{
1790 1791
    errno = kqueue_queue_internal_close(self);
    if (errno < 0) {
1792
        PyErr_SetFromErrno(PyExc_OSError);
1793 1794 1795
        return NULL;
    }
    Py_RETURN_NONE;
Christian Heimes's avatar
Christian Heimes committed
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
}

PyDoc_STRVAR(kqueue_queue_close_doc,
"close() -> None\n\
\n\
Close the kqueue control file descriptor. Further operations on the kqueue\n\
object will raise an exception.");

static PyObject*
kqueue_queue_get_closed(kqueue_queue_Object *self)
{
1807 1808 1809 1810
    if (self->kqfd < 0)
        Py_RETURN_TRUE;
    else
        Py_RETURN_FALSE;
Christian Heimes's avatar
Christian Heimes committed
1811 1812 1813 1814 1815
}

static PyObject*
kqueue_queue_fileno(kqueue_queue_Object *self)
{
1816 1817 1818
    if (self->kqfd < 0)
        return kqueue_queue_err_closed();
    return PyLong_FromLong(self->kqfd);
Christian Heimes's avatar
Christian Heimes committed
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
}

PyDoc_STRVAR(kqueue_queue_fileno_doc,
"fileno() -> int\n\
\n\
Return the kqueue control file descriptor.");

static PyObject*
kqueue_queue_fromfd(PyObject *cls, PyObject *args)
{
1829
    SOCKET fd;
Christian Heimes's avatar
Christian Heimes committed
1830

1831 1832
    if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
        return NULL;
Christian Heimes's avatar
Christian Heimes committed
1833

1834
    return newKqueue_Object((PyTypeObject*)cls, fd);
Christian Heimes's avatar
Christian Heimes committed
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
}

PyDoc_STRVAR(kqueue_queue_fromfd_doc,
"fromfd(fd) -> kqueue\n\
\n\
Create a kqueue object from a given control fd.");

static PyObject *
kqueue_queue_control(kqueue_queue_Object *self, PyObject *args)
{
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
    int nevents = 0;
    int gotevents = 0;
    int nchanges = 0;
    int i = 0;
    PyObject *otimeout = NULL;
    PyObject *ch = NULL;
    PyObject *it = NULL, *ei = NULL;
    PyObject *result = NULL;
    struct kevent *evl = NULL;
    struct kevent *chl = NULL;
1855
    struct timespec timeout;
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
    struct timespec *ptimeoutspec;

    if (self->kqfd < 0)
        return kqueue_queue_err_closed();

    if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout))
        return NULL;

    if (nevents < 0) {
        PyErr_Format(PyExc_ValueError,
            "Length of eventlist must be 0 or positive, got %d",
            nevents);
        return NULL;
    }

    if (otimeout == Py_None || otimeout == NULL) {
        ptimeoutspec = NULL;
    }
    else if (PyNumber_Check(otimeout)) {
1875 1876
        if (_PyTime_ObjectToTimespec(otimeout,
                                     &timeout.tv_sec, &timeout.tv_nsec) == -1)
1877
            return NULL;
1878 1879

        if (timeout.tv_sec < 0) {
1880 1881 1882 1883
            PyErr_SetString(PyExc_ValueError,
                            "timeout must be positive or None");
            return NULL;
        }
1884
        ptimeoutspec = &timeout;
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
    }
    else {
        PyErr_Format(PyExc_TypeError,
            "timeout argument must be an number "
            "or None, got %.200s",
            Py_TYPE(otimeout)->tp_name);
        return NULL;
    }

    if (ch != NULL && ch != Py_None) {
        it = PyObject_GetIter(ch);
        if (it == NULL) {
            PyErr_SetString(PyExc_TypeError,
                            "changelist is not iterable");
            return NULL;
        }
        nchanges = PyObject_Size(ch);
        if (nchanges < 0) {
            goto error;
        }

        chl = PyMem_New(struct kevent, nchanges);
        if (chl == NULL) {
            PyErr_NoMemory();
            goto error;
        }
        i = 0;
        while ((ei = PyIter_Next(it)) != NULL) {
            if (!kqueue_event_Check(ei)) {
                Py_DECREF(ei);
                PyErr_SetString(PyExc_TypeError,
                    "changelist must be an iterable of "
                    "select.kevent objects");
                goto error;
            } else {
                chl[i++] = ((kqueue_event_Object *)ei)->e;
            }
            Py_DECREF(ei);
        }
    }
    Py_CLEAR(it);

    /* event list */
    if (nevents) {
        evl = PyMem_New(struct kevent, nevents);
        if (evl == NULL) {
            PyErr_NoMemory();
            goto error;
        }
    }

    Py_BEGIN_ALLOW_THREADS
    gotevents = kevent(self->kqfd, chl, nchanges,
                       evl, nevents, ptimeoutspec);
    Py_END_ALLOW_THREADS

    if (gotevents == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    result = PyList_New(gotevents);
    if (result == NULL) {
        goto error;
    }

    for (i = 0; i < gotevents; i++) {
        kqueue_event_Object *ch;

        ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type);
        if (ch == NULL) {
            goto error;
        }
        ch->e = evl[i];
        PyList_SET_ITEM(result, i, (PyObject *)ch);
    }
    PyMem_Free(chl);
    PyMem_Free(evl);
    return result;
Christian Heimes's avatar
Christian Heimes committed
1964 1965

    error:
1966 1967 1968 1969 1970
    PyMem_Free(chl);
    PyMem_Free(evl);
    Py_XDECREF(result);
    Py_XDECREF(it);
    return NULL;
Christian Heimes's avatar
Christian Heimes committed
1971 1972 1973
}

PyDoc_STRVAR(kqueue_queue_control_doc,
Benjamin Peterson's avatar
Benjamin Peterson committed
1974
"control(changelist, max_events[, timeout=None]) -> eventlist\n\
Christian Heimes's avatar
Christian Heimes committed
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
\n\
Calls the kernel kevent function.\n\
- changelist must be a list of kevent objects describing the changes\n\
  to be made to the kernel's watch list or None.\n\
- max_events lets you specify the maximum number of events that the\n\
  kernel will return.\n\
- timeout is the maximum time to wait in seconds, or else None,\n\
  to wait forever. timeout accepts floats for smaller timeouts, too.");


static PyMethodDef kqueue_queue_methods[] = {
1986 1987 1988 1989 1990 1991 1992 1993 1994
    {"fromfd",          (PyCFunction)kqueue_queue_fromfd,
     METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc},
    {"close",           (PyCFunction)kqueue_queue_close,        METH_NOARGS,
     kqueue_queue_close_doc},
    {"fileno",          (PyCFunction)kqueue_queue_fileno,       METH_NOARGS,
     kqueue_queue_fileno_doc},
    {"control",         (PyCFunction)kqueue_queue_control,
     METH_VARARGS ,     kqueue_queue_control_doc},
    {NULL,      NULL},
Christian Heimes's avatar
Christian Heimes committed
1995 1996 1997
};

static PyGetSetDef kqueue_queue_getsetlist[] = {
1998 1999 2000
    {"closed", (getter)kqueue_queue_get_closed, NULL,
     "True if the kqueue handler is closed"},
    {0},
Christian Heimes's avatar
Christian Heimes committed
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
};

PyDoc_STRVAR(kqueue_queue_doc,
"Kqueue syscall wrapper.\n\
\n\
For example, to start watching a socket for input:\n\
>>> kq = kqueue()\n\
>>> sock = socket()\n\
>>> sock.connect((host, port))\n\
>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\
\n\
To wait one second for it to become writeable:\n\
>>> kq.control(None, 1, 1000)\n\
\n\
To stop listening:\n\
>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)");

static PyTypeObject kqueue_queue_Type = {
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
    PyVarObject_HEAD_INIT(NULL, 0)
    "select.kqueue",                                    /* tp_name */
    sizeof(kqueue_queue_Object),                        /* tp_basicsize */
    0,                                                  /* tp_itemsize */
    (destructor)kqueue_queue_dealloc,                   /* tp_dealloc */
    0,                                                  /* tp_print */
    0,                                                  /* tp_getattr */
    0,                                                  /* tp_setattr */
    0,                                                  /* tp_reserved */
    0,                                                  /* tp_repr */
    0,                                                  /* tp_as_number */
    0,                                                  /* tp_as_sequence */
    0,                                                  /* tp_as_mapping */
    0,                                                  /* tp_hash */
    0,                                                  /* tp_call */
    0,                                                  /* tp_str */
    0,                                                  /* tp_getattro */
    0,                                                  /* tp_setattro */
    0,                                                  /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                                 /* tp_flags */
    kqueue_queue_doc,                                   /* tp_doc */
    0,                                                  /* tp_traverse */
    0,                                                  /* tp_clear */
    0,                                                  /* tp_richcompare */
    0,                                                  /* tp_weaklistoffset */
    0,                                                  /* tp_iter */
    0,                                                  /* tp_iternext */
    kqueue_queue_methods,                               /* tp_methods */
    0,                                                  /* tp_members */
    kqueue_queue_getsetlist,                            /* tp_getset */
    0,                                                  /* tp_base */
    0,                                                  /* tp_dict */
    0,                                                  /* tp_descr_get */
    0,                                                  /* tp_descr_set */
    0,                                                  /* tp_dictoffset */
    0,                                                  /* tp_init */
    0,                                                  /* tp_alloc */
    kqueue_queue_new,                                   /* tp_new */
    0,                                                  /* tp_free */
Christian Heimes's avatar
Christian Heimes committed
2058 2059 2060
};

#endif /* HAVE_KQUEUE */
2061 2062 2063 2064 2065





Christian Heimes's avatar
Christian Heimes committed
2066 2067
/* ************************************************************************ */

2068
PyDoc_STRVAR(select_doc,
Guido van Rossum's avatar
Guido van Rossum committed
2069 2070 2071
"select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\
\n\
Wait until one or more file descriptors are ready for some kind of I/O.\n\
2072
The first three arguments are sequences of file descriptors to be waited for:\n\
Guido van Rossum's avatar
Guido van Rossum committed
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
rlist -- wait until ready for reading\n\
wlist -- wait until ready for writing\n\
xlist -- wait for an ``exceptional condition''\n\
If only one kind of condition is required, pass [] for the other lists.\n\
A file descriptor is either a socket or file object, or a small integer\n\
gotten from a fileno() method call on one of those.\n\
\n\
The optional 4th argument specifies a timeout in seconds; it may be\n\
a floating point number to specify fractions of seconds.  If it is absent\n\
or None, the call will never time out.\n\
\n\
The return value is a tuple of three lists corresponding to the first three\n\
arguments; each contains the subset of the corresponding file descriptors\n\
that are ready.\n\
\n\
*** IMPORTANT NOTICE ***\n\
Christian Heimes's avatar
Christian Heimes committed
2089
On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\
Christian Heimes's avatar
Christian Heimes committed
2090
descriptors can be used.");
Guido van Rossum's avatar
Guido van Rossum committed
2091

2092
static PyMethodDef select_methods[] = {
2093
    {"select",          select_select,  METH_VARARGS,   select_doc},
Christian Heimes's avatar
Christian Heimes committed
2094
#ifdef HAVE_POLL
2095
    {"poll",            select_poll,    METH_NOARGS,    poll_doc},
2096
#endif /* HAVE_POLL */
2097 2098 2099
#ifdef HAVE_SYS_DEVPOLL_H
    {"devpoll",         select_devpoll, METH_NOARGS,    devpoll_doc},
#endif
2100
    {0,         0},     /* sentinel */
2101 2102
};

2103
PyDoc_STRVAR(module_doc,
Guido van Rossum's avatar
Guido van Rossum committed
2104 2105 2106
"This module supports asynchronous I/O on multiple file descriptors.\n\
\n\
*** IMPORTANT NOTICE ***\n\
2107
On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors.");
2108

2109 2110

static struct PyModuleDef selectmodule = {
2111 2112 2113 2114 2115 2116 2117 2118 2119
    PyModuleDef_HEAD_INIT,
    "select",
    module_doc,
    -1,
    select_methods,
    NULL,
    NULL,
    NULL,
    NULL
2120 2121
};

2122 2123 2124



2125
PyMODINIT_FUNC
2126
PyInit_select(void)
2127
{
2128 2129 2130 2131
    PyObject *m;
    m = PyModule_Create(&selectmodule);
    if (m == NULL)
        return NULL;
2132

2133 2134
    Py_INCREF(PyExc_OSError);
    PyModule_AddObject(m, "error", PyExc_OSError);
2135

2136
#ifdef PIPE_BUF
2137 2138 2139 2140
#ifdef HAVE_BROKEN_PIPE_BUF
#undef PIPE_BUF
#define PIPE_BUF 512
#endif
2141
    PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF);
2142
#endif
2143

Christian Heimes's avatar
Christian Heimes committed
2144
#if defined(HAVE_POLL)
2145
#ifdef __APPLE__
2146 2147 2148 2149 2150
    if (select_have_broken_poll()) {
        if (PyObject_DelAttrString(m, "poll") == -1) {
            PyErr_Clear();
        }
    } else {
2151
#else
2152
    {
2153
#endif
2154 2155 2156 2157 2158 2159 2160 2161
        if (PyType_Ready(&poll_Type) < 0)
            return NULL;
        PyModule_AddIntConstant(m, "POLLIN", POLLIN);
        PyModule_AddIntConstant(m, "POLLPRI", POLLPRI);
        PyModule_AddIntConstant(m, "POLLOUT", POLLOUT);
        PyModule_AddIntConstant(m, "POLLERR", POLLERR);
        PyModule_AddIntConstant(m, "POLLHUP", POLLHUP);
        PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL);
2162

2163
#ifdef POLLRDNORM
2164
        PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM);
2165 2166
#endif
#ifdef POLLRDBAND
2167
        PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND);
2168 2169
#endif
#ifdef POLLWRNORM
2170
        PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM);
2171 2172
#endif
#ifdef POLLWRBAND
2173
        PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND);
2174
#endif
2175
#ifdef POLLMSG
2176
        PyModule_AddIntConstant(m, "POLLMSG", POLLMSG);
2177
#endif
2178
    }
2179
#endif /* HAVE_POLL */
Christian Heimes's avatar
Christian Heimes committed
2180

2181 2182 2183 2184 2185
#ifdef HAVE_SYS_DEVPOLL_H
    if (PyType_Ready(&devpoll_Type) < 0)
        return NULL;
#endif

Christian Heimes's avatar
Christian Heimes committed
2186
#ifdef HAVE_EPOLL
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
    Py_TYPE(&pyEpoll_Type) = &PyType_Type;
    if (PyType_Ready(&pyEpoll_Type) < 0)
        return NULL;

    Py_INCREF(&pyEpoll_Type);
    PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type);

    PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN);
    PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT);
    PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI);
    PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR);
    PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP);
    PyModule_AddIntConstant(m, "EPOLLET", EPOLLET);
Christian Heimes's avatar
Christian Heimes committed
2200
#ifdef EPOLLONESHOT
2201 2202
    /* Kernel 2.6.2+ */
    PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT);
Christian Heimes's avatar
Christian Heimes committed
2203
#endif
2204 2205 2206 2207 2208 2209
    /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */
    PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM);
    PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND);
    PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM);
    PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND);
    PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG);
2210

2211
#ifdef EPOLL_CLOEXEC
2212
    PyModule_AddIntConstant(m, "EPOLL_CLOEXEC", EPOLL_CLOEXEC);
2213
#endif
Christian Heimes's avatar
Christian Heimes committed
2214 2215 2216
#endif /* HAVE_EPOLL */

#ifdef HAVE_KQUEUE
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
    kqueue_event_Type.tp_new = PyType_GenericNew;
    Py_TYPE(&kqueue_event_Type) = &PyType_Type;
    if(PyType_Ready(&kqueue_event_Type) < 0)
        return NULL;

    Py_INCREF(&kqueue_event_Type);
    PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type);

    Py_TYPE(&kqueue_queue_Type) = &PyType_Type;
    if(PyType_Ready(&kqueue_queue_Type) < 0)
        return NULL;
    Py_INCREF(&kqueue_queue_Type);
    PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type);

    /* event filters */
    PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);
    PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);
    PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
    PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
    PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
Christian Heimes's avatar
Christian Heimes committed
2237
#ifdef EVFILT_NETDEV
2238
    PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
Christian Heimes's avatar
Christian Heimes committed
2239
#endif
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
    PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);

    /* event flags */
    PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);
    PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);
    PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);
    PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);
    PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);
    PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);

    PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
    PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);

    PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
    PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);

    /* READ WRITE filter flag */
    PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);

    /* VNODE filter flags  */
    PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);
    PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);
    PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);
    PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);
    PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);
    PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);
    PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);

    /* PROC filter flags  */
    PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);
    PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);
    PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);
    PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);
    PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);

    PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);
    PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);
    PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);

    /* NETDEV filter flags */
Christian Heimes's avatar
Christian Heimes committed
2281
#ifdef EVFILT_NETDEV
2282 2283 2284
    PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);
    PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);
    PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);
Christian Heimes's avatar
Christian Heimes committed
2285 2286 2287
#endif

#endif /* HAVE_KQUEUE */
2288
    return m;
2289
}