1 /* select - Module containing unix select(2) call.
2    Under Unix, the file descriptors are small integers.
3    Under Win32, select only exists for sockets, and sockets may
4    have any value except INVALID_SOCKET.
5 */
6 
7 #if defined(HAVE_POLL_H) && !defined(_GNU_SOURCE)
8 #define _GNU_SOURCE
9 #endif
10 
11 #include "Python.h"
12 #include <structmember.h>
13 
14 #ifdef HAVE_SYS_DEVPOLL_H
15 #include <sys/resource.h>
16 #include <sys/devpoll.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #endif
21 
22 #ifdef __APPLE__
23     /* Perform runtime testing for a broken poll on OSX to make it easier
24      * to use the same binary on multiple releases of the OS.
25      */
26 #undef HAVE_BROKEN_POLL
27 #endif
28 
29 /* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined.
30    64 is too small (too many people have bumped into that limit).
31    Here we boost it.
32    Users who want even more than the boosted limit should #define
33    FD_SETSIZE higher before this; e.g., via compiler /D switch.
34 */
35 #if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
36 #define FD_SETSIZE 512
37 #endif
38 
39 #if defined(HAVE_POLL_H)
40 #include <poll.h>
41 #elif defined(HAVE_SYS_POLL_H)
42 #include <sys/poll.h>
43 #endif
44 
45 #ifdef __sgi
46 /* This is missing from unistd.h */
47 extern void bzero(void *, int);
48 #endif
49 
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
52 #endif
53 
54 #ifdef MS_WINDOWS
55 #  define WIN32_LEAN_AND_MEAN
56 #  include <winsock.h>
57 #else
58 #  define SOCKET int
59 #endif
60 
61 /* list of Python objects and their file descriptor */
62 typedef struct {
63     PyObject *obj;                           /* owned reference */
64     SOCKET fd;
65     int sentinel;                            /* -1 == sentinel */
66 } pylist;
67 
68 static void
reap_obj(pylist fd2obj[FD_SETSIZE+1])69 reap_obj(pylist fd2obj[FD_SETSIZE + 1])
70 {
71     unsigned int i;
72     for (i = 0; i < (unsigned int)FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
73         Py_CLEAR(fd2obj[i].obj);
74     }
75     fd2obj[0].sentinel = -1;
76 }
77 
78 
79 /* returns -1 and sets the Python exception if an error occurred, otherwise
80    returns a number >= 0
81 */
82 static int
seq2set(PyObject * seq,fd_set * set,pylist fd2obj[FD_SETSIZE+1])83 seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
84 {
85     int max = -1;
86     unsigned int index = 0;
87     Py_ssize_t i;
88     PyObject* fast_seq = NULL;
89     PyObject* o = NULL;
90 
91     fd2obj[0].obj = (PyObject*)0;            /* set list to zero size */
92     FD_ZERO(set);
93 
94     fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
95     if (!fast_seq)
96         return -1;
97 
98     for (i = 0; i < PySequence_Fast_GET_SIZE(fast_seq); i++)  {
99         SOCKET v;
100 
101         /* any intervening fileno() calls could decr this refcnt */
102         if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
103             goto finally;
104 
105         Py_INCREF(o);
106         v = PyObject_AsFileDescriptor( o );
107         if (v == -1) goto finally;
108 
109 #if defined(_MSC_VER)
110         max = 0;                             /* not used for Win32 */
111 #else  /* !_MSC_VER */
112         if (!_PyIsSelectable_fd(v)) {
113             PyErr_SetString(PyExc_ValueError,
114                         "filedescriptor out of range in select()");
115             goto finally;
116         }
117         if (v > max)
118             max = v;
119 #endif /* _MSC_VER */
120         FD_SET(v, set);
121 
122         /* add object and its file descriptor to the list */
123         if (index >= (unsigned int)FD_SETSIZE) {
124             PyErr_SetString(PyExc_ValueError,
125                           "too many file descriptors in select()");
126             goto finally;
127         }
128         fd2obj[index].obj = o;
129         fd2obj[index].fd = v;
130         fd2obj[index].sentinel = 0;
131         fd2obj[++index].sentinel = -1;
132     }
133     Py_DECREF(fast_seq);
134     return max+1;
135 
136   finally:
137     Py_XDECREF(o);
138     Py_DECREF(fast_seq);
139     return -1;
140 }
141 
142 /* returns NULL and sets the Python exception if an error occurred */
143 static PyObject *
set2list(fd_set * set,pylist fd2obj[FD_SETSIZE+1])144 set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
145 {
146     int i, j, count=0;
147     PyObject *list, *o;
148     SOCKET fd;
149 
150     for (j = 0; fd2obj[j].sentinel >= 0; j++) {
151         if (FD_ISSET(fd2obj[j].fd, set))
152             count++;
153     }
154     list = PyList_New(count);
155     if (!list)
156         return NULL;
157 
158     i = 0;
159     for (j = 0; fd2obj[j].sentinel >= 0; j++) {
160         fd = fd2obj[j].fd;
161         if (FD_ISSET(fd, set)) {
162             o = fd2obj[j].obj;
163             fd2obj[j].obj = NULL;
164             /* transfer ownership */
165             if (PyList_SetItem(list, i, o) < 0)
166                 goto finally;
167 
168             i++;
169         }
170     }
171     return list;
172   finally:
173     Py_DECREF(list);
174     return NULL;
175 }
176 
177 #undef SELECT_USES_HEAP
178 #if FD_SETSIZE > 1024
179 #define SELECT_USES_HEAP
180 #endif /* FD_SETSIZE > 1024 */
181 
182 static PyObject *
select_select(PyObject * self,PyObject * args)183 select_select(PyObject *self, PyObject *args)
184 {
185 #ifdef SELECT_USES_HEAP
186     pylist *rfd2obj, *wfd2obj, *efd2obj;
187 #else  /* !SELECT_USES_HEAP */
188     /* XXX: All this should probably be implemented as follows:
189      * - find the highest descriptor we're interested in
190      * - add one
191      * - that's the size
192      * See: Stevens, APitUE, $12.5.1
193      */
194     pylist rfd2obj[FD_SETSIZE + 1];
195     pylist wfd2obj[FD_SETSIZE + 1];
196     pylist efd2obj[FD_SETSIZE + 1];
197 #endif /* SELECT_USES_HEAP */
198     PyObject *ifdlist, *ofdlist, *efdlist;
199     PyObject *ret = NULL;
200     PyObject *timeout_obj = Py_None;
201     fd_set ifdset, ofdset, efdset;
202     struct timeval tv, *tvp;
203     int imax, omax, emax, max;
204     int n;
205     _PyTime_t timeout, deadline = 0;
206 
207     /* convert arguments */
208     if (!PyArg_UnpackTuple(args, "select", 3, 4,
209                           &ifdlist, &ofdlist, &efdlist, &timeout_obj))
210         return NULL;
211 
212     if (timeout_obj == Py_None)
213         tvp = (struct timeval *)NULL;
214     else {
215         if (_PyTime_FromSecondsObject(&timeout, timeout_obj,
216                                       _PyTime_ROUND_TIMEOUT) < 0) {
217             if (PyErr_ExceptionMatches(PyExc_TypeError)) {
218                 PyErr_SetString(PyExc_TypeError,
219                                 "timeout must be a float or None");
220             }
221             return NULL;
222         }
223 
224         if (_PyTime_AsTimeval(timeout, &tv, _PyTime_ROUND_TIMEOUT) == -1)
225             return NULL;
226         if (tv.tv_sec < 0) {
227             PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
228             return NULL;
229         }
230         tvp = &tv;
231     }
232 
233 #ifdef SELECT_USES_HEAP
234     /* Allocate memory for the lists */
235     rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
236     wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
237     efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
238     if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
239         if (rfd2obj) PyMem_DEL(rfd2obj);
240         if (wfd2obj) PyMem_DEL(wfd2obj);
241         if (efd2obj) PyMem_DEL(efd2obj);
242         return PyErr_NoMemory();
243     }
244 #endif /* SELECT_USES_HEAP */
245 
246     /* Convert sequences to fd_sets, and get maximum fd number
247      * propagates the Python exception set in seq2set()
248      */
249     rfd2obj[0].sentinel = -1;
250     wfd2obj[0].sentinel = -1;
251     efd2obj[0].sentinel = -1;
252     if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
253         goto finally;
254     if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
255         goto finally;
256     if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
257         goto finally;
258 
259     max = imax;
260     if (omax > max) max = omax;
261     if (emax > max) max = emax;
262 
263     if (tvp)
264         deadline = _PyTime_GetMonotonicClock() + timeout;
265 
266     do {
267         Py_BEGIN_ALLOW_THREADS
268         errno = 0;
269         n = select(max, &ifdset, &ofdset, &efdset, tvp);
270         Py_END_ALLOW_THREADS
271 
272         if (errno != EINTR)
273             break;
274 
275         /* select() was interrupted by a signal */
276         if (PyErr_CheckSignals())
277             goto finally;
278 
279         if (tvp) {
280             timeout = deadline - _PyTime_GetMonotonicClock();
281             if (timeout < 0) {
282                 /* bpo-35310: lists were unmodified -- clear them explicitly */
283                 FD_ZERO(&ifdset);
284                 FD_ZERO(&ofdset);
285                 FD_ZERO(&efdset);
286                 n = 0;
287                 break;
288             }
289             _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
290             /* retry select() with the recomputed timeout */
291         }
292     } while (1);
293 
294 #ifdef MS_WINDOWS
295     if (n == SOCKET_ERROR) {
296         PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
297     }
298 #else
299     if (n < 0) {
300         PyErr_SetFromErrno(PyExc_OSError);
301     }
302 #endif
303     else {
304         /* any of these three calls can raise an exception.  it's more
305            convenient to test for this after all three calls... but
306            is that acceptable?
307         */
308         ifdlist = set2list(&ifdset, rfd2obj);
309         ofdlist = set2list(&ofdset, wfd2obj);
310         efdlist = set2list(&efdset, efd2obj);
311         if (PyErr_Occurred())
312             ret = NULL;
313         else
314             ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);
315 
316         Py_XDECREF(ifdlist);
317         Py_XDECREF(ofdlist);
318         Py_XDECREF(efdlist);
319     }
320 
321   finally:
322     reap_obj(rfd2obj);
323     reap_obj(wfd2obj);
324     reap_obj(efd2obj);
325 #ifdef SELECT_USES_HEAP
326     PyMem_DEL(rfd2obj);
327     PyMem_DEL(wfd2obj);
328     PyMem_DEL(efd2obj);
329 #endif /* SELECT_USES_HEAP */
330     return ret;
331 }
332 
333 #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
334 /*
335  * poll() support
336  */
337 
338 typedef struct {
339     PyObject_HEAD
340     PyObject *dict;
341     int ufd_uptodate;
342     int ufd_len;
343     struct pollfd *ufds;
344     int poll_running;
345 } pollObject;
346 
347 static PyTypeObject poll_Type;
348 
349 /* Update the malloc'ed array of pollfds to match the dictionary
350    contained within a pollObject.  Return 1 on success, 0 on an error.
351 */
352 
353 static int
update_ufd_array(pollObject * self)354 update_ufd_array(pollObject *self)
355 {
356     Py_ssize_t i, pos;
357     PyObject *key, *value;
358     struct pollfd *old_ufds = self->ufds;
359 
360     self->ufd_len = PyDict_GET_SIZE(self->dict);
361     PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
362     if (self->ufds == NULL) {
363         self->ufds = old_ufds;
364         PyErr_NoMemory();
365         return 0;
366     }
367 
368     i = pos = 0;
369     while (PyDict_Next(self->dict, &pos, &key, &value)) {
370         assert(i < self->ufd_len);
371         /* Never overflow */
372         self->ufds[i].fd = (int)PyLong_AsLong(key);
373         self->ufds[i].events = (short)(unsigned short)PyLong_AsLong(value);
374         i++;
375     }
376     assert(i == self->ufd_len);
377     self->ufd_uptodate = 1;
378     return 1;
379 }
380 
381 static int
ushort_converter(PyObject * obj,void * ptr)382 ushort_converter(PyObject *obj, void *ptr)
383 {
384     unsigned long uval;
385 
386     uval = PyLong_AsUnsignedLong(obj);
387     if (uval == (unsigned long)-1 && PyErr_Occurred())
388         return 0;
389     if (uval > USHRT_MAX) {
390         PyErr_SetString(PyExc_OverflowError,
391                         "Python int too large for C unsigned short");
392         return 0;
393     }
394 
395     *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
396     return 1;
397 }
398 
399 PyDoc_STRVAR(poll_register_doc,
400 "register(fd [, eventmask] ) -> None\n\n\
401 Register a file descriptor with the polling object.\n\
402 fd -- either an integer, or an object with a fileno() method returning an\n\
403       int.\n\
404 events -- an optional bitmask describing the type of events to check for");
405 
406 static PyObject *
poll_register(pollObject * self,PyObject * args)407 poll_register(pollObject *self, PyObject *args)
408 {
409     PyObject *o, *key, *value;
410     int fd;
411     unsigned short events = POLLIN | POLLPRI | POLLOUT;
412     int err;
413 
414     if (!PyArg_ParseTuple(args, "O|O&:register", &o, ushort_converter, &events))
415         return NULL;
416 
417     fd = PyObject_AsFileDescriptor(o);
418     if (fd == -1) return NULL;
419 
420     /* Add entry to the internal dictionary: the key is the
421        file descriptor, and the value is the event mask. */
422     key = PyLong_FromLong(fd);
423     if (key == NULL)
424         return NULL;
425     value = PyLong_FromLong(events);
426     if (value == NULL) {
427         Py_DECREF(key);
428         return NULL;
429     }
430     err = PyDict_SetItem(self->dict, key, value);
431     Py_DECREF(key);
432     Py_DECREF(value);
433     if (err < 0)
434         return NULL;
435 
436     self->ufd_uptodate = 0;
437 
438     Py_RETURN_NONE;
439 }
440 
441 PyDoc_STRVAR(poll_modify_doc,
442 "modify(fd, eventmask) -> None\n\n\
443 Modify an already registered file descriptor.\n\
444 fd -- either an integer, or an object with a fileno() method returning an\n\
445       int.\n\
446 events -- an optional bitmask describing the type of events to check for");
447 
448 static PyObject *
poll_modify(pollObject * self,PyObject * args)449 poll_modify(pollObject *self, PyObject *args)
450 {
451     PyObject *o, *key, *value;
452     int fd;
453     unsigned short events;
454     int err;
455 
456     if (!PyArg_ParseTuple(args, "OO&:modify", &o, ushort_converter, &events))
457         return NULL;
458 
459     fd = PyObject_AsFileDescriptor(o);
460     if (fd == -1) return NULL;
461 
462     /* Modify registered fd */
463     key = PyLong_FromLong(fd);
464     if (key == NULL)
465         return NULL;
466     if (PyDict_GetItem(self->dict, key) == NULL) {
467         errno = ENOENT;
468         PyErr_SetFromErrno(PyExc_OSError);
469         Py_DECREF(key);
470         return NULL;
471     }
472     value = PyLong_FromLong(events);
473     if (value == NULL) {
474         Py_DECREF(key);
475         return NULL;
476     }
477     err = PyDict_SetItem(self->dict, key, value);
478     Py_DECREF(key);
479     Py_DECREF(value);
480     if (err < 0)
481         return NULL;
482 
483     self->ufd_uptodate = 0;
484 
485     Py_RETURN_NONE;
486 }
487 
488 
489 PyDoc_STRVAR(poll_unregister_doc,
490 "unregister(fd) -> None\n\n\
491 Remove a file descriptor being tracked by the polling object.");
492 
493 static PyObject *
poll_unregister(pollObject * self,PyObject * o)494 poll_unregister(pollObject *self, PyObject *o)
495 {
496     PyObject *key;
497     int fd;
498 
499     fd = PyObject_AsFileDescriptor( o );
500     if (fd == -1)
501         return NULL;
502 
503     /* Check whether the fd is already in the array */
504     key = PyLong_FromLong(fd);
505     if (key == NULL)
506         return NULL;
507 
508     if (PyDict_DelItem(self->dict, key) == -1) {
509         Py_DECREF(key);
510         /* This will simply raise the KeyError set by PyDict_DelItem
511            if the file descriptor isn't registered. */
512         return NULL;
513     }
514 
515     Py_DECREF(key);
516     self->ufd_uptodate = 0;
517 
518     Py_RETURN_NONE;
519 }
520 
521 PyDoc_STRVAR(poll_poll_doc,
522 "poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
523 Polls the set of registered file descriptors, returning a list containing \n\
524 any descriptors that have events or errors to report.");
525 
526 static PyObject *
poll_poll(pollObject * self,PyObject * args)527 poll_poll(pollObject *self, PyObject *args)
528 {
529     PyObject *result_list = NULL, *timeout_obj = NULL;
530     int poll_result, i, j;
531     PyObject *value = NULL, *num = NULL;
532     _PyTime_t timeout = -1, ms = -1, deadline = 0;
533     int async_err = 0;
534 
535     if (!PyArg_ParseTuple(args, "|O:poll", &timeout_obj)) {
536         return NULL;
537     }
538 
539     if (timeout_obj != NULL && timeout_obj != Py_None) {
540         if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
541                                            _PyTime_ROUND_TIMEOUT) < 0) {
542             if (PyErr_ExceptionMatches(PyExc_TypeError)) {
543                 PyErr_SetString(PyExc_TypeError,
544                                 "timeout must be an integer or None");
545             }
546             return NULL;
547         }
548 
549         ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_TIMEOUT);
550         if (ms < INT_MIN || ms > INT_MAX) {
551             PyErr_SetString(PyExc_OverflowError, "timeout is too large");
552             return NULL;
553         }
554 
555         if (timeout >= 0) {
556             deadline = _PyTime_GetMonotonicClock() + timeout;
557         }
558     }
559 
560     /* On some OSes, typically BSD-based ones, the timeout parameter of the
561        poll() syscall, when negative, must be exactly INFTIM, where defined,
562        or -1. See issue 31334. */
563     if (ms < 0) {
564 #ifdef INFTIM
565         ms = INFTIM;
566 #else
567         ms = -1;
568 #endif
569     }
570 
571     /* Avoid concurrent poll() invocation, issue 8865 */
572     if (self->poll_running) {
573         PyErr_SetString(PyExc_RuntimeError,
574                         "concurrent poll() invocation");
575         return NULL;
576     }
577 
578     /* Ensure the ufd array is up to date */
579     if (!self->ufd_uptodate)
580         if (update_ufd_array(self) == 0)
581             return NULL;
582 
583     self->poll_running = 1;
584 
585     /* call poll() */
586     async_err = 0;
587     do {
588         Py_BEGIN_ALLOW_THREADS
589         errno = 0;
590         poll_result = poll(self->ufds, self->ufd_len, (int)ms);
591         Py_END_ALLOW_THREADS
592 
593         if (errno != EINTR)
594             break;
595 
596         /* poll() was interrupted by a signal */
597         if (PyErr_CheckSignals()) {
598             async_err = 1;
599             break;
600         }
601 
602         if (timeout >= 0) {
603             timeout = deadline - _PyTime_GetMonotonicClock();
604             if (timeout < 0) {
605                 poll_result = 0;
606                 break;
607             }
608             ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
609             /* retry poll() with the recomputed timeout */
610         }
611     } while (1);
612 
613     self->poll_running = 0;
614 
615     if (poll_result < 0) {
616         if (!async_err)
617             PyErr_SetFromErrno(PyExc_OSError);
618         return NULL;
619     }
620 
621     /* build the result list */
622 
623     result_list = PyList_New(poll_result);
624     if (!result_list)
625         return NULL;
626 
627     for (i = 0, j = 0; j < poll_result; j++) {
628         /* skip to the next fired descriptor */
629         while (!self->ufds[i].revents) {
630             i++;
631         }
632         /* if we hit a NULL return, set value to NULL
633            and break out of loop; code at end will
634            clean up result_list */
635         value = PyTuple_New(2);
636         if (value == NULL)
637             goto error;
638         num = PyLong_FromLong(self->ufds[i].fd);
639         if (num == NULL) {
640             Py_DECREF(value);
641             goto error;
642         }
643         PyTuple_SET_ITEM(value, 0, num);
644 
645         /* The &0xffff is a workaround for AIX.  'revents'
646            is a 16-bit short, and IBM assigned POLLNVAL
647            to be 0x8000, so the conversion to int results
648            in a negative number. See SF bug #923315. */
649         num = PyLong_FromLong(self->ufds[i].revents & 0xffff);
650         if (num == NULL) {
651             Py_DECREF(value);
652             goto error;
653         }
654         PyTuple_SET_ITEM(value, 1, num);
655         PyList_SET_ITEM(result_list, j, value);
656         i++;
657     }
658     return result_list;
659 
660   error:
661     Py_DECREF(result_list);
662     return NULL;
663 }
664 
665 static PyMethodDef poll_methods[] = {
666     {"register",        (PyCFunction)poll_register,
667      METH_VARARGS,  poll_register_doc},
668     {"modify",          (PyCFunction)poll_modify,
669      METH_VARARGS,  poll_modify_doc},
670     {"unregister",      (PyCFunction)poll_unregister,
671      METH_O,        poll_unregister_doc},
672     {"poll",            (PyCFunction)poll_poll,
673      METH_VARARGS,  poll_poll_doc},
674     {NULL,              NULL}           /* sentinel */
675 };
676 
677 static pollObject *
newPollObject(void)678 newPollObject(void)
679 {
680     pollObject *self;
681     self = PyObject_New(pollObject, &poll_Type);
682     if (self == NULL)
683         return NULL;
684     /* ufd_uptodate is a Boolean, denoting whether the
685        array pointed to by ufds matches the contents of the dictionary. */
686     self->ufd_uptodate = 0;
687     self->ufds = NULL;
688     self->poll_running = 0;
689     self->dict = PyDict_New();
690     if (self->dict == NULL) {
691         Py_DECREF(self);
692         return NULL;
693     }
694     return self;
695 }
696 
697 static void
poll_dealloc(pollObject * self)698 poll_dealloc(pollObject *self)
699 {
700     if (self->ufds != NULL)
701         PyMem_DEL(self->ufds);
702     Py_XDECREF(self->dict);
703     PyObject_Del(self);
704 }
705 
706 static PyTypeObject poll_Type = {
707     /* The ob_type field must be initialized in the module init function
708      * to be portable to Windows without using C++. */
709     PyVarObject_HEAD_INIT(NULL, 0)
710     "select.poll",              /*tp_name*/
711     sizeof(pollObject),         /*tp_basicsize*/
712     0,                          /*tp_itemsize*/
713     /* methods */
714     (destructor)poll_dealloc, /*tp_dealloc*/
715     0,                          /*tp_print*/
716     0,                          /*tp_getattr*/
717     0,                      /*tp_setattr*/
718     0,                          /*tp_reserved*/
719     0,                          /*tp_repr*/
720     0,                          /*tp_as_number*/
721     0,                          /*tp_as_sequence*/
722     0,                          /*tp_as_mapping*/
723     0,                          /*tp_hash*/
724     0,                          /*tp_call*/
725     0,                          /*tp_str*/
726     0,                          /*tp_getattro*/
727     0,                          /*tp_setattro*/
728     0,                          /*tp_as_buffer*/
729     Py_TPFLAGS_DEFAULT,         /*tp_flags*/
730     0,                          /*tp_doc*/
731     0,                          /*tp_traverse*/
732     0,                          /*tp_clear*/
733     0,                          /*tp_richcompare*/
734     0,                          /*tp_weaklistoffset*/
735     0,                          /*tp_iter*/
736     0,                          /*tp_iternext*/
737     poll_methods,               /*tp_methods*/
738 };
739 
740 #ifdef HAVE_SYS_DEVPOLL_H
741 typedef struct {
742     PyObject_HEAD
743     int fd_devpoll;
744     int max_n_fds;
745     int n_fds;
746     struct pollfd *fds;
747 } devpollObject;
748 
749 static PyTypeObject devpoll_Type;
750 
751 static PyObject *
devpoll_err_closed(void)752 devpoll_err_closed(void)
753 {
754     PyErr_SetString(PyExc_ValueError, "I/O operation on closed devpoll object");
755     return NULL;
756 }
757 
devpoll_flush(devpollObject * self)758 static int devpoll_flush(devpollObject *self)
759 {
760     int size, n;
761 
762     if (!self->n_fds) return 0;
763 
764     size = sizeof(struct pollfd)*self->n_fds;
765     self->n_fds = 0;
766 
767     n = _Py_write(self->fd_devpoll, self->fds, size);
768     if (n == -1)
769         return -1;
770 
771     if (n < size) {
772         /*
773         ** Data writed to /dev/poll is a binary data structure. It is not
774         ** clear what to do if a partial write occurred. For now, raise
775         ** an exception and see if we actually found this problem in
776         ** the wild.
777         ** See http://bugs.python.org/issue6397.
778         */
779         PyErr_Format(PyExc_OSError, "failed to write all pollfds. "
780                 "Please, report at http://bugs.python.org/. "
781                 "Data to report: Size tried: %d, actual size written: %d.",
782                 size, n);
783         return -1;
784     }
785     return 0;
786 }
787 
788 static PyObject *
internal_devpoll_register(devpollObject * self,PyObject * args,int remove)789 internal_devpoll_register(devpollObject *self, PyObject *args, int remove)
790 {
791     PyObject *o;
792     int fd;
793     unsigned short events = POLLIN | POLLPRI | POLLOUT;
794 
795     if (self->fd_devpoll < 0)
796         return devpoll_err_closed();
797 
798     if (!PyArg_ParseTuple(args, "O|O&:register", &o, ushort_converter, &events))
799         return NULL;
800 
801     fd = PyObject_AsFileDescriptor(o);
802     if (fd == -1) return NULL;
803 
804     if (remove) {
805         self->fds[self->n_fds].fd = fd;
806         self->fds[self->n_fds].events = POLLREMOVE;
807 
808         if (++self->n_fds == self->max_n_fds) {
809             if (devpoll_flush(self))
810                 return NULL;
811         }
812     }
813 
814     self->fds[self->n_fds].fd = fd;
815     self->fds[self->n_fds].events = (signed short)events;
816 
817     if (++self->n_fds == self->max_n_fds) {
818         if (devpoll_flush(self))
819             return NULL;
820     }
821 
822     Py_RETURN_NONE;
823 }
824 
825 PyDoc_STRVAR(devpoll_register_doc,
826 "register(fd [, eventmask] ) -> None\n\n\
827 Register a file descriptor with the polling object.\n\
828 fd -- either an integer, or an object with a fileno() method returning an\n\
829       int.\n\
830 events -- an optional bitmask describing the type of events to check for");
831 
832 static PyObject *
devpoll_register(devpollObject * self,PyObject * args)833 devpoll_register(devpollObject *self, PyObject *args)
834 {
835     return internal_devpoll_register(self, args, 0);
836 }
837 
838 PyDoc_STRVAR(devpoll_modify_doc,
839 "modify(fd[, eventmask]) -> None\n\n\
840 Modify a possible already registered file descriptor.\n\
841 fd -- either an integer, or an object with a fileno() method returning an\n\
842       int.\n\
843 events -- an optional bitmask describing the type of events to check for");
844 
845 static PyObject *
devpoll_modify(devpollObject * self,PyObject * args)846 devpoll_modify(devpollObject *self, PyObject *args)
847 {
848     return internal_devpoll_register(self, args, 1);
849 }
850 
851 
852 PyDoc_STRVAR(devpoll_unregister_doc,
853 "unregister(fd) -> None\n\n\
854 Remove a file descriptor being tracked by the polling object.");
855 
856 static PyObject *
devpoll_unregister(devpollObject * self,PyObject * o)857 devpoll_unregister(devpollObject *self, PyObject *o)
858 {
859     int fd;
860 
861     if (self->fd_devpoll < 0)
862         return devpoll_err_closed();
863 
864     fd = PyObject_AsFileDescriptor( o );
865     if (fd == -1)
866         return NULL;
867 
868     self->fds[self->n_fds].fd = fd;
869     self->fds[self->n_fds].events = POLLREMOVE;
870 
871     if (++self->n_fds == self->max_n_fds) {
872         if (devpoll_flush(self))
873             return NULL;
874     }
875 
876     Py_RETURN_NONE;
877 }
878 
879 PyDoc_STRVAR(devpoll_poll_doc,
880 "poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
881 Polls the set of registered file descriptors, returning a list containing \n\
882 any descriptors that have events or errors to report.");
883 
884 static PyObject *
devpoll_poll(devpollObject * self,PyObject * args)885 devpoll_poll(devpollObject *self, PyObject *args)
886 {
887     struct dvpoll dvp;
888     PyObject *result_list = NULL, *timeout_obj = NULL;
889     int poll_result, i;
890     PyObject *value, *num1, *num2;
891     _PyTime_t timeout, ms, deadline = 0;
892 
893     if (self->fd_devpoll < 0)
894         return devpoll_err_closed();
895 
896     if (!PyArg_ParseTuple(args, "|O:poll", &timeout_obj)) {
897         return NULL;
898     }
899 
900     /* Check values for timeout */
901     if (timeout_obj == NULL || timeout_obj == Py_None) {
902         timeout = -1;
903         ms = -1;
904     }
905     else {
906         if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
907                                            _PyTime_ROUND_TIMEOUT) < 0) {
908             if (PyErr_ExceptionMatches(PyExc_TypeError)) {
909                 PyErr_SetString(PyExc_TypeError,
910                                 "timeout must be an integer or None");
911             }
912             return NULL;
913         }
914 
915         ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_TIMEOUT);
916         if (ms < -1 || ms > INT_MAX) {
917             PyErr_SetString(PyExc_OverflowError, "timeout is too large");
918             return NULL;
919         }
920     }
921 
922     if (devpoll_flush(self))
923         return NULL;
924 
925     dvp.dp_fds = self->fds;
926     dvp.dp_nfds = self->max_n_fds;
927     dvp.dp_timeout = (int)ms;
928 
929     if (timeout >= 0)
930         deadline = _PyTime_GetMonotonicClock() + timeout;
931 
932     do {
933         /* call devpoll() */
934         Py_BEGIN_ALLOW_THREADS
935         errno = 0;
936         poll_result = ioctl(self->fd_devpoll, DP_POLL, &dvp);
937         Py_END_ALLOW_THREADS
938 
939         if (errno != EINTR)
940             break;
941 
942         /* devpoll() was interrupted by a signal */
943         if (PyErr_CheckSignals())
944             return NULL;
945 
946         if (timeout >= 0) {
947             timeout = deadline - _PyTime_GetMonotonicClock();
948             if (timeout < 0) {
949                 poll_result = 0;
950                 break;
951             }
952             ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
953             dvp.dp_timeout = (int)ms;
954             /* retry devpoll() with the recomputed timeout */
955         }
956     } while (1);
957 
958     if (poll_result < 0) {
959         PyErr_SetFromErrno(PyExc_OSError);
960         return NULL;
961     }
962 
963     /* build the result list */
964     result_list = PyList_New(poll_result);
965     if (!result_list)
966         return NULL;
967 
968     for (i = 0; i < poll_result; i++) {
969         num1 = PyLong_FromLong(self->fds[i].fd);
970         num2 = PyLong_FromLong(self->fds[i].revents);
971         if ((num1 == NULL) || (num2 == NULL)) {
972             Py_XDECREF(num1);
973             Py_XDECREF(num2);
974             goto error;
975         }
976         value = PyTuple_Pack(2, num1, num2);
977         Py_DECREF(num1);
978         Py_DECREF(num2);
979         if (value == NULL)
980             goto error;
981         PyList_SET_ITEM(result_list, i, value);
982     }
983 
984     return result_list;
985 
986   error:
987     Py_DECREF(result_list);
988     return NULL;
989 }
990 
991 static int
devpoll_internal_close(devpollObject * self)992 devpoll_internal_close(devpollObject *self)
993 {
994     int save_errno = 0;
995     if (self->fd_devpoll >= 0) {
996         int fd = self->fd_devpoll;
997         self->fd_devpoll = -1;
998         Py_BEGIN_ALLOW_THREADS
999         if (close(fd) < 0)
1000             save_errno = errno;
1001         Py_END_ALLOW_THREADS
1002     }
1003     return save_errno;
1004 }
1005 
1006 static PyObject*
devpoll_close(devpollObject * self)1007 devpoll_close(devpollObject *self)
1008 {
1009     errno = devpoll_internal_close(self);
1010     if (errno < 0) {
1011         PyErr_SetFromErrno(PyExc_OSError);
1012         return NULL;
1013     }
1014     Py_RETURN_NONE;
1015 }
1016 
1017 PyDoc_STRVAR(devpoll_close_doc,
1018 "close() -> None\n\
1019 \n\
1020 Close the devpoll file descriptor. Further operations on the devpoll\n\
1021 object will raise an exception.");
1022 
1023 static PyObject*
devpoll_get_closed(devpollObject * self,void * Py_UNUSED (ignored))1024 devpoll_get_closed(devpollObject *self, void *Py_UNUSED(ignored))
1025 {
1026     if (self->fd_devpoll < 0)
1027         Py_RETURN_TRUE;
1028     else
1029         Py_RETURN_FALSE;
1030 }
1031 
1032 static PyObject*
devpoll_fileno(devpollObject * self)1033 devpoll_fileno(devpollObject *self)
1034 {
1035     if (self->fd_devpoll < 0)
1036         return devpoll_err_closed();
1037     return PyLong_FromLong(self->fd_devpoll);
1038 }
1039 
1040 PyDoc_STRVAR(devpoll_fileno_doc,
1041 "fileno() -> int\n\
1042 \n\
1043 Return the file descriptor.");
1044 
1045 static PyMethodDef devpoll_methods[] = {
1046     {"register",        (PyCFunction)devpoll_register,
1047      METH_VARARGS,  devpoll_register_doc},
1048     {"modify",          (PyCFunction)devpoll_modify,
1049      METH_VARARGS,  devpoll_modify_doc},
1050     {"unregister",      (PyCFunction)devpoll_unregister,
1051      METH_O,        devpoll_unregister_doc},
1052     {"poll",            (PyCFunction)devpoll_poll,
1053      METH_VARARGS,  devpoll_poll_doc},
1054     {"close",           (PyCFunction)devpoll_close,    METH_NOARGS,
1055      devpoll_close_doc},
1056     {"fileno",          (PyCFunction)devpoll_fileno,    METH_NOARGS,
1057      devpoll_fileno_doc},
1058     {NULL,              NULL}           /* sentinel */
1059 };
1060 
1061 static PyGetSetDef devpoll_getsetlist[] = {
1062     {"closed", (getter)devpoll_get_closed, NULL,
1063      "True if the devpoll object is closed"},
1064     {0},
1065 };
1066 
1067 static devpollObject *
newDevPollObject(void)1068 newDevPollObject(void)
1069 {
1070     devpollObject *self;
1071     int fd_devpoll, limit_result;
1072     struct pollfd *fds;
1073     struct rlimit limit;
1074 
1075     /*
1076     ** If we try to process more that getrlimit()
1077     ** fds, the kernel will give an error, so
1078     ** we set the limit here. It is a dynamic
1079     ** value, because we can change rlimit() anytime.
1080     */
1081     limit_result = getrlimit(RLIMIT_NOFILE, &limit);
1082     if (limit_result == -1) {
1083         PyErr_SetFromErrno(PyExc_OSError);
1084         return NULL;
1085     }
1086 
1087     fd_devpoll = _Py_open("/dev/poll", O_RDWR);
1088     if (fd_devpoll == -1)
1089         return NULL;
1090 
1091     fds = PyMem_NEW(struct pollfd, limit.rlim_cur);
1092     if (fds == NULL) {
1093         close(fd_devpoll);
1094         PyErr_NoMemory();
1095         return NULL;
1096     }
1097 
1098     self = PyObject_New(devpollObject, &devpoll_Type);
1099     if (self == NULL) {
1100         close(fd_devpoll);
1101         PyMem_DEL(fds);
1102         return NULL;
1103     }
1104     self->fd_devpoll = fd_devpoll;
1105     self->max_n_fds = limit.rlim_cur;
1106     self->n_fds = 0;
1107     self->fds = fds;
1108 
1109     return self;
1110 }
1111 
1112 static void
devpoll_dealloc(devpollObject * self)1113 devpoll_dealloc(devpollObject *self)
1114 {
1115     (void)devpoll_internal_close(self);
1116     PyMem_DEL(self->fds);
1117     PyObject_Del(self);
1118 }
1119 
1120 static PyTypeObject devpoll_Type = {
1121     /* The ob_type field must be initialized in the module init function
1122      * to be portable to Windows without using C++. */
1123     PyVarObject_HEAD_INIT(NULL, 0)
1124     "select.devpoll",           /*tp_name*/
1125     sizeof(devpollObject),      /*tp_basicsize*/
1126     0,                          /*tp_itemsize*/
1127     /* methods */
1128     (destructor)devpoll_dealloc, /*tp_dealloc*/
1129     0,                          /*tp_print*/
1130     0,                          /*tp_getattr*/
1131     0,                          /*tp_setattr*/
1132     0,                          /*tp_reserved*/
1133     0,                          /*tp_repr*/
1134     0,                          /*tp_as_number*/
1135     0,                          /*tp_as_sequence*/
1136     0,                          /*tp_as_mapping*/
1137     0,                          /*tp_hash*/
1138     0,                          /*tp_call*/
1139     0,                          /*tp_str*/
1140     0,                          /*tp_getattro*/
1141     0,                          /*tp_setattro*/
1142     0,                          /*tp_as_buffer*/
1143     Py_TPFLAGS_DEFAULT,         /*tp_flags*/
1144     0,                          /*tp_doc*/
1145     0,                          /*tp_traverse*/
1146     0,                          /*tp_clear*/
1147     0,                          /*tp_richcompare*/
1148     0,                          /*tp_weaklistoffset*/
1149     0,                          /*tp_iter*/
1150     0,                          /*tp_iternext*/
1151     devpoll_methods,            /*tp_methods*/
1152     0,                          /* tp_members */
1153     devpoll_getsetlist,         /* tp_getset */
1154 };
1155 #endif  /* HAVE_SYS_DEVPOLL_H */
1156 
1157 
1158 
1159 PyDoc_STRVAR(poll_doc,
1160 "Returns a polling object, which supports registering and\n\
1161 unregistering file descriptors, and then polling them for I/O events.");
1162 
1163 static PyObject *
select_poll(PyObject * self,PyObject * unused)1164 select_poll(PyObject *self, PyObject *unused)
1165 {
1166     return (PyObject *)newPollObject();
1167 }
1168 
1169 #ifdef HAVE_SYS_DEVPOLL_H
1170 PyDoc_STRVAR(devpoll_doc,
1171 "Returns a polling object, which supports registering and\n\
1172 unregistering file descriptors, and then polling them for I/O events.");
1173 
1174 static PyObject *
select_devpoll(PyObject * self,PyObject * unused)1175 select_devpoll(PyObject *self, PyObject *unused)
1176 {
1177     return (PyObject *)newDevPollObject();
1178 }
1179 #endif
1180 
1181 
1182 #ifdef __APPLE__
1183 /*
1184  * On some systems poll() sets errno on invalid file descriptors. We test
1185  * for this at runtime because this bug may be fixed or introduced between
1186  * OS releases.
1187  */
select_have_broken_poll(void)1188 static int select_have_broken_poll(void)
1189 {
1190     int poll_test;
1191     int filedes[2];
1192 
1193     struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };
1194 
1195     /* Create a file descriptor to make invalid */
1196     if (pipe(filedes) < 0) {
1197         return 1;
1198     }
1199     poll_struct.fd = filedes[0];
1200     close(filedes[0]);
1201     close(filedes[1]);
1202     poll_test = poll(&poll_struct, 1, 0);
1203     if (poll_test < 0) {
1204         return 1;
1205     } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
1206         return 1;
1207     }
1208     return 0;
1209 }
1210 #endif /* __APPLE__ */
1211 
1212 #endif /* HAVE_POLL */
1213 
1214 #ifdef HAVE_EPOLL
1215 /* **************************************************************************
1216  *                      epoll interface for Linux 2.6
1217  *
1218  * Written by Christian Heimes
1219  * Inspired by Twisted's _epoll.pyx and select.poll()
1220  */
1221 
1222 #ifdef HAVE_SYS_EPOLL_H
1223 #include <sys/epoll.h>
1224 #endif
1225 
1226 typedef struct {
1227     PyObject_HEAD
1228     SOCKET epfd;                        /* epoll control file descriptor */
1229 } pyEpoll_Object;
1230 
1231 static PyTypeObject pyEpoll_Type;
1232 #define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type))
1233 
1234 static PyObject *
pyepoll_err_closed(void)1235 pyepoll_err_closed(void)
1236 {
1237     PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll object");
1238     return NULL;
1239 }
1240 
1241 static int
pyepoll_internal_close(pyEpoll_Object * self)1242 pyepoll_internal_close(pyEpoll_Object *self)
1243 {
1244     int save_errno = 0;
1245     if (self->epfd >= 0) {
1246         int epfd = self->epfd;
1247         self->epfd = -1;
1248         Py_BEGIN_ALLOW_THREADS
1249         if (close(epfd) < 0)
1250             save_errno = errno;
1251         Py_END_ALLOW_THREADS
1252     }
1253     return save_errno;
1254 }
1255 
1256 static PyObject *
newPyEpoll_Object(PyTypeObject * type,int sizehint,SOCKET fd)1257 newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd)
1258 {
1259     pyEpoll_Object *self;
1260 
1261     assert(type != NULL && type->tp_alloc != NULL);
1262     self = (pyEpoll_Object *) type->tp_alloc(type, 0);
1263     if (self == NULL)
1264         return NULL;
1265 
1266     if (fd == -1) {
1267         Py_BEGIN_ALLOW_THREADS
1268 #ifdef HAVE_EPOLL_CREATE1
1269         self->epfd = epoll_create1(EPOLL_CLOEXEC);
1270 #else
1271         self->epfd = epoll_create(sizehint);
1272 #endif
1273         Py_END_ALLOW_THREADS
1274     }
1275     else {
1276         self->epfd = fd;
1277     }
1278     if (self->epfd < 0) {
1279         Py_DECREF(self);
1280         PyErr_SetFromErrno(PyExc_OSError);
1281         return NULL;
1282     }
1283 
1284 #ifndef HAVE_EPOLL_CREATE1
1285     if (fd == -1 && _Py_set_inheritable(self->epfd, 0, NULL) < 0) {
1286         Py_DECREF(self);
1287         return NULL;
1288     }
1289 #endif
1290 
1291     return (PyObject *)self;
1292 }
1293 
1294 
1295 static PyObject *
pyepoll_new(PyTypeObject * type,PyObject * args,PyObject * kwds)1296 pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1297 {
1298     int flags = 0, sizehint = -1;
1299     static char *kwlist[] = {"sizehint", "flags", NULL};
1300 
1301     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:epoll", kwlist,
1302                                      &sizehint, &flags))
1303         return NULL;
1304     if (sizehint == -1) {
1305         sizehint = FD_SETSIZE - 1;
1306     }
1307     else if (sizehint <= 0) {
1308         PyErr_SetString(PyExc_ValueError, "sizehint must be positive or -1");
1309         return NULL;
1310     }
1311 
1312 #ifdef HAVE_EPOLL_CREATE1
1313     if (flags && flags != EPOLL_CLOEXEC) {
1314         PyErr_SetString(PyExc_OSError, "invalid flags");
1315         return NULL;
1316     }
1317 #endif
1318     return newPyEpoll_Object(type, sizehint, -1);
1319 }
1320 
1321 
1322 static void
pyepoll_dealloc(pyEpoll_Object * self)1323 pyepoll_dealloc(pyEpoll_Object *self)
1324 {
1325     (void)pyepoll_internal_close(self);
1326     Py_TYPE(self)->tp_free(self);
1327 }
1328 
1329 static PyObject*
pyepoll_close(pyEpoll_Object * self)1330 pyepoll_close(pyEpoll_Object *self)
1331 {
1332     errno = pyepoll_internal_close(self);
1333     if (errno < 0) {
1334         PyErr_SetFromErrno(PyExc_OSError);
1335         return NULL;
1336     }
1337     Py_RETURN_NONE;
1338 }
1339 
1340 PyDoc_STRVAR(pyepoll_close_doc,
1341 "close() -> None\n\
1342 \n\
1343 Close the epoll control file descriptor. Further operations on the epoll\n\
1344 object will raise an exception.");
1345 
1346 static PyObject*
pyepoll_get_closed(pyEpoll_Object * self,void * Py_UNUSED (ignored))1347 pyepoll_get_closed(pyEpoll_Object *self, void *Py_UNUSED(ignored))
1348 {
1349     if (self->epfd < 0)
1350         Py_RETURN_TRUE;
1351     else
1352         Py_RETURN_FALSE;
1353 }
1354 
1355 static PyObject*
pyepoll_fileno(pyEpoll_Object * self)1356 pyepoll_fileno(pyEpoll_Object *self)
1357 {
1358     if (self->epfd < 0)
1359         return pyepoll_err_closed();
1360     return PyLong_FromLong(self->epfd);
1361 }
1362 
1363 PyDoc_STRVAR(pyepoll_fileno_doc,
1364 "fileno() -> int\n\
1365 \n\
1366 Return the epoll control file descriptor.");
1367 
1368 static PyObject*
pyepoll_fromfd(PyObject * cls,PyObject * args)1369 pyepoll_fromfd(PyObject *cls, PyObject *args)
1370 {
1371     SOCKET fd;
1372 
1373     if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
1374         return NULL;
1375 
1376     return newPyEpoll_Object((PyTypeObject*)cls, FD_SETSIZE - 1, fd);
1377 }
1378 
1379 PyDoc_STRVAR(pyepoll_fromfd_doc,
1380 "fromfd(fd) -> epoll\n\
1381 \n\
1382 Create an epoll object from a given control fd.");
1383 
1384 static PyObject *
pyepoll_internal_ctl(int epfd,int op,PyObject * pfd,unsigned int events)1385 pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events)
1386 {
1387     struct epoll_event ev;
1388     int result;
1389     int fd;
1390 
1391     if (epfd < 0)
1392         return pyepoll_err_closed();
1393 
1394     fd = PyObject_AsFileDescriptor(pfd);
1395     if (fd == -1) {
1396         return NULL;
1397     }
1398 
1399     switch (op) {
1400     case EPOLL_CTL_ADD:
1401     case EPOLL_CTL_MOD:
1402         ev.events = events;
1403         ev.data.fd = fd;
1404         Py_BEGIN_ALLOW_THREADS
1405         result = epoll_ctl(epfd, op, fd, &ev);
1406         Py_END_ALLOW_THREADS
1407         break;
1408     case EPOLL_CTL_DEL:
1409         /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
1410          * operation required a non-NULL pointer in event, even
1411          * though this argument is ignored. */
1412         Py_BEGIN_ALLOW_THREADS
1413         result = epoll_ctl(epfd, op, fd, &ev);
1414         if (errno == EBADF) {
1415             /* fd already closed */
1416             result = 0;
1417             errno = 0;
1418         }
1419         Py_END_ALLOW_THREADS
1420         break;
1421     default:
1422         result = -1;
1423         errno = EINVAL;
1424     }
1425 
1426     if (result < 0) {
1427         PyErr_SetFromErrno(PyExc_OSError);
1428         return NULL;
1429     }
1430     Py_RETURN_NONE;
1431 }
1432 
1433 static PyObject *
pyepoll_register(pyEpoll_Object * self,PyObject * args,PyObject * kwds)1434 pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
1435 {
1436     PyObject *pfd;
1437     unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;
1438     static char *kwlist[] = {"fd", "eventmask", NULL};
1439 
1440     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
1441                                      &pfd, &events)) {
1442         return NULL;
1443     }
1444 
1445     return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
1446 }
1447 
1448 PyDoc_STRVAR(pyepoll_register_doc,
1449 "register(fd[, eventmask]) -> None\n\
1450 \n\
1451 Registers a new fd or raises an OSError if the fd is already registered.\n\
1452 fd is the target file descriptor of the operation.\n\
1453 events is a bit set composed of the various EPOLL constants; the default\n\
1454 is EPOLLIN | EPOLLOUT | EPOLLPRI.\n\
1455 \n\
1456 The epoll interface supports all file descriptors that support poll.");
1457 
1458 static PyObject *
pyepoll_modify(pyEpoll_Object * self,PyObject * args,PyObject * kwds)1459 pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
1460 {
1461     PyObject *pfd;
1462     unsigned int events;
1463     static char *kwlist[] = {"fd", "eventmask", NULL};
1464 
1465     if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
1466                                      &pfd, &events)) {
1467         return NULL;
1468     }
1469 
1470     return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
1471 }
1472 
1473 PyDoc_STRVAR(pyepoll_modify_doc,
1474 "modify(fd, eventmask) -> None\n\
1475 \n\
1476 fd is the target file descriptor of the operation\n\
1477 events is a bit set composed of the various EPOLL constants");
1478 
1479 static PyObject *
pyepoll_unregister(pyEpoll_Object * self,PyObject * args,PyObject * kwds)1480 pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
1481 {
1482     PyObject *pfd;
1483     static char *kwlist[] = {"fd", NULL};
1484 
1485     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
1486                                      &pfd)) {
1487         return NULL;
1488     }
1489 
1490     return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
1491 }
1492 
1493 PyDoc_STRVAR(pyepoll_unregister_doc,
1494 "unregister(fd) -> None\n\
1495 \n\
1496 fd is the target file descriptor of the operation.");
1497 
1498 static PyObject *
pyepoll_poll(pyEpoll_Object * self,PyObject * args,PyObject * kwds)1499 pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
1500 {
1501     static char *kwlist[] = {"timeout", "maxevents", NULL};
1502     PyObject *timeout_obj = NULL;
1503     int maxevents = -1;
1504     int nfds, i;
1505     PyObject *elist = NULL, *etuple = NULL;
1506     struct epoll_event *evs = NULL;
1507     _PyTime_t timeout, ms, deadline;
1508 
1509     if (self->epfd < 0)
1510         return pyepoll_err_closed();
1511 
1512     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:poll", kwlist,
1513                                      &timeout_obj, &maxevents)) {
1514         return NULL;
1515     }
1516 
1517     if (timeout_obj == NULL || timeout_obj == Py_None) {
1518         timeout = -1;
1519         ms = -1;
1520         deadline = 0;   /* initialize to prevent gcc warning */
1521     }
1522     else {
1523         /* epoll_wait() has a resolution of 1 millisecond, round towards
1524            infinity to wait at least timeout seconds. */
1525         if (_PyTime_FromSecondsObject(&timeout, timeout_obj,
1526                                       _PyTime_ROUND_TIMEOUT) < 0) {
1527             if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1528                 PyErr_SetString(PyExc_TypeError,
1529                                 "timeout must be an integer or None");
1530             }
1531             return NULL;
1532         }
1533 
1534         ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
1535         if (ms < INT_MIN || ms > INT_MAX) {
1536             PyErr_SetString(PyExc_OverflowError, "timeout is too large");
1537             return NULL;
1538         }
1539 
1540         deadline = _PyTime_GetMonotonicClock() + timeout;
1541     }
1542 
1543     if (maxevents == -1) {
1544         maxevents = FD_SETSIZE-1;
1545     }
1546     else if (maxevents < 1) {
1547         PyErr_Format(PyExc_ValueError,
1548                      "maxevents must be greater than 0, got %d",
1549                      maxevents);
1550         return NULL;
1551     }
1552 
1553     evs = PyMem_New(struct epoll_event, maxevents);
1554     if (evs == NULL) {
1555         PyErr_NoMemory();
1556         return NULL;
1557     }
1558 
1559     do {
1560         Py_BEGIN_ALLOW_THREADS
1561         errno = 0;
1562         nfds = epoll_wait(self->epfd, evs, maxevents, (int)ms);
1563         Py_END_ALLOW_THREADS
1564 
1565         if (errno != EINTR)
1566             break;
1567 
1568         /* poll() was interrupted by a signal */
1569         if (PyErr_CheckSignals())
1570             goto error;
1571 
1572         if (timeout >= 0) {
1573             timeout = deadline - _PyTime_GetMonotonicClock();
1574             if (timeout < 0) {
1575                 nfds = 0;
1576                 break;
1577             }
1578             ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
1579             /* retry epoll_wait() with the recomputed timeout */
1580         }
1581     } while(1);
1582 
1583     if (nfds < 0) {
1584         PyErr_SetFromErrno(PyExc_OSError);
1585         goto error;
1586     }
1587 
1588     elist = PyList_New(nfds);
1589     if (elist == NULL) {
1590         goto error;
1591     }
1592 
1593     for (i = 0; i < nfds; i++) {
1594         etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
1595         if (etuple == NULL) {
1596             Py_CLEAR(elist);
1597             goto error;
1598         }
1599         PyList_SET_ITEM(elist, i, etuple);
1600     }
1601 
1602     error:
1603     PyMem_Free(evs);
1604     return elist;
1605 }
1606 
1607 PyDoc_STRVAR(pyepoll_poll_doc,
1608 "poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\
1609 \n\
1610 Wait for events on the epoll file descriptor for a maximum time of timeout\n\
1611 in seconds (as float). -1 makes poll wait indefinitely.\n\
1612 Up to maxevents are returned to the caller.");
1613 
1614 static PyObject *
pyepoll_enter(pyEpoll_Object * self,PyObject * args)1615 pyepoll_enter(pyEpoll_Object *self, PyObject *args)
1616 {
1617     if (self->epfd < 0)
1618         return pyepoll_err_closed();
1619 
1620     Py_INCREF(self);
1621     return (PyObject *)self;
1622 }
1623 
1624 static PyObject *
pyepoll_exit(PyObject * self,PyObject * args)1625 pyepoll_exit(PyObject *self, PyObject *args)
1626 {
1627     _Py_IDENTIFIER(close);
1628 
1629     return _PyObject_CallMethodId(self, &PyId_close, NULL);
1630 }
1631 
1632 static PyMethodDef pyepoll_methods[] = {
1633     {"fromfd",          (PyCFunction)pyepoll_fromfd,
1634      METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},
1635     {"close",           (PyCFunction)pyepoll_close,     METH_NOARGS,
1636      pyepoll_close_doc},
1637     {"fileno",          (PyCFunction)pyepoll_fileno,    METH_NOARGS,
1638      pyepoll_fileno_doc},
1639     {"modify",          (PyCFunction)pyepoll_modify,
1640      METH_VARARGS | METH_KEYWORDS,      pyepoll_modify_doc},
1641     {"register",        (PyCFunction)pyepoll_register,
1642      METH_VARARGS | METH_KEYWORDS,      pyepoll_register_doc},
1643     {"unregister",      (PyCFunction)pyepoll_unregister,
1644      METH_VARARGS | METH_KEYWORDS,      pyepoll_unregister_doc},
1645     {"poll",            (PyCFunction)pyepoll_poll,
1646      METH_VARARGS | METH_KEYWORDS,      pyepoll_poll_doc},
1647     {"__enter__",           (PyCFunction)pyepoll_enter,     METH_NOARGS,
1648      NULL},
1649     {"__exit__",           (PyCFunction)pyepoll_exit,     METH_VARARGS,
1650      NULL},
1651     {NULL,      NULL},
1652 };
1653 
1654 static PyGetSetDef pyepoll_getsetlist[] = {
1655     {"closed", (getter)pyepoll_get_closed, NULL,
1656      "True if the epoll handler is closed"},
1657     {0},
1658 };
1659 
1660 PyDoc_STRVAR(pyepoll_doc,
1661 "select.epoll(sizehint=-1, flags=0)\n\
1662 \n\
1663 Returns an epolling object\n\
1664 \n\
1665 sizehint must be a positive integer or -1 for the default size. The\n\
1666 sizehint is used to optimize internal data structures. It doesn't limit\n\
1667 the maximum number of monitored events.");
1668 
1669 static PyTypeObject pyEpoll_Type = {
1670     PyVarObject_HEAD_INIT(NULL, 0)
1671     "select.epoll",                                     /* tp_name */
1672     sizeof(pyEpoll_Object),                             /* tp_basicsize */
1673     0,                                                  /* tp_itemsize */
1674     (destructor)pyepoll_dealloc,                        /* tp_dealloc */
1675     0,                                                  /* tp_print */
1676     0,                                                  /* tp_getattr */
1677     0,                                                  /* tp_setattr */
1678     0,                                                  /* tp_reserved */
1679     0,                                                  /* tp_repr */
1680     0,                                                  /* tp_as_number */
1681     0,                                                  /* tp_as_sequence */
1682     0,                                                  /* tp_as_mapping */
1683     0,                                                  /* tp_hash */
1684     0,                                                  /* tp_call */
1685     0,                                                  /* tp_str */
1686     PyObject_GenericGetAttr,                            /* tp_getattro */
1687     0,                                                  /* tp_setattro */
1688     0,                                                  /* tp_as_buffer */
1689     Py_TPFLAGS_DEFAULT,                                 /* tp_flags */
1690     pyepoll_doc,                                        /* tp_doc */
1691     0,                                                  /* tp_traverse */
1692     0,                                                  /* tp_clear */
1693     0,                                                  /* tp_richcompare */
1694     0,                                                  /* tp_weaklistoffset */
1695     0,                                                  /* tp_iter */
1696     0,                                                  /* tp_iternext */
1697     pyepoll_methods,                                    /* tp_methods */
1698     0,                                                  /* tp_members */
1699     pyepoll_getsetlist,                                 /* tp_getset */
1700     0,                                                  /* tp_base */
1701     0,                                                  /* tp_dict */
1702     0,                                                  /* tp_descr_get */
1703     0,                                                  /* tp_descr_set */
1704     0,                                                  /* tp_dictoffset */
1705     0,                                                  /* tp_init */
1706     0,                                                  /* tp_alloc */
1707     pyepoll_new,                                        /* tp_new */
1708     0,                                                  /* tp_free */
1709 };
1710 
1711 #endif /* HAVE_EPOLL */
1712 
1713 #ifdef HAVE_KQUEUE
1714 /* **************************************************************************
1715  *                      kqueue interface for BSD
1716  *
1717  * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
1718  * All rights reserved.
1719  *
1720  * Redistribution and use in source and binary forms, with or without
1721  * modification, are permitted provided that the following conditions
1722  * are met:
1723  * 1. Redistributions of source code must retain the above copyright
1724  *    notice, this list of conditions and the following disclaimer.
1725  * 2. Redistributions in binary form must reproduce the above copyright
1726  *    notice, this list of conditions and the following disclaimer in the
1727  *    documentation and/or other materials provided with the distribution.
1728  *
1729  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1730  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1731  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1732  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1733  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1734  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1735  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1736  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1737  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1738  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1739  * SUCH DAMAGE.
1740  */
1741 
1742 #ifdef HAVE_SYS_EVENT_H
1743 #include <sys/event.h>
1744 #endif
1745 
1746 PyDoc_STRVAR(kqueue_event_doc,
1747 "kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\
1748 \n\
1749 This object is the equivalent of the struct kevent for the C API.\n\
1750 \n\
1751 See the kqueue manpage for more detailed information about the meaning\n\
1752 of the arguments.\n\
1753 \n\
1754 One minor note: while you might hope that udata could store a\n\
1755 reference to a python object, it cannot, because it is impossible to\n\
1756 keep a proper reference count of the object once it's passed into the\n\
1757 kernel. Therefore, I have restricted it to only storing an integer.  I\n\
1758 recommend ignoring it and simply using the 'ident' field to key off\n\
1759 of. You could also set up a dictionary on the python side to store a\n\
1760 udata->object mapping.");
1761 
1762 typedef struct {
1763     PyObject_HEAD
1764     struct kevent e;
1765 } kqueue_event_Object;
1766 
1767 static PyTypeObject kqueue_event_Type;
1768 
1769 #define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type))
1770 
1771 typedef struct {
1772     PyObject_HEAD
1773     SOCKET kqfd;                /* kqueue control fd */
1774 } kqueue_queue_Object;
1775 
1776 static PyTypeObject kqueue_queue_Type;
1777 
1778 #define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type))
1779 
1780 #if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P)
1781 #   error uintptr_t does not match void *!
1782 #elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG)
1783 #   define T_UINTPTRT         T_ULONGLONG
1784 #   define T_INTPTRT          T_LONGLONG
1785 #   define UINTPTRT_FMT_UNIT  "K"
1786 #   define INTPTRT_FMT_UNIT   "L"
1787 #elif (SIZEOF_UINTPTR_T == SIZEOF_LONG)
1788 #   define T_UINTPTRT         T_ULONG
1789 #   define T_INTPTRT          T_LONG
1790 #   define UINTPTRT_FMT_UNIT  "k"
1791 #   define INTPTRT_FMT_UNIT   "l"
1792 #elif (SIZEOF_UINTPTR_T == SIZEOF_INT)
1793 #   define T_UINTPTRT         T_UINT
1794 #   define T_INTPTRT          T_INT
1795 #   define UINTPTRT_FMT_UNIT  "I"
1796 #   define INTPTRT_FMT_UNIT   "i"
1797 #else
1798 #   error uintptr_t does not match int, long, or long long!
1799 #endif
1800 
1801 #if SIZEOF_LONG_LONG == 8
1802 #   define T_INT64          T_LONGLONG
1803 #   define INT64_FMT_UNIT   "L"
1804 #elif SIZEOF_LONG == 8
1805 #   define T_INT64          T_LONG
1806 #   define INT64_FMT_UNIT   "l"
1807 #elif SIZEOF_INT == 8
1808 #   define T_INT64          T_INT
1809 #   define INT64_FMT_UNIT   "i"
1810 #else
1811 #   define INT64_FMT_UNIT   "_"
1812 #endif
1813 
1814 #if SIZEOF_LONG_LONG == 4
1815 #   define T_UINT32         T_ULONGLONG
1816 #   define UINT32_FMT_UNIT  "K"
1817 #elif SIZEOF_LONG == 4
1818 #   define T_UINT32         T_ULONG
1819 #   define UINT32_FMT_UNIT  "k"
1820 #elif SIZEOF_INT == 4
1821 #   define T_UINT32         T_UINT
1822 #   define UINT32_FMT_UNIT  "I"
1823 #else
1824 #   define UINT32_FMT_UNIT  "_"
1825 #endif
1826 
1827 /*
1828  * kevent is not standard and its members vary across BSDs.
1829  */
1830 #ifdef __NetBSD__
1831 #   define FILTER_TYPE      T_UINT32
1832 #   define FILTER_FMT_UNIT  UINT32_FMT_UNIT
1833 #   define FLAGS_TYPE       T_UINT32
1834 #   define FLAGS_FMT_UNIT   UINT32_FMT_UNIT
1835 #   define FFLAGS_TYPE      T_UINT32
1836 #   define FFLAGS_FMT_UNIT  UINT32_FMT_UNIT
1837 #else
1838 #   define FILTER_TYPE      T_SHORT
1839 #   define FILTER_FMT_UNIT  "h"
1840 #   define FLAGS_TYPE       T_USHORT
1841 #   define FLAGS_FMT_UNIT   "H"
1842 #   define FFLAGS_TYPE      T_UINT
1843 #   define FFLAGS_FMT_UNIT  "I"
1844 #endif
1845 
1846 #if defined(__NetBSD__) || defined(__OpenBSD__)
1847 #   define DATA_TYPE        T_INT64
1848 #   define DATA_FMT_UNIT    INT64_FMT_UNIT
1849 #else
1850 #   define DATA_TYPE        T_INTPTRT
1851 #   define DATA_FMT_UNIT    INTPTRT_FMT_UNIT
1852 #endif
1853 
1854 /* Unfortunately, we can't store python objects in udata, because
1855  * kevents in the kernel can be removed without warning, which would
1856  * forever lose the refcount on the object stored with it.
1857  */
1858 
1859 #define KQ_OFF(x) offsetof(kqueue_event_Object, x)
1860 static struct PyMemberDef kqueue_event_members[] = {
1861     {"ident",           T_UINTPTRT,     KQ_OFF(e.ident)},
1862     {"filter",          FILTER_TYPE,    KQ_OFF(e.filter)},
1863     {"flags",           FLAGS_TYPE,     KQ_OFF(e.flags)},
1864     {"fflags",          T_UINT,         KQ_OFF(e.fflags)},
1865     {"data",            DATA_TYPE,      KQ_OFF(e.data)},
1866     {"udata",           T_UINTPTRT,     KQ_OFF(e.udata)},
1867     {NULL} /* Sentinel */
1868 };
1869 #undef KQ_OFF
1870 
1871 static PyObject *
1872 
kqueue_event_repr(kqueue_event_Object * s)1873 kqueue_event_repr(kqueue_event_Object *s)
1874 {
1875     char buf[1024];
1876     PyOS_snprintf(
1877         buf, sizeof(buf),
1878         "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
1879         "data=0x%llx udata=%p>",
1880         (size_t)(s->e.ident), (int)s->e.filter, (unsigned int)s->e.flags,
1881         (unsigned int)s->e.fflags, (long long)(s->e.data), (void *)s->e.udata);
1882     return PyUnicode_FromString(buf);
1883 }
1884 
1885 static int
kqueue_event_init(kqueue_event_Object * self,PyObject * args,PyObject * kwds)1886 kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds)
1887 {
1888     PyObject *pfd;
1889     static char *kwlist[] = {"ident", "filter", "flags", "fflags",
1890                              "data", "udata", NULL};
1891     static const char fmt[] = "O|"
1892                 FILTER_FMT_UNIT FLAGS_FMT_UNIT FFLAGS_FMT_UNIT DATA_FMT_UNIT
1893                 UINTPTRT_FMT_UNIT ":kevent";
1894 
1895     EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
1896 
1897     if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1898         &pfd, &(self->e.filter), &(self->e.flags),
1899         &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
1900         return -1;
1901     }
1902 
1903     if (PyLong_Check(pfd)) {
1904         self->e.ident = PyLong_AsSize_t(pfd);
1905     }
1906     else {
1907         self->e.ident = PyObject_AsFileDescriptor(pfd);
1908     }
1909     if (PyErr_Occurred()) {
1910         return -1;
1911     }
1912     return 0;
1913 }
1914 
1915 static PyObject *
kqueue_event_richcompare(kqueue_event_Object * s,kqueue_event_Object * o,int op)1916 kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o,
1917                          int op)
1918 {
1919     int result;
1920 
1921     if (!kqueue_event_Check(o)) {
1922         Py_RETURN_NOTIMPLEMENTED;
1923     }
1924 
1925 #define CMP(a, b) ((a) != (b)) ? ((a) < (b) ? -1 : 1)
1926     result = CMP(s->e.ident, o->e.ident)
1927            : CMP(s->e.filter, o->e.filter)
1928            : CMP(s->e.flags, o->e.flags)
1929            : CMP(s->e.fflags, o->e.fflags)
1930            : CMP(s->e.data, o->e.data)
1931            : CMP((intptr_t)s->e.udata, (intptr_t)o->e.udata)
1932            : 0;
1933 #undef CMP
1934 
1935     Py_RETURN_RICHCOMPARE(result, 0, op);
1936 }
1937 
1938 static PyTypeObject kqueue_event_Type = {
1939     PyVarObject_HEAD_INIT(NULL, 0)
1940     "select.kevent",                                    /* tp_name */
1941     sizeof(kqueue_event_Object),                        /* tp_basicsize */
1942     0,                                                  /* tp_itemsize */
1943     0,                                                  /* tp_dealloc */
1944     0,                                                  /* tp_print */
1945     0,                                                  /* tp_getattr */
1946     0,                                                  /* tp_setattr */
1947     0,                                                  /* tp_reserved */
1948     (reprfunc)kqueue_event_repr,                        /* tp_repr */
1949     0,                                                  /* tp_as_number */
1950     0,                                                  /* tp_as_sequence */
1951     0,                                                  /* tp_as_mapping */
1952     0,                                                  /* tp_hash */
1953     0,                                                  /* tp_call */
1954     0,                                                  /* tp_str */
1955     0,                                                  /* tp_getattro */
1956     0,                                                  /* tp_setattro */
1957     0,                                                  /* tp_as_buffer */
1958     Py_TPFLAGS_DEFAULT,                                 /* tp_flags */
1959     kqueue_event_doc,                                   /* tp_doc */
1960     0,                                                  /* tp_traverse */
1961     0,                                                  /* tp_clear */
1962     (richcmpfunc)kqueue_event_richcompare,              /* tp_richcompare */
1963     0,                                                  /* tp_weaklistoffset */
1964     0,                                                  /* tp_iter */
1965     0,                                                  /* tp_iternext */
1966     0,                                                  /* tp_methods */
1967     kqueue_event_members,                               /* tp_members */
1968     0,                                                  /* tp_getset */
1969     0,                                                  /* tp_base */
1970     0,                                                  /* tp_dict */
1971     0,                                                  /* tp_descr_get */
1972     0,                                                  /* tp_descr_set */
1973     0,                                                  /* tp_dictoffset */
1974     (initproc)kqueue_event_init,                        /* tp_init */
1975     0,                                                  /* tp_alloc */
1976     0,                                                  /* tp_new */
1977     0,                                                  /* tp_free */
1978 };
1979 
1980 static PyObject *
kqueue_queue_err_closed(void)1981 kqueue_queue_err_closed(void)
1982 {
1983     PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue object");
1984     return NULL;
1985 }
1986 
1987 static int
kqueue_queue_internal_close(kqueue_queue_Object * self)1988 kqueue_queue_internal_close(kqueue_queue_Object *self)
1989 {
1990     int save_errno = 0;
1991     if (self->kqfd >= 0) {
1992         int kqfd = self->kqfd;
1993         self->kqfd = -1;
1994         Py_BEGIN_ALLOW_THREADS
1995         if (close(kqfd) < 0)
1996             save_errno = errno;
1997         Py_END_ALLOW_THREADS
1998     }
1999     return save_errno;
2000 }
2001 
2002 static PyObject *
newKqueue_Object(PyTypeObject * type,SOCKET fd)2003 newKqueue_Object(PyTypeObject *type, SOCKET fd)
2004 {
2005     kqueue_queue_Object *self;
2006     assert(type != NULL && type->tp_alloc != NULL);
2007     self = (kqueue_queue_Object *) type->tp_alloc(type, 0);
2008     if (self == NULL) {
2009         return NULL;
2010     }
2011 
2012     if (fd == -1) {
2013         Py_BEGIN_ALLOW_THREADS
2014         self->kqfd = kqueue();
2015         Py_END_ALLOW_THREADS
2016     }
2017     else {
2018         self->kqfd = fd;
2019     }
2020     if (self->kqfd < 0) {
2021         Py_DECREF(self);
2022         PyErr_SetFromErrno(PyExc_OSError);
2023         return NULL;
2024     }
2025 
2026     if (fd == -1) {
2027         if (_Py_set_inheritable(self->kqfd, 0, NULL) < 0) {
2028             Py_DECREF(self);
2029             return NULL;
2030         }
2031     }
2032     return (PyObject *)self;
2033 }
2034 
2035 static PyObject *
kqueue_queue_new(PyTypeObject * type,PyObject * args,PyObject * kwds)2036 kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2037 {
2038     if (PyTuple_GET_SIZE(args) ||
2039                     (kwds != NULL && PyDict_GET_SIZE(kwds))) {
2040         PyErr_SetString(PyExc_ValueError,
2041                         "select.kqueue doesn't accept arguments");
2042         return NULL;
2043     }
2044 
2045     return newKqueue_Object(type, -1);
2046 }
2047 
2048 static void
kqueue_queue_dealloc(kqueue_queue_Object * self)2049 kqueue_queue_dealloc(kqueue_queue_Object *self)
2050 {
2051     kqueue_queue_internal_close(self);
2052     Py_TYPE(self)->tp_free(self);
2053 }
2054 
2055 static PyObject*
kqueue_queue_close(kqueue_queue_Object * self)2056 kqueue_queue_close(kqueue_queue_Object *self)
2057 {
2058     errno = kqueue_queue_internal_close(self);
2059     if (errno < 0) {
2060         PyErr_SetFromErrno(PyExc_OSError);
2061         return NULL;
2062     }
2063     Py_RETURN_NONE;
2064 }
2065 
2066 PyDoc_STRVAR(kqueue_queue_close_doc,
2067 "close() -> None\n\
2068 \n\
2069 Close the kqueue control file descriptor. Further operations on the kqueue\n\
2070 object will raise an exception.");
2071 
2072 static PyObject*
kqueue_queue_get_closed(kqueue_queue_Object * self,void * Py_UNUSED (ignored))2073 kqueue_queue_get_closed(kqueue_queue_Object *self, void *Py_UNUSED(ignored))
2074 {
2075     if (self->kqfd < 0)
2076         Py_RETURN_TRUE;
2077     else
2078         Py_RETURN_FALSE;
2079 }
2080 
2081 static PyObject*
kqueue_queue_fileno(kqueue_queue_Object * self)2082 kqueue_queue_fileno(kqueue_queue_Object *self)
2083 {
2084     if (self->kqfd < 0)
2085         return kqueue_queue_err_closed();
2086     return PyLong_FromLong(self->kqfd);
2087 }
2088 
2089 PyDoc_STRVAR(kqueue_queue_fileno_doc,
2090 "fileno() -> int\n\
2091 \n\
2092 Return the kqueue control file descriptor.");
2093 
2094 static PyObject*
kqueue_queue_fromfd(PyObject * cls,PyObject * args)2095 kqueue_queue_fromfd(PyObject *cls, PyObject *args)
2096 {
2097     SOCKET fd;
2098 
2099     if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
2100         return NULL;
2101 
2102     return newKqueue_Object((PyTypeObject*)cls, fd);
2103 }
2104 
2105 PyDoc_STRVAR(kqueue_queue_fromfd_doc,
2106 "fromfd(fd) -> kqueue\n\
2107 \n\
2108 Create a kqueue object from a given control fd.");
2109 
2110 static PyObject *
kqueue_queue_control(kqueue_queue_Object * self,PyObject * args)2111 kqueue_queue_control(kqueue_queue_Object *self, PyObject *args)
2112 {
2113     int nevents = 0;
2114     int gotevents = 0;
2115     int nchanges = 0;
2116     int i = 0;
2117     PyObject *otimeout = NULL;
2118     PyObject *ch = NULL;
2119     PyObject *seq = NULL, *ei = NULL;
2120     PyObject *result = NULL;
2121     struct kevent *evl = NULL;
2122     struct kevent *chl = NULL;
2123     struct timespec timeoutspec;
2124     struct timespec *ptimeoutspec;
2125     _PyTime_t timeout, deadline = 0;
2126 
2127     if (self->kqfd < 0)
2128         return kqueue_queue_err_closed();
2129 
2130     if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout))
2131         return NULL;
2132 
2133     if (nevents < 0) {
2134         PyErr_Format(PyExc_ValueError,
2135             "Length of eventlist must be 0 or positive, got %d",
2136             nevents);
2137         return NULL;
2138     }
2139 
2140     if (otimeout == Py_None || otimeout == NULL) {
2141         ptimeoutspec = NULL;
2142     }
2143     else {
2144         if (_PyTime_FromSecondsObject(&timeout,
2145                                       otimeout, _PyTime_ROUND_TIMEOUT) < 0) {
2146             PyErr_Format(PyExc_TypeError,
2147                 "timeout argument must be a number "
2148                 "or None, got %.200s",
2149                 Py_TYPE(otimeout)->tp_name);
2150             return NULL;
2151         }
2152 
2153         if (_PyTime_AsTimespec(timeout, &timeoutspec) == -1)
2154             return NULL;
2155 
2156         if (timeoutspec.tv_sec < 0) {
2157             PyErr_SetString(PyExc_ValueError,
2158                             "timeout must be positive or None");
2159             return NULL;
2160         }
2161         ptimeoutspec = &timeoutspec;
2162     }
2163 
2164     if (ch != NULL && ch != Py_None) {
2165         seq = PySequence_Fast(ch, "changelist is not iterable");
2166         if (seq == NULL) {
2167             return NULL;
2168         }
2169         if (PySequence_Fast_GET_SIZE(seq) > INT_MAX) {
2170             PyErr_SetString(PyExc_OverflowError,
2171                             "changelist is too long");
2172             goto error;
2173         }
2174         nchanges = (int)PySequence_Fast_GET_SIZE(seq);
2175 
2176         chl = PyMem_New(struct kevent, nchanges);
2177         if (chl == NULL) {
2178             PyErr_NoMemory();
2179             goto error;
2180         }
2181         for (i = 0; i < nchanges; ++i) {
2182             ei = PySequence_Fast_GET_ITEM(seq, i);
2183             if (!kqueue_event_Check(ei)) {
2184                 PyErr_SetString(PyExc_TypeError,
2185                     "changelist must be an iterable of "
2186                     "select.kevent objects");
2187                 goto error;
2188             }
2189             chl[i] = ((kqueue_event_Object *)ei)->e;
2190         }
2191         Py_CLEAR(seq);
2192     }
2193 
2194     /* event list */
2195     if (nevents) {
2196         evl = PyMem_New(struct kevent, nevents);
2197         if (evl == NULL) {
2198             PyErr_NoMemory();
2199             goto error;
2200         }
2201     }
2202 
2203     if (ptimeoutspec)
2204         deadline = _PyTime_GetMonotonicClock() + timeout;
2205 
2206     do {
2207         Py_BEGIN_ALLOW_THREADS
2208         errno = 0;
2209         gotevents = kevent(self->kqfd, chl, nchanges,
2210                            evl, nevents, ptimeoutspec);
2211         Py_END_ALLOW_THREADS
2212 
2213         if (errno != EINTR)
2214             break;
2215 
2216         /* kevent() was interrupted by a signal */
2217         if (PyErr_CheckSignals())
2218             goto error;
2219 
2220         if (ptimeoutspec) {
2221             timeout = deadline - _PyTime_GetMonotonicClock();
2222             if (timeout < 0) {
2223                 gotevents = 0;
2224                 break;
2225             }
2226             if (_PyTime_AsTimespec(timeout, &timeoutspec) == -1)
2227                 goto error;
2228             /* retry kevent() with the recomputed timeout */
2229         }
2230     } while (1);
2231 
2232     if (gotevents == -1) {
2233         PyErr_SetFromErrno(PyExc_OSError);
2234         goto error;
2235     }
2236 
2237     result = PyList_New(gotevents);
2238     if (result == NULL) {
2239         goto error;
2240     }
2241 
2242     for (i = 0; i < gotevents; i++) {
2243         kqueue_event_Object *ch;
2244 
2245         ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type);
2246         if (ch == NULL) {
2247             goto error;
2248         }
2249         ch->e = evl[i];
2250         PyList_SET_ITEM(result, i, (PyObject *)ch);
2251     }
2252     PyMem_Free(chl);
2253     PyMem_Free(evl);
2254     return result;
2255 
2256     error:
2257     PyMem_Free(chl);
2258     PyMem_Free(evl);
2259     Py_XDECREF(result);
2260     Py_XDECREF(seq);
2261     return NULL;
2262 }
2263 
2264 PyDoc_STRVAR(kqueue_queue_control_doc,
2265 "control(changelist, max_events[, timeout=None]) -> eventlist\n\
2266 \n\
2267 Calls the kernel kevent function.\n\
2268 - changelist must be an iterable of kevent objects describing the changes\n\
2269   to be made to the kernel's watch list or None.\n\
2270 - max_events lets you specify the maximum number of events that the\n\
2271   kernel will return.\n\
2272 - timeout is the maximum time to wait in seconds, or else None,\n\
2273   to wait forever. timeout accepts floats for smaller timeouts, too.");
2274 
2275 
2276 static PyMethodDef kqueue_queue_methods[] = {
2277     {"fromfd",          (PyCFunction)kqueue_queue_fromfd,
2278      METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc},
2279     {"close",           (PyCFunction)kqueue_queue_close,        METH_NOARGS,
2280      kqueue_queue_close_doc},
2281     {"fileno",          (PyCFunction)kqueue_queue_fileno,       METH_NOARGS,
2282      kqueue_queue_fileno_doc},
2283     {"control",         (PyCFunction)kqueue_queue_control,
2284      METH_VARARGS ,     kqueue_queue_control_doc},
2285     {NULL,      NULL},
2286 };
2287 
2288 static PyGetSetDef kqueue_queue_getsetlist[] = {
2289     {"closed", (getter)kqueue_queue_get_closed, NULL,
2290      "True if the kqueue handler is closed"},
2291     {0},
2292 };
2293 
2294 PyDoc_STRVAR(kqueue_queue_doc,
2295 "Kqueue syscall wrapper.\n\
2296 \n\
2297 For example, to start watching a socket for input:\n\
2298 >>> kq = kqueue()\n\
2299 >>> sock = socket()\n\
2300 >>> sock.connect((host, port))\n\
2301 >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\
2302 \n\
2303 To wait one second for it to become writeable:\n\
2304 >>> kq.control(None, 1, 1000)\n\
2305 \n\
2306 To stop listening:\n\
2307 >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)");
2308 
2309 static PyTypeObject kqueue_queue_Type = {
2310     PyVarObject_HEAD_INIT(NULL, 0)
2311     "select.kqueue",                                    /* tp_name */
2312     sizeof(kqueue_queue_Object),                        /* tp_basicsize */
2313     0,                                                  /* tp_itemsize */
2314     (destructor)kqueue_queue_dealloc,                   /* tp_dealloc */
2315     0,                                                  /* tp_print */
2316     0,                                                  /* tp_getattr */
2317     0,                                                  /* tp_setattr */
2318     0,                                                  /* tp_reserved */
2319     0,                                                  /* tp_repr */
2320     0,                                                  /* tp_as_number */
2321     0,                                                  /* tp_as_sequence */
2322     0,                                                  /* tp_as_mapping */
2323     0,                                                  /* tp_hash */
2324     0,                                                  /* tp_call */
2325     0,                                                  /* tp_str */
2326     0,                                                  /* tp_getattro */
2327     0,                                                  /* tp_setattro */
2328     0,                                                  /* tp_as_buffer */
2329     Py_TPFLAGS_DEFAULT,                                 /* tp_flags */
2330     kqueue_queue_doc,                                   /* tp_doc */
2331     0,                                                  /* tp_traverse */
2332     0,                                                  /* tp_clear */
2333     0,                                                  /* tp_richcompare */
2334     0,                                                  /* tp_weaklistoffset */
2335     0,                                                  /* tp_iter */
2336     0,                                                  /* tp_iternext */
2337     kqueue_queue_methods,                               /* tp_methods */
2338     0,                                                  /* tp_members */
2339     kqueue_queue_getsetlist,                            /* tp_getset */
2340     0,                                                  /* tp_base */
2341     0,                                                  /* tp_dict */
2342     0,                                                  /* tp_descr_get */
2343     0,                                                  /* tp_descr_set */
2344     0,                                                  /* tp_dictoffset */
2345     0,                                                  /* tp_init */
2346     0,                                                  /* tp_alloc */
2347     kqueue_queue_new,                                   /* tp_new */
2348     0,                                                  /* tp_free */
2349 };
2350 
2351 #endif /* HAVE_KQUEUE */
2352 
2353 
2354 
2355 
2356 
2357 /* ************************************************************************ */
2358 
2359 PyDoc_STRVAR(select_doc,
2360 "select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\
2361 \n\
2362 Wait until one or more file descriptors are ready for some kind of I/O.\n\
2363 The first three arguments are sequences of file descriptors to be waited for:\n\
2364 rlist -- wait until ready for reading\n\
2365 wlist -- wait until ready for writing\n\
2366 xlist -- wait for an ``exceptional condition''\n\
2367 If only one kind of condition is required, pass [] for the other lists.\n\
2368 A file descriptor is either a socket or file object, or a small integer\n\
2369 gotten from a fileno() method call on one of those.\n\
2370 \n\
2371 The optional 4th argument specifies a timeout in seconds; it may be\n\
2372 a floating point number to specify fractions of seconds.  If it is absent\n\
2373 or None, the call will never time out.\n\
2374 \n\
2375 The return value is a tuple of three lists corresponding to the first three\n\
2376 arguments; each contains the subset of the corresponding file descriptors\n\
2377 that are ready.\n\
2378 \n\
2379 *** IMPORTANT NOTICE ***\n\
2380 On Windows, only sockets are supported; on Unix, all file\n\
2381 descriptors can be used.");
2382 
2383 static PyMethodDef select_methods[] = {
2384     {"select",          select_select,  METH_VARARGS,   select_doc},
2385 #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
2386     {"poll",            select_poll,    METH_NOARGS,    poll_doc},
2387 #endif /* HAVE_POLL */
2388 #ifdef HAVE_SYS_DEVPOLL_H
2389     {"devpoll",         select_devpoll, METH_NOARGS,    devpoll_doc},
2390 #endif
2391     {0,         0},     /* sentinel */
2392 };
2393 
2394 PyDoc_STRVAR(module_doc,
2395 "This module supports asynchronous I/O on multiple file descriptors.\n\
2396 \n\
2397 *** IMPORTANT NOTICE ***\n\
2398 On Windows, only sockets are supported; on Unix, all file descriptors.");
2399 
2400 
2401 static struct PyModuleDef selectmodule = {
2402     PyModuleDef_HEAD_INIT,
2403     "select",
2404     module_doc,
2405     -1,
2406     select_methods,
2407     NULL,
2408     NULL,
2409     NULL,
2410     NULL
2411 };
2412 
2413 
2414 
2415 
2416 PyMODINIT_FUNC
PyInit_select(void)2417 PyInit_select(void)
2418 {
2419     PyObject *m;
2420     m = PyModule_Create(&selectmodule);
2421     if (m == NULL)
2422         return NULL;
2423 
2424     Py_INCREF(PyExc_OSError);
2425     PyModule_AddObject(m, "error", PyExc_OSError);
2426 
2427 #ifdef PIPE_BUF
2428 #ifdef HAVE_BROKEN_PIPE_BUF
2429 #undef PIPE_BUF
2430 #define PIPE_BUF 512
2431 #endif
2432     PyModule_AddIntMacro(m, PIPE_BUF);
2433 #endif
2434 
2435 #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
2436 #ifdef __APPLE__
2437     if (select_have_broken_poll()) {
2438         if (PyObject_DelAttrString(m, "poll") == -1) {
2439             PyErr_Clear();
2440         }
2441     } else {
2442 #else
2443     {
2444 #endif
2445         if (PyType_Ready(&poll_Type) < 0)
2446             return NULL;
2447         PyModule_AddIntMacro(m, POLLIN);
2448         PyModule_AddIntMacro(m, POLLPRI);
2449         PyModule_AddIntMacro(m, POLLOUT);
2450         PyModule_AddIntMacro(m, POLLERR);
2451         PyModule_AddIntMacro(m, POLLHUP);
2452         PyModule_AddIntMacro(m, POLLNVAL);
2453 
2454 #ifdef POLLRDNORM
2455         PyModule_AddIntMacro(m, POLLRDNORM);
2456 #endif
2457 #ifdef POLLRDBAND
2458         PyModule_AddIntMacro(m, POLLRDBAND);
2459 #endif
2460 #ifdef POLLWRNORM
2461         PyModule_AddIntMacro(m, POLLWRNORM);
2462 #endif
2463 #ifdef POLLWRBAND
2464         PyModule_AddIntMacro(m, POLLWRBAND);
2465 #endif
2466 #ifdef POLLMSG
2467         PyModule_AddIntMacro(m, POLLMSG);
2468 #endif
2469 #ifdef POLLRDHUP
2470         /* Kernel 2.6.17+ */
2471         PyModule_AddIntMacro(m, POLLRDHUP);
2472 #endif
2473     }
2474 #endif /* HAVE_POLL */
2475 
2476 #ifdef HAVE_SYS_DEVPOLL_H
2477     if (PyType_Ready(&devpoll_Type) < 0)
2478         return NULL;
2479 #endif
2480 
2481 #ifdef HAVE_EPOLL
2482     Py_TYPE(&pyEpoll_Type) = &PyType_Type;
2483     if (PyType_Ready(&pyEpoll_Type) < 0)
2484         return NULL;
2485 
2486     Py_INCREF(&pyEpoll_Type);
2487     PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type);
2488 
2489     PyModule_AddIntMacro(m, EPOLLIN);
2490     PyModule_AddIntMacro(m, EPOLLOUT);
2491     PyModule_AddIntMacro(m, EPOLLPRI);
2492     PyModule_AddIntMacro(m, EPOLLERR);
2493     PyModule_AddIntMacro(m, EPOLLHUP);
2494 #ifdef EPOLLRDHUP
2495     /* Kernel 2.6.17 */
2496     PyModule_AddIntMacro(m, EPOLLRDHUP);
2497 #endif
2498     PyModule_AddIntMacro(m, EPOLLET);
2499 #ifdef EPOLLONESHOT
2500     /* Kernel 2.6.2+ */
2501     PyModule_AddIntMacro(m, EPOLLONESHOT);
2502 #endif
2503 #ifdef EPOLLEXCLUSIVE
2504     PyModule_AddIntMacro(m, EPOLLEXCLUSIVE);
2505 #endif
2506 
2507 #ifdef EPOLLRDNORM
2508     PyModule_AddIntMacro(m, EPOLLRDNORM);
2509 #endif
2510 #ifdef EPOLLRDBAND
2511     PyModule_AddIntMacro(m, EPOLLRDBAND);
2512 #endif
2513 #ifdef EPOLLWRNORM
2514     PyModule_AddIntMacro(m, EPOLLWRNORM);
2515 #endif
2516 #ifdef EPOLLWRBAND
2517     PyModule_AddIntMacro(m, EPOLLWRBAND);
2518 #endif
2519 #ifdef EPOLLMSG
2520     PyModule_AddIntMacro(m, EPOLLMSG);
2521 #endif
2522 
2523 #ifdef EPOLL_CLOEXEC
2524     PyModule_AddIntMacro(m, EPOLL_CLOEXEC);
2525 #endif
2526 #endif /* HAVE_EPOLL */
2527 
2528 #ifdef HAVE_KQUEUE
2529     kqueue_event_Type.tp_new = PyType_GenericNew;
2530     Py_TYPE(&kqueue_event_Type) = &PyType_Type;
2531     if(PyType_Ready(&kqueue_event_Type) < 0)
2532         return NULL;
2533 
2534     Py_INCREF(&kqueue_event_Type);
2535     PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type);
2536 
2537     Py_TYPE(&kqueue_queue_Type) = &PyType_Type;
2538     if(PyType_Ready(&kqueue_queue_Type) < 0)
2539         return NULL;
2540     Py_INCREF(&kqueue_queue_Type);
2541     PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type);
2542 
2543     /* event filters */
2544     PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);
2545     PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);
2546 #ifdef EVFILT_AIO
2547     PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
2548 #endif
2549 #ifdef EVFILT_VNODE
2550     PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
2551 #endif
2552 #ifdef EVFILT_PROC
2553     PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
2554 #endif
2555 #ifdef EVFILT_NETDEV
2556     PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
2557 #endif
2558 #ifdef EVFILT_SIGNAL
2559     PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
2560 #endif
2561     PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);
2562 
2563     /* event flags */
2564     PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);
2565     PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);
2566     PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);
2567     PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);
2568     PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);
2569     PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);
2570 
2571 #ifdef EV_SYSFLAGS
2572     PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
2573 #endif
2574 #ifdef EV_FLAG1
2575     PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);
2576 #endif
2577 
2578     PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
2579     PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);
2580 
2581     /* READ WRITE filter flag */
2582 #ifdef NOTE_LOWAT
2583     PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);
2584 #endif
2585 
2586     /* VNODE filter flags  */
2587 #ifdef EVFILT_VNODE
2588     PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);
2589     PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);
2590     PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);
2591     PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);
2592     PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);
2593     PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);
2594     PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);
2595 #endif
2596 
2597     /* PROC filter flags  */
2598 #ifdef EVFILT_PROC
2599     PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);
2600     PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);
2601     PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);
2602     PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);
2603     PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);
2604 
2605     PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);
2606     PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);
2607     PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);
2608 #endif
2609 
2610     /* NETDEV filter flags */
2611 #ifdef EVFILT_NETDEV
2612     PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);
2613     PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);
2614     PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);
2615 #endif
2616 
2617 #endif /* HAVE_KQUEUE */
2618     return m;
2619 }
2620