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    Under BeOS, we suffer the same dichotomy as Win32; sockets can be anything
6    >= 0.
7 */
8 
9 #include "Python.h"
10 #include <structmember.h>
11 
12 #ifdef __APPLE__
13     /* Perform runtime testing for a broken poll on OSX to make it easier
14      * to use the same binary on multiple releases of the OS.
15      */
16 #undef HAVE_BROKEN_POLL
17 #endif
18 
19 /* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined.
20    64 is too small (too many people have bumped into that limit).
21    Here we boost it.
22    Users who want even more than the boosted limit should #define
23    FD_SETSIZE higher before this; e.g., via compiler /D switch.
24 */
25 #if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
26 #define FD_SETSIZE 512
27 #endif
28 
29 #if defined(HAVE_POLL_H)
30 #include <poll.h>
31 #elif defined(HAVE_SYS_POLL_H)
32 #include <sys/poll.h>
33 #endif
34 
35 #ifdef __sgi
36 /* This is missing from unistd.h */
37 extern void bzero(void *, int);
38 #endif
39 
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
42 #endif
43 
44 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
45 #include <sys/time.h>
46 #include <utils.h>
47 #endif
48 
49 #ifdef MS_WINDOWS
50 #  include <winsock2.h>
51 #else
52 #  define SOCKET int
53 #  ifdef __BEOS__
54 #    include <net/socket.h>
55 #  elif defined(__VMS)
56 #    include <socket.h>
57 #  endif
58 #endif
59 
60 static PyObject *SelectError;
61 
62 /* list of Python objects and their file descriptor */
63 typedef struct {
64     PyObject *obj;                           /* owned reference */
65     SOCKET fd;
66     int sentinel;                            /* -1 == sentinel */
67 } pylist;
68 
69 static void
reap_obj(pylist fd2obj[FD_SETSIZE+1])70 reap_obj(pylist fd2obj[FD_SETSIZE + 1])
71 {
72     int i;
73     for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
74         Py_CLEAR(fd2obj[i].obj);
75     }
76     fd2obj[0].sentinel = -1;
77 }
78 
79 
80 /* returns -1 and sets the Python exception if an error occurred, otherwise
81    returns a number >= 0
82 */
83 static int
seq2set(PyObject * seq,fd_set * set,pylist fd2obj[FD_SETSIZE+1])84 seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
85 {
86     int i;
87     int max = -1;
88     int index = 0;
89     PyObject* fast_seq = NULL;
90     PyObject* o = NULL;
91 
92     fd2obj[0].obj = (PyObject*)0;            /* set list to zero size */
93     FD_ZERO(set);
94 
95     fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
96     if (!fast_seq)
97         return -1;
98 
99     for (i = 0; i < PySequence_Fast_GET_SIZE(fast_seq); i++)  {
100         SOCKET v;
101 
102         /* any intervening fileno() calls could decr this refcnt */
103         if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
104             return -1;
105 
106         Py_INCREF(o);
107         v = PyObject_AsFileDescriptor( o );
108         if (v == -1) goto finally;
109 
110 #if defined(_MSC_VER)
111         max = 0;                             /* not used for Win32 */
112 #else  /* !_MSC_VER */
113         if (!_PyIsSelectable_fd(v)) {
114             PyErr_SetString(PyExc_ValueError,
115                         "filedescriptor out of range in select()");
116             goto finally;
117         }
118         if (v > max)
119             max = v;
120 #endif /* _MSC_VER */
121         FD_SET(v, set);
122 
123         /* add object and its file descriptor to the list */
124         if (index >= FD_SETSIZE) {
125             PyErr_SetString(PyExc_ValueError,
126                           "too many file descriptors in select()");
127             goto finally;
128         }
129         fd2obj[index].obj = o;
130         fd2obj[index].fd = v;
131         fd2obj[index].sentinel = 0;
132         fd2obj[++index].sentinel = -1;
133     }
134     Py_DECREF(fast_seq);
135     return max+1;
136 
137   finally:
138     Py_XDECREF(o);
139     Py_DECREF(fast_seq);
140     return -1;
141 }
142 
143 /* returns NULL and sets the Python exception if an error occurred */
144 static PyObject *
set2list(fd_set * set,pylist fd2obj[FD_SETSIZE+1])145 set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
146 {
147     int i, j, count=0;
148     PyObject *list, *o;
149     SOCKET fd;
150 
151     for (j = 0; fd2obj[j].sentinel >= 0; j++) {
152         if (FD_ISSET(fd2obj[j].fd, set))
153             count++;
154     }
155     list = PyList_New(count);
156     if (!list)
157         return NULL;
158 
159     i = 0;
160     for (j = 0; fd2obj[j].sentinel >= 0; j++) {
161         fd = fd2obj[j].fd;
162         if (FD_ISSET(fd, set)) {
163             o = fd2obj[j].obj;
164             fd2obj[j].obj = NULL;
165             /* transfer ownership */
166             if (PyList_SetItem(list, i, o) < 0)
167                 goto finally;
168 
169             i++;
170         }
171     }
172     return list;
173   finally:
174     Py_DECREF(list);
175     return NULL;
176 }
177 
178 #undef SELECT_USES_HEAP
179 #if FD_SETSIZE > 1024
180 #define SELECT_USES_HEAP
181 #endif /* FD_SETSIZE > 1024 */
182 
183 static PyObject *
select_select(PyObject * self,PyObject * args)184 select_select(PyObject *self, PyObject *args)
185 {
186 #ifdef SELECT_USES_HEAP
187     pylist *rfd2obj, *wfd2obj, *efd2obj;
188 #else  /* !SELECT_USES_HEAP */
189     /* XXX: All this should probably be implemented as follows:
190      * - find the highest descriptor we're interested in
191      * - add one
192      * - that's the size
193      * See: Stevens, APitUE, $12.5.1
194      */
195     pylist rfd2obj[FD_SETSIZE + 1];
196     pylist wfd2obj[FD_SETSIZE + 1];
197     pylist efd2obj[FD_SETSIZE + 1];
198 #endif /* SELECT_USES_HEAP */
199     PyObject *ifdlist, *ofdlist, *efdlist;
200     PyObject *ret = NULL;
201     PyObject *tout = Py_None;
202     fd_set ifdset, ofdset, efdset;
203     double timeout;
204     struct timeval tv, *tvp;
205     long seconds;
206     int imax, omax, emax, max;
207     int n;
208 
209     /* convert arguments */
210     if (!PyArg_UnpackTuple(args, "select", 3, 4,
211                           &ifdlist, &ofdlist, &efdlist, &tout))
212         return NULL;
213 
214     if (tout == Py_None)
215         tvp = (struct timeval *)0;
216     else if (!PyNumber_Check(tout)) {
217         PyErr_SetString(PyExc_TypeError,
218                         "timeout must be a float or None");
219         return NULL;
220     }
221     else {
222         timeout = PyFloat_AsDouble(tout);
223         if (timeout == -1 && PyErr_Occurred())
224             return NULL;
225         if (timeout > (double)LONG_MAX) {
226             PyErr_SetString(PyExc_OverflowError,
227                             "timeout period too long");
228             return NULL;
229         }
230         seconds = (long)timeout;
231         timeout = timeout - (double)seconds;
232         tv.tv_sec = seconds;
233         tv.tv_usec = (long)(timeout * 1E6);
234         tvp = &tv;
235     }
236 
237 
238 #ifdef SELECT_USES_HEAP
239     /* Allocate memory for the lists */
240     rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
241     wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
242     efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
243     if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
244         if (rfd2obj) PyMem_DEL(rfd2obj);
245         if (wfd2obj) PyMem_DEL(wfd2obj);
246         if (efd2obj) PyMem_DEL(efd2obj);
247         return PyErr_NoMemory();
248     }
249 #endif /* SELECT_USES_HEAP */
250     /* Convert sequences to fd_sets, and get maximum fd number
251      * propagates the Python exception set in seq2set()
252      */
253     rfd2obj[0].sentinel = -1;
254     wfd2obj[0].sentinel = -1;
255     efd2obj[0].sentinel = -1;
256     if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
257         goto finally;
258     if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
259         goto finally;
260     if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
261         goto finally;
262     max = imax;
263     if (omax > max) max = omax;
264     if (emax > max) max = emax;
265 
266     Py_BEGIN_ALLOW_THREADS
267     n = select(max, &ifdset, &ofdset, &efdset, tvp);
268     Py_END_ALLOW_THREADS
269 
270 #ifdef MS_WINDOWS
271     if (n == SOCKET_ERROR) {
272         PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError());
273     }
274 #else
275     if (n < 0) {
276         PyErr_SetFromErrno(SelectError);
277     }
278 #endif
279     else {
280         /* any of these three calls can raise an exception.  it's more
281            convenient to test for this after all three calls... but
282            is that acceptable?
283         */
284         ifdlist = set2list(&ifdset, rfd2obj);
285         ofdlist = set2list(&ofdset, wfd2obj);
286         efdlist = set2list(&efdset, efd2obj);
287         if (PyErr_Occurred())
288             ret = NULL;
289         else
290             ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);
291 
292         Py_XDECREF(ifdlist);
293         Py_XDECREF(ofdlist);
294         Py_XDECREF(efdlist);
295     }
296 
297   finally:
298     reap_obj(rfd2obj);
299     reap_obj(wfd2obj);
300     reap_obj(efd2obj);
301 #ifdef SELECT_USES_HEAP
302     PyMem_DEL(rfd2obj);
303     PyMem_DEL(wfd2obj);
304     PyMem_DEL(efd2obj);
305 #endif /* SELECT_USES_HEAP */
306     return ret;
307 }
308 
309 #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
310 /*
311  * poll() support
312  */
313 
314 typedef struct {
315     PyObject_HEAD
316     PyObject *dict;
317     int ufd_uptodate;
318     int ufd_len;
319     struct pollfd *ufds;
320     int poll_running;
321 } pollObject;
322 
323 static PyTypeObject poll_Type;
324 
325 /* Update the malloc'ed array of pollfds to match the dictionary
326    contained within a pollObject.  Return 1 on success, 0 on an error.
327 */
328 
329 static int
update_ufd_array(pollObject * self)330 update_ufd_array(pollObject *self)
331 {
332     Py_ssize_t i, pos;
333     PyObject *key, *value;
334     struct pollfd *old_ufds = self->ufds;
335 
336     self->ufd_len = PyDict_Size(self->dict);
337     PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
338     if (self->ufds == NULL) {
339         self->ufds = old_ufds;
340         PyErr_NoMemory();
341         return 0;
342     }
343 
344     i = pos = 0;
345     while (PyDict_Next(self->dict, &pos, &key, &value)) {
346         assert(i < self->ufd_len);
347         /* Never overflow */
348         self->ufds[i].fd = (int)PyInt_AsLong(key);
349         self->ufds[i].events = (short)(unsigned short)PyInt_AsLong(value);
350         i++;
351     }
352     assert(i == self->ufd_len);
353     self->ufd_uptodate = 1;
354     return 1;
355 }
356 
357 static int
ushort_converter(PyObject * obj,void * ptr)358 ushort_converter(PyObject *obj, void *ptr)
359 {
360     unsigned long uval;
361 
362     uval = PyLong_AsUnsignedLong(obj);
363     if (uval == (unsigned long)-1 && PyErr_Occurred())
364         return 0;
365     if (uval > USHRT_MAX) {
366         PyErr_SetString(PyExc_OverflowError,
367                         "Python int too large for C unsigned short");
368         return 0;
369     }
370 
371     *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
372     return 1;
373 }
374 
375 PyDoc_STRVAR(poll_register_doc,
376 "register(fd [, eventmask] ) -> None\n\n\
377 Register a file descriptor with the polling object.\n\
378 fd -- either an integer, or an object with a fileno() method returning an\n\
379       int.\n\
380 events -- an optional bitmask describing the type of events to check for");
381 
382 static PyObject *
poll_register(pollObject * self,PyObject * args)383 poll_register(pollObject *self, PyObject *args)
384 {
385     PyObject *o, *key, *value;
386     int fd;
387     unsigned short events = POLLIN | POLLPRI | POLLOUT;
388     int err;
389 
390     if (!PyArg_ParseTuple(args, "O|O&:register", &o, ushort_converter, &events))
391         return NULL;
392 
393     fd = PyObject_AsFileDescriptor(o);
394     if (fd == -1) return NULL;
395 
396     /* Add entry to the internal dictionary: the key is the
397        file descriptor, and the value is the event mask. */
398     key = PyInt_FromLong(fd);
399     if (key == NULL)
400         return NULL;
401     value = PyInt_FromLong(events);
402     if (value == NULL) {
403         Py_DECREF(key);
404         return NULL;
405     }
406     err = PyDict_SetItem(self->dict, key, value);
407     Py_DECREF(key);
408     Py_DECREF(value);
409     if (err < 0)
410         return NULL;
411 
412     self->ufd_uptodate = 0;
413 
414     Py_INCREF(Py_None);
415     return Py_None;
416 }
417 
418 PyDoc_STRVAR(poll_modify_doc,
419 "modify(fd, eventmask) -> None\n\n\
420 Modify an already registered file descriptor.\n\
421 fd -- either an integer, or an object with a fileno() method returning an\n\
422       int.\n\
423 events -- an optional bitmask describing the type of events to check for");
424 
425 static PyObject *
poll_modify(pollObject * self,PyObject * args)426 poll_modify(pollObject *self, PyObject *args)
427 {
428     PyObject *o, *key, *value;
429     int fd;
430     unsigned short events;
431     int err;
432 
433     if (!PyArg_ParseTuple(args, "OO&:modify", &o, ushort_converter, &events))
434         return NULL;
435 
436     fd = PyObject_AsFileDescriptor(o);
437     if (fd == -1) return NULL;
438 
439     /* Modify registered fd */
440     key = PyInt_FromLong(fd);
441     if (key == NULL)
442         return NULL;
443     if (PyDict_GetItem(self->dict, key) == NULL) {
444         errno = ENOENT;
445         PyErr_SetFromErrno(PyExc_IOError);
446         return NULL;
447     }
448     value = PyInt_FromLong(events);
449     if (value == NULL) {
450         Py_DECREF(key);
451         return NULL;
452     }
453     err = PyDict_SetItem(self->dict, key, value);
454     Py_DECREF(key);
455     Py_DECREF(value);
456     if (err < 0)
457         return NULL;
458 
459     self->ufd_uptodate = 0;
460 
461     Py_INCREF(Py_None);
462     return Py_None;
463 }
464 
465 
466 PyDoc_STRVAR(poll_unregister_doc,
467 "unregister(fd) -> None\n\n\
468 Remove a file descriptor being tracked by the polling object.");
469 
470 static PyObject *
poll_unregister(pollObject * self,PyObject * o)471 poll_unregister(pollObject *self, PyObject *o)
472 {
473     PyObject *key;
474     int fd;
475 
476     fd = PyObject_AsFileDescriptor( o );
477     if (fd == -1)
478         return NULL;
479 
480     /* Check whether the fd is already in the array */
481     key = PyInt_FromLong(fd);
482     if (key == NULL)
483         return NULL;
484 
485     if (PyDict_DelItem(self->dict, key) == -1) {
486         Py_DECREF(key);
487         /* This will simply raise the KeyError set by PyDict_DelItem
488            if the file descriptor isn't registered. */
489         return NULL;
490     }
491 
492     Py_DECREF(key);
493     self->ufd_uptodate = 0;
494 
495     Py_INCREF(Py_None);
496     return Py_None;
497 }
498 
499 PyDoc_STRVAR(poll_poll_doc,
500 "poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
501 Polls the set of registered file descriptors, returning a list containing \n\
502 any descriptors that have events or errors to report.");
503 
504 static PyObject *
poll_poll(pollObject * self,PyObject * args)505 poll_poll(pollObject *self, PyObject *args)
506 {
507     PyObject *result_list = NULL, *tout = NULL;
508     int timeout = 0, poll_result, i, j;
509     PyObject *value = NULL, *num = NULL;
510 
511     if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {
512         return NULL;
513     }
514 
515     /* Check values for timeout */
516     if (tout == NULL || tout == Py_None)
517         timeout = -1;
518     else if (!PyNumber_Check(tout)) {
519         PyErr_SetString(PyExc_TypeError,
520                         "timeout must be an integer or None");
521         return NULL;
522     }
523     else {
524         tout = PyNumber_Int(tout);
525         if (!tout)
526             return NULL;
527         timeout = _PyInt_AsInt(tout);
528         Py_DECREF(tout);
529         if (timeout == -1 && PyErr_Occurred())
530             return NULL;
531     }
532 
533     /* On some OSes, typically BSD-based ones, the timeout parameter of the
534        poll() syscall, when negative, must be exactly INFTIM, where defined,
535        or -1. See issue 31334. */
536     if (timeout < 0) {
537 #ifdef INFTIM
538         timeout = INFTIM;
539 #else
540         timeout = -1;
541 #endif
542     }
543 
544     /* Avoid concurrent poll() invocation, issue 8865 */
545     if (self->poll_running) {
546         PyErr_SetString(PyExc_RuntimeError,
547                         "concurrent poll() invocation");
548         return NULL;
549     }
550 
551     /* Ensure the ufd array is up to date */
552     if (!self->ufd_uptodate)
553         if (update_ufd_array(self) == 0)
554             return NULL;
555 
556     self->poll_running = 1;
557 
558     /* call poll() */
559     Py_BEGIN_ALLOW_THREADS
560     poll_result = poll(self->ufds, self->ufd_len, timeout);
561     Py_END_ALLOW_THREADS
562 
563     self->poll_running = 0;
564 
565     if (poll_result < 0) {
566         PyErr_SetFromErrno(SelectError);
567         return NULL;
568     }
569 
570     /* build the result list */
571 
572     result_list = PyList_New(poll_result);
573     if (!result_list)
574         return NULL;
575     else {
576         for (i = 0, j = 0; j < poll_result; j++) {
577             /* skip to the next fired descriptor */
578             while (!self->ufds[i].revents) {
579                 i++;
580             }
581             /* if we hit a NULL return, set value to NULL
582                and break out of loop; code at end will
583                clean up result_list */
584             value = PyTuple_New(2);
585             if (value == NULL)
586                 goto error;
587             num = PyInt_FromLong(self->ufds[i].fd);
588             if (num == NULL) {
589                 Py_DECREF(value);
590                 goto error;
591             }
592             PyTuple_SET_ITEM(value, 0, num);
593 
594             /* The &0xffff is a workaround for AIX.  'revents'
595                is a 16-bit short, and IBM assigned POLLNVAL
596                to be 0x8000, so the conversion to int results
597                in a negative number. See SF bug #923315. */
598             num = PyInt_FromLong(self->ufds[i].revents & 0xffff);
599             if (num == NULL) {
600                 Py_DECREF(value);
601                 goto error;
602             }
603             PyTuple_SET_ITEM(value, 1, num);
604             PyList_SET_ITEM(result_list, j, value);
605             i++;
606         }
607     }
608     return result_list;
609 
610   error:
611     Py_DECREF(result_list);
612     return NULL;
613 }
614 
615 static PyMethodDef poll_methods[] = {
616     {"register",        (PyCFunction)poll_register,
617      METH_VARARGS,  poll_register_doc},
618     {"modify",          (PyCFunction)poll_modify,
619      METH_VARARGS,  poll_modify_doc},
620     {"unregister",      (PyCFunction)poll_unregister,
621      METH_O,        poll_unregister_doc},
622     {"poll",            (PyCFunction)poll_poll,
623      METH_VARARGS,  poll_poll_doc},
624     {NULL,              NULL}           /* sentinel */
625 };
626 
627 static pollObject *
newPollObject(void)628 newPollObject(void)
629 {
630     pollObject *self;
631     self = PyObject_New(pollObject, &poll_Type);
632     if (self == NULL)
633         return NULL;
634     /* ufd_uptodate is a Boolean, denoting whether the
635        array pointed to by ufds matches the contents of the dictionary. */
636     self->ufd_uptodate = 0;
637     self->ufds = NULL;
638     self->poll_running = 0;
639     self->dict = PyDict_New();
640     if (self->dict == NULL) {
641         Py_DECREF(self);
642         return NULL;
643     }
644     return self;
645 }
646 
647 static void
poll_dealloc(pollObject * self)648 poll_dealloc(pollObject *self)
649 {
650     if (self->ufds != NULL)
651         PyMem_DEL(self->ufds);
652     Py_XDECREF(self->dict);
653     PyObject_Del(self);
654 }
655 
656 static PyObject *
poll_getattr(pollObject * self,char * name)657 poll_getattr(pollObject *self, char *name)
658 {
659     return Py_FindMethod(poll_methods, (PyObject *)self, name);
660 }
661 
662 static PyTypeObject poll_Type = {
663     /* The ob_type field must be initialized in the module init function
664      * to be portable to Windows without using C++. */
665     PyVarObject_HEAD_INIT(NULL, 0)
666     "select.poll",              /*tp_name*/
667     sizeof(pollObject),         /*tp_basicsize*/
668     0,                          /*tp_itemsize*/
669     /* methods */
670     (destructor)poll_dealloc, /*tp_dealloc*/
671     0,                          /*tp_print*/
672     (getattrfunc)poll_getattr, /*tp_getattr*/
673     0,                      /*tp_setattr*/
674     0,                          /*tp_compare*/
675     0,                          /*tp_repr*/
676     0,                          /*tp_as_number*/
677     0,                          /*tp_as_sequence*/
678     0,                          /*tp_as_mapping*/
679     0,                          /*tp_hash*/
680 };
681 
682 PyDoc_STRVAR(poll_doc,
683 "Returns a polling object, which supports registering and\n\
684 unregistering file descriptors, and then polling them for I/O events.");
685 
686 static PyObject *
select_poll(PyObject * self,PyObject * unused)687 select_poll(PyObject *self, PyObject *unused)
688 {
689     return (PyObject *)newPollObject();
690 }
691 
692 #ifdef __APPLE__
693 /*
694  * On some systems poll() sets errno on invalid file descriptors. We test
695  * for this at runtime because this bug may be fixed or introduced between
696  * OS releases.
697  */
select_have_broken_poll(void)698 static int select_have_broken_poll(void)
699 {
700     int poll_test;
701     int filedes[2];
702 
703     struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };
704 
705     /* Create a file descriptor to make invalid */
706     if (pipe(filedes) < 0) {
707         return 1;
708     }
709     poll_struct.fd = filedes[0];
710     close(filedes[0]);
711     close(filedes[1]);
712     poll_test = poll(&poll_struct, 1, 0);
713     if (poll_test < 0) {
714         return 1;
715     } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
716         return 1;
717     }
718     return 0;
719 }
720 #endif /* __APPLE__ */
721 
722 #endif /* HAVE_POLL */
723 
724 #ifdef HAVE_EPOLL
725 /* **************************************************************************
726  *                      epoll interface for Linux 2.6
727  *
728  * Written by Christian Heimes
729  * Inspired by Twisted's _epoll.pyx and select.poll()
730  */
731 
732 #ifdef HAVE_SYS_EPOLL_H
733 #include <sys/epoll.h>
734 #endif
735 
736 typedef struct {
737     PyObject_HEAD
738     SOCKET epfd;                        /* epoll control file descriptor */
739 } pyEpoll_Object;
740 
741 static PyTypeObject pyEpoll_Type;
742 #define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type))
743 
744 static PyObject *
pyepoll_err_closed(void)745 pyepoll_err_closed(void)
746 {
747     PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd");
748     return NULL;
749 }
750 
751 static int
pyepoll_internal_close(pyEpoll_Object * self)752 pyepoll_internal_close(pyEpoll_Object *self)
753 {
754     int save_errno = 0;
755     if (self->epfd >= 0) {
756         int epfd = self->epfd;
757         self->epfd = -1;
758         Py_BEGIN_ALLOW_THREADS
759         if (close(epfd) < 0)
760             save_errno = errno;
761         Py_END_ALLOW_THREADS
762     }
763     return save_errno;
764 }
765 
766 static PyObject *
newPyEpoll_Object(PyTypeObject * type,int sizehint,SOCKET fd)767 newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd)
768 {
769     pyEpoll_Object *self;
770 
771     if (sizehint == -1) {
772         sizehint = FD_SETSIZE-1;
773     }
774     else if (sizehint < 1) {
775         PyErr_Format(PyExc_ValueError,
776                      "sizehint must be greater zero, got %d",
777                      sizehint);
778         return NULL;
779     }
780 
781     assert(type != NULL && type->tp_alloc != NULL);
782     self = (pyEpoll_Object *) type->tp_alloc(type, 0);
783     if (self == NULL)
784         return NULL;
785 
786     if (fd == -1) {
787         Py_BEGIN_ALLOW_THREADS
788         self->epfd = epoll_create(sizehint);
789         Py_END_ALLOW_THREADS
790     }
791     else {
792         self->epfd = fd;
793     }
794     if (self->epfd < 0) {
795         Py_DECREF(self);
796         PyErr_SetFromErrno(PyExc_IOError);
797         return NULL;
798     }
799     return (PyObject *)self;
800 }
801 
802 
803 static PyObject *
pyepoll_new(PyTypeObject * type,PyObject * args,PyObject * kwds)804 pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
805 {
806     int sizehint = -1;
807     static char *kwlist[] = {"sizehint", NULL};
808 
809     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist,
810                                      &sizehint))
811         return NULL;
812 
813     return newPyEpoll_Object(type, sizehint, -1);
814 }
815 
816 
817 static void
pyepoll_dealloc(pyEpoll_Object * self)818 pyepoll_dealloc(pyEpoll_Object *self)
819 {
820     (void)pyepoll_internal_close(self);
821     Py_TYPE(self)->tp_free(self);
822 }
823 
824 static PyObject*
pyepoll_close(pyEpoll_Object * self)825 pyepoll_close(pyEpoll_Object *self)
826 {
827     errno = pyepoll_internal_close(self);
828     if (errno < 0) {
829         PyErr_SetFromErrno(PyExc_IOError);
830         return NULL;
831     }
832     Py_RETURN_NONE;
833 }
834 
835 PyDoc_STRVAR(pyepoll_close_doc,
836 "close() -> None\n\
837 \n\
838 Close the epoll control file descriptor. Further operations on the epoll\n\
839 object will raise an exception.");
840 
841 static PyObject*
pyepoll_get_closed(pyEpoll_Object * self)842 pyepoll_get_closed(pyEpoll_Object *self)
843 {
844     if (self->epfd < 0)
845         Py_RETURN_TRUE;
846     else
847         Py_RETURN_FALSE;
848 }
849 
850 static PyObject*
pyepoll_fileno(pyEpoll_Object * self)851 pyepoll_fileno(pyEpoll_Object *self)
852 {
853     if (self->epfd < 0)
854         return pyepoll_err_closed();
855     return PyInt_FromLong(self->epfd);
856 }
857 
858 PyDoc_STRVAR(pyepoll_fileno_doc,
859 "fileno() -> int\n\
860 \n\
861 Return the epoll control file descriptor.");
862 
863 static PyObject*
pyepoll_fromfd(PyObject * cls,PyObject * args)864 pyepoll_fromfd(PyObject *cls, PyObject *args)
865 {
866     SOCKET fd;
867 
868     if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
869         return NULL;
870 
871     return newPyEpoll_Object((PyTypeObject*)cls, -1, fd);
872 }
873 
874 PyDoc_STRVAR(pyepoll_fromfd_doc,
875 "fromfd(fd) -> epoll\n\
876 \n\
877 Create an epoll object from a given control fd.");
878 
879 static PyObject *
pyepoll_internal_ctl(int epfd,int op,PyObject * pfd,unsigned int events)880 pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events)
881 {
882     struct epoll_event ev;
883     int result;
884     int fd;
885 
886     if (epfd < 0)
887         return pyepoll_err_closed();
888 
889     fd = PyObject_AsFileDescriptor(pfd);
890     if (fd == -1) {
891         return NULL;
892     }
893 
894     switch(op) {
895         case EPOLL_CTL_ADD:
896         case EPOLL_CTL_MOD:
897         ev.events = events;
898         ev.data.fd = fd;
899         Py_BEGIN_ALLOW_THREADS
900         result = epoll_ctl(epfd, op, fd, &ev);
901         Py_END_ALLOW_THREADS
902         break;
903         case EPOLL_CTL_DEL:
904         /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
905          * operation required a non-NULL pointer in event, even
906          * though this argument is ignored. */
907         Py_BEGIN_ALLOW_THREADS
908         result = epoll_ctl(epfd, op, fd, &ev);
909         if (errno == EBADF) {
910             /* fd already closed */
911             result = 0;
912             errno = 0;
913         }
914         Py_END_ALLOW_THREADS
915         break;
916         default:
917         result = -1;
918         errno = EINVAL;
919     }
920 
921     if (result < 0) {
922         PyErr_SetFromErrno(PyExc_IOError);
923         return NULL;
924     }
925     Py_RETURN_NONE;
926 }
927 
928 static PyObject *
pyepoll_register(pyEpoll_Object * self,PyObject * args,PyObject * kwds)929 pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
930 {
931     PyObject *pfd;
932     unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;
933     static char *kwlist[] = {"fd", "eventmask", NULL};
934 
935     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
936                                      &pfd, &events)) {
937         return NULL;
938     }
939 
940     return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
941 }
942 
943 PyDoc_STRVAR(pyepoll_register_doc,
944 "register(fd[, eventmask]) -> None\n\
945 \n\
946 Registers a new fd or raises an IOError if the fd is already registered.\n\
947 fd is the target file descriptor of the operation.\n\
948 events is a bit set composed of the various EPOLL constants; the default\n\
949 is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\
950 \n\
951 The epoll interface supports all file descriptors that support poll.");
952 
953 static PyObject *
pyepoll_modify(pyEpoll_Object * self,PyObject * args,PyObject * kwds)954 pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
955 {
956     PyObject *pfd;
957     unsigned int events;
958     static char *kwlist[] = {"fd", "eventmask", NULL};
959 
960     if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
961                                      &pfd, &events)) {
962         return NULL;
963     }
964 
965     return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
966 }
967 
968 PyDoc_STRVAR(pyepoll_modify_doc,
969 "modify(fd, eventmask) -> None\n\
970 \n\
971 fd is the target file descriptor of the operation\n\
972 events is a bit set composed of the various EPOLL constants");
973 
974 static PyObject *
pyepoll_unregister(pyEpoll_Object * self,PyObject * args,PyObject * kwds)975 pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
976 {
977     PyObject *pfd;
978     static char *kwlist[] = {"fd", NULL};
979 
980     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
981                                      &pfd)) {
982         return NULL;
983     }
984 
985     return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
986 }
987 
988 PyDoc_STRVAR(pyepoll_unregister_doc,
989 "unregister(fd) -> None\n\
990 \n\
991 fd is the target file descriptor of the operation.");
992 
993 static PyObject *
pyepoll_poll(pyEpoll_Object * self,PyObject * args,PyObject * kwds)994 pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
995 {
996     double dtimeout = -1.;
997     int timeout;
998     int maxevents = -1;
999     int nfds, i;
1000     PyObject *elist = NULL, *etuple = NULL;
1001     struct epoll_event *evs = NULL;
1002     static char *kwlist[] = {"timeout", "maxevents", NULL};
1003 
1004     if (self->epfd < 0)
1005         return pyepoll_err_closed();
1006 
1007     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist,
1008                                      &dtimeout, &maxevents)) {
1009         return NULL;
1010     }
1011 
1012     if (dtimeout < 0) {
1013         timeout = -1;
1014     }
1015     else if (dtimeout * 1000.0 > INT_MAX) {
1016         PyErr_SetString(PyExc_OverflowError,
1017                         "timeout is too large");
1018         return NULL;
1019     }
1020     else {
1021         timeout = (int)(dtimeout * 1000.0);
1022     }
1023 
1024     if (maxevents == -1) {
1025         maxevents = FD_SETSIZE-1;
1026     }
1027     else if (maxevents < 1) {
1028         PyErr_Format(PyExc_ValueError,
1029                      "maxevents must be greater than 0, got %d",
1030                      maxevents);
1031         return NULL;
1032     }
1033 
1034     evs = PyMem_New(struct epoll_event, maxevents);
1035     if (evs == NULL) {
1036         Py_DECREF(self);
1037         PyErr_NoMemory();
1038         return NULL;
1039     }
1040 
1041     Py_BEGIN_ALLOW_THREADS
1042     nfds = epoll_wait(self->epfd, evs, maxevents, timeout);
1043     Py_END_ALLOW_THREADS
1044     if (nfds < 0) {
1045         PyErr_SetFromErrno(PyExc_IOError);
1046         goto error;
1047     }
1048 
1049     elist = PyList_New(nfds);
1050     if (elist == NULL) {
1051         goto error;
1052     }
1053 
1054     for (i = 0; i < nfds; i++) {
1055         etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
1056         if (etuple == NULL) {
1057             Py_CLEAR(elist);
1058             goto error;
1059         }
1060         PyList_SET_ITEM(elist, i, etuple);
1061     }
1062 
1063     error:
1064     PyMem_Free(evs);
1065     return elist;
1066 }
1067 
1068 PyDoc_STRVAR(pyepoll_poll_doc,
1069 "poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\
1070 \n\
1071 Wait for events on the epoll file descriptor for a maximum time of timeout\n\
1072 in seconds (as float). -1 makes poll wait indefinitely.\n\
1073 Up to maxevents are returned to the caller.");
1074 
1075 static PyMethodDef pyepoll_methods[] = {
1076     {"fromfd",          (PyCFunction)pyepoll_fromfd,
1077      METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},
1078     {"close",           (PyCFunction)pyepoll_close,     METH_NOARGS,
1079      pyepoll_close_doc},
1080     {"fileno",          (PyCFunction)pyepoll_fileno,    METH_NOARGS,
1081      pyepoll_fileno_doc},
1082     {"modify",          (PyCFunction)pyepoll_modify,
1083      METH_VARARGS | METH_KEYWORDS,      pyepoll_modify_doc},
1084     {"register",        (PyCFunction)pyepoll_register,
1085      METH_VARARGS | METH_KEYWORDS,      pyepoll_register_doc},
1086     {"unregister",      (PyCFunction)pyepoll_unregister,
1087      METH_VARARGS | METH_KEYWORDS,      pyepoll_unregister_doc},
1088     {"poll",            (PyCFunction)pyepoll_poll,
1089      METH_VARARGS | METH_KEYWORDS,      pyepoll_poll_doc},
1090     {NULL,      NULL},
1091 };
1092 
1093 static PyGetSetDef pyepoll_getsetlist[] = {
1094     {"closed", (getter)pyepoll_get_closed, NULL,
1095      "True if the epoll handler is closed"},
1096     {0},
1097 };
1098 
1099 PyDoc_STRVAR(pyepoll_doc,
1100 "select.epoll([sizehint=-1])\n\
1101 \n\
1102 Returns an epolling object\n\
1103 \n\
1104 sizehint must be a positive integer or -1 for the default size. The\n\
1105 sizehint is used to optimize internal data structures. It doesn't limit\n\
1106 the maximum number of monitored events.");
1107 
1108 static PyTypeObject pyEpoll_Type = {
1109     PyVarObject_HEAD_INIT(NULL, 0)
1110     "select.epoll",                                     /* tp_name */
1111     sizeof(pyEpoll_Object),                             /* tp_basicsize */
1112     0,                                                  /* tp_itemsize */
1113     (destructor)pyepoll_dealloc,                        /* tp_dealloc */
1114     0,                                                  /* tp_print */
1115     0,                                                  /* tp_getattr */
1116     0,                                                  /* tp_setattr */
1117     0,                                                  /* tp_compare */
1118     0,                                                  /* tp_repr */
1119     0,                                                  /* tp_as_number */
1120     0,                                                  /* tp_as_sequence */
1121     0,                                                  /* tp_as_mapping */
1122     0,                                                  /* tp_hash */
1123     0,                                                  /* tp_call */
1124     0,                                                  /* tp_str */
1125     PyObject_GenericGetAttr,                            /* tp_getattro */
1126     0,                                                  /* tp_setattro */
1127     0,                                                  /* tp_as_buffer */
1128     Py_TPFLAGS_DEFAULT,                                 /* tp_flags */
1129     pyepoll_doc,                                        /* tp_doc */
1130     0,                                                  /* tp_traverse */
1131     0,                                                  /* tp_clear */
1132     0,                                                  /* tp_richcompare */
1133     0,                                                  /* tp_weaklistoffset */
1134     0,                                                  /* tp_iter */
1135     0,                                                  /* tp_iternext */
1136     pyepoll_methods,                                    /* tp_methods */
1137     0,                                                  /* tp_members */
1138     pyepoll_getsetlist,                                 /* tp_getset */
1139     0,                                                  /* tp_base */
1140     0,                                                  /* tp_dict */
1141     0,                                                  /* tp_descr_get */
1142     0,                                                  /* tp_descr_set */
1143     0,                                                  /* tp_dictoffset */
1144     0,                                                  /* tp_init */
1145     0,                                                  /* tp_alloc */
1146     pyepoll_new,                                        /* tp_new */
1147     0,                                                  /* tp_free */
1148 };
1149 
1150 #endif /* HAVE_EPOLL */
1151 
1152 #ifdef HAVE_KQUEUE
1153 /* **************************************************************************
1154  *                      kqueue interface for BSD
1155  *
1156  * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
1157  * All rights reserved.
1158  *
1159  * Redistribution and use in source and binary forms, with or without
1160  * modification, are permitted provided that the following conditions
1161  * are met:
1162  * 1. Redistributions of source code must retain the above copyright
1163  *    notice, this list of conditions and the following disclaimer.
1164  * 2. Redistributions in binary form must reproduce the above copyright
1165  *    notice, this list of conditions and the following disclaimer in the
1166  *    documentation and/or other materials provided with the distribution.
1167  *
1168  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1169  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1170  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1171  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1172  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1173  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1174  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1175  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1176  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1177  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1178  * SUCH DAMAGE.
1179  */
1180 
1181 #ifdef HAVE_SYS_EVENT_H
1182 #include <sys/event.h>
1183 #endif
1184 
1185 PyDoc_STRVAR(kqueue_event_doc,
1186 "kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\
1187 \n\
1188 This object is the equivalent of the struct kevent for the C API.\n\
1189 \n\
1190 See the kqueue manpage for more detailed information about the meaning\n\
1191 of the arguments.\n\
1192 \n\
1193 One minor note: while you might hope that udata could store a\n\
1194 reference to a python object, it cannot, because it is impossible to\n\
1195 keep a proper reference count of the object once it's passed into the\n\
1196 kernel. Therefore, I have restricted it to only storing an integer.  I\n\
1197 recommend ignoring it and simply using the 'ident' field to key off\n\
1198 of. You could also set up a dictionary on the python side to store a\n\
1199 udata->object mapping.");
1200 
1201 typedef struct {
1202     PyObject_HEAD
1203     struct kevent e;
1204 } kqueue_event_Object;
1205 
1206 static PyTypeObject kqueue_event_Type;
1207 
1208 #define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type))
1209 
1210 typedef struct {
1211     PyObject_HEAD
1212     SOCKET kqfd;                /* kqueue control fd */
1213 } kqueue_queue_Object;
1214 
1215 static PyTypeObject kqueue_queue_Type;
1216 
1217 #define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type))
1218 
1219 #if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P)
1220 #   error uintptr_t does not match void *!
1221 #elif defined(HAVE_LONG_LONG) && (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG)
1222 #   define T_UINTPTRT         T_ULONGLONG
1223 #   define T_INTPTRT          T_LONGLONG
1224 #   define UINTPTRT_FMT_UNIT  "K"
1225 #   define INTPTRT_FMT_UNIT   "L"
1226 #elif (SIZEOF_UINTPTR_T == SIZEOF_LONG)
1227 #   define T_UINTPTRT         T_ULONG
1228 #   define T_INTPTRT          T_LONG
1229 #   define UINTPTRT_FMT_UNIT  "k"
1230 #   define INTPTRT_FMT_UNIT   "l"
1231 #elif (SIZEOF_UINTPTR_T == SIZEOF_INT)
1232 #   define T_UINTPTRT         T_UINT
1233 #   define T_INTPTRT          T_INT
1234 #   define UINTPTRT_FMT_UNIT  "I"
1235 #   define INTPTRT_FMT_UNIT   "i"
1236 #else
1237 #   error uintptr_t does not match int, long, or long long!
1238 #endif
1239 
1240 #if defined(HAVE_LONG_LONG) && SIZEOF_LONG_LONG == 8
1241 #   define T_INT64          T_LONGLONG
1242 #   define INT64_FMT_UNIT   "L"
1243 #elif SIZEOF_LONG == 8
1244 #   define T_INT64          T_LONG
1245 #   define INT64_FMT_UNIT   "l"
1246 #elif SIZEOF_INT == 8
1247 #   define T_INT64          T_INT
1248 #   define INT64_FMT_UNIT   "i"
1249 #else
1250 #   define INT64_FMT_UNIT   "_"
1251 #endif
1252 
1253 #if defined(HAVE_LONG_LONG) && SIZEOF_LONG_LONG == 4
1254 #   define T_UINT32         T_ULONGLONG
1255 #   define UINT32_FMT_UNIT  "K"
1256 #elif SIZEOF_LONG == 4
1257 #   define T_UINT32         T_ULONG
1258 #   define UINT32_FMT_UNIT  "k"
1259 #elif SIZEOF_INT == 4
1260 #   define T_UINT32         T_UINT
1261 #   define UINT32_FMT_UNIT  "I"
1262 #else
1263 #   define UINT32_FMT_UNIT  "_"
1264 #endif
1265 
1266 /*
1267  * kevent is not standard and its members vary across BSDs.
1268  */
1269 #ifdef __NetBSD__
1270 #   define FILTER_TYPE      T_UINT32
1271 #   define FILTER_FMT_UNIT  UINT32_FMT_UNIT
1272 #   define FLAGS_TYPE       T_UINT32
1273 #   define FLAGS_FMT_UNIT   UINT32_FMT_UNIT
1274 #   define FFLAGS_TYPE      T_UINT32
1275 #   define FFLAGS_FMT_UNIT  UINT32_FMT_UNIT
1276 #else
1277 #   define FILTER_TYPE      T_SHORT
1278 #   define FILTER_FMT_UNIT  "h"
1279 #   define FLAGS_TYPE       T_USHORT
1280 #   define FLAGS_FMT_UNIT   "H"
1281 #   define FFLAGS_TYPE      T_UINT
1282 #   define FFLAGS_FMT_UNIT  "I"
1283 #endif
1284 
1285 #if defined(__NetBSD__) || defined(__OpenBSD__)
1286 #   define DATA_TYPE        T_INT64
1287 #   define DATA_FMT_UNIT    INT64_FMT_UNIT
1288 #else
1289 #   define DATA_TYPE        T_INTPTRT
1290 #   define DATA_FMT_UNIT    INTPTRT_FMT_UNIT
1291 #endif
1292 
1293 /* Unfortunately, we can't store python objects in udata, because
1294  * kevents in the kernel can be removed without warning, which would
1295  * forever lose the refcount on the object stored with it.
1296  */
1297 
1298 #define KQ_OFF(x) offsetof(kqueue_event_Object, x)
1299 static struct PyMemberDef kqueue_event_members[] = {
1300     {"ident",           T_UINTPTRT,     KQ_OFF(e.ident)},
1301     {"filter",          FILTER_TYPE,    KQ_OFF(e.filter)},
1302     {"flags",           FLAGS_TYPE,     KQ_OFF(e.flags)},
1303     {"fflags",          T_UINT,         KQ_OFF(e.fflags)},
1304     {"data",            DATA_TYPE,      KQ_OFF(e.data)},
1305     {"udata",           T_UINTPTRT,     KQ_OFF(e.udata)},
1306     {NULL} /* Sentinel */
1307 };
1308 #undef KQ_OFF
1309 
1310 static PyObject *
1311 
kqueue_event_repr(kqueue_event_Object * s)1312 kqueue_event_repr(kqueue_event_Object *s)
1313 {
1314     char buf[1024];
1315     PyOS_snprintf(
1316         buf, sizeof(buf),
1317 #ifdef HAVE_LONG_LONG
1318         "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
1319         "data=0x%llx udata=%p>",
1320         (size_t)(s->e.ident), (int)s->e.filter, (unsigned int)s->e.flags,
1321         (unsigned int)s->e.fflags, (long long)(s->e.data), (void *)s->e.udata);
1322 #else
1323         "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
1324         "data=0x%llx udata=%p>",
1325         (size_t)(s->e.ident), (int)s->e.filter, (unsigned int)s->e.flags,
1326         (unsigned int)s->e.fflags, (long)(s->e.data), (void *)s->e.udata);
1327 #endif
1328     return PyString_FromString(buf);
1329 }
1330 
1331 static int
kqueue_event_init(kqueue_event_Object * self,PyObject * args,PyObject * kwds)1332 kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds)
1333 {
1334     PyObject *pfd;
1335     static char *kwlist[] = {"ident", "filter", "flags", "fflags",
1336                              "data", "udata", NULL};
1337     static const char fmt[] = "O|"
1338                 FILTER_FMT_UNIT FLAGS_FMT_UNIT FFLAGS_FMT_UNIT DATA_FMT_UNIT
1339                 UINTPTRT_FMT_UNIT ":kevent";
1340 
1341     EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
1342 
1343     if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1344         &pfd, &(self->e.filter), &(self->e.flags),
1345         &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
1346         return -1;
1347     }
1348 
1349     if (PyInt_Check(pfd)) {
1350         self->e.ident = PyInt_AsUnsignedLongMask(pfd);
1351     }
1352     else if (PyLong_Check(pfd)) {
1353 #if defined(HAVE_LONG_LONG) && (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG)
1354         self->e.ident = PyLong_AsUnsignedLongLongMask(pfd);
1355 #else
1356         self->e.ident = PyLong_AsUnsignedLongMask(pfd);
1357 #endif
1358     }
1359     else {
1360         self->e.ident = PyObject_AsFileDescriptor(pfd);
1361     }
1362     if (PyErr_Occurred()) {
1363         return -1;
1364     }
1365     return 0;
1366 }
1367 
1368 static PyObject *
kqueue_event_richcompare(kqueue_event_Object * s,kqueue_event_Object * o,int op)1369 kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o,
1370                          int op)
1371 {
1372     int result;
1373 
1374     if (!kqueue_event_Check(o)) {
1375         Py_INCREF(Py_NotImplemented);
1376         return Py_NotImplemented;
1377     }
1378 
1379 #define CMP(a, b) ((a) != (b)) ? ((a) < (b) ? -1 : 1)
1380     result = CMP(s->e.ident, o->e.ident)
1381            : CMP(s->e.filter, o->e.filter)
1382            : CMP(s->e.flags, o->e.flags)
1383            : CMP(s->e.fflags, o->e.fflags)
1384            : CMP(s->e.data, o->e.data)
1385            : CMP((Py_intptr_t)s->e.udata, (Py_intptr_t)o->e.udata)
1386            : 0;
1387 #undef CMP
1388 
1389     switch (op) {
1390         case Py_EQ:
1391         result = (result == 0);
1392         break;
1393         case Py_NE:
1394         result = (result != 0);
1395         break;
1396         case Py_LE:
1397         result = (result <= 0);
1398         break;
1399         case Py_GE:
1400         result = (result >= 0);
1401         break;
1402         case Py_LT:
1403         result = (result < 0);
1404         break;
1405         case Py_GT:
1406         result = (result > 0);
1407         break;
1408     }
1409     return PyBool_FromLong((long)result);
1410 }
1411 
1412 static PyTypeObject kqueue_event_Type = {
1413     PyVarObject_HEAD_INIT(NULL, 0)
1414     "select.kevent",                                    /* tp_name */
1415     sizeof(kqueue_event_Object),                        /* tp_basicsize */
1416     0,                                                  /* tp_itemsize */
1417     0,                                                  /* tp_dealloc */
1418     0,                                                  /* tp_print */
1419     0,                                                  /* tp_getattr */
1420     0,                                                  /* tp_setattr */
1421     0,                                                  /* tp_compare */
1422     (reprfunc)kqueue_event_repr,                        /* tp_repr */
1423     0,                                                  /* tp_as_number */
1424     0,                                                  /* tp_as_sequence */
1425     0,                                                  /* tp_as_mapping */
1426     0,                                                  /* tp_hash */
1427     0,                                                  /* tp_call */
1428     0,                                                  /* tp_str */
1429     0,                                                  /* tp_getattro */
1430     0,                                                  /* tp_setattro */
1431     0,                                                  /* tp_as_buffer */
1432     Py_TPFLAGS_DEFAULT,                                 /* tp_flags */
1433     kqueue_event_doc,                                   /* tp_doc */
1434     0,                                                  /* tp_traverse */
1435     0,                                                  /* tp_clear */
1436     (richcmpfunc)kqueue_event_richcompare,              /* tp_richcompare */
1437     0,                                                  /* tp_weaklistoffset */
1438     0,                                                  /* tp_iter */
1439     0,                                                  /* tp_iternext */
1440     0,                                                  /* tp_methods */
1441     kqueue_event_members,                               /* tp_members */
1442     0,                                                  /* tp_getset */
1443     0,                                                  /* tp_base */
1444     0,                                                  /* tp_dict */
1445     0,                                                  /* tp_descr_get */
1446     0,                                                  /* tp_descr_set */
1447     0,                                                  /* tp_dictoffset */
1448     (initproc)kqueue_event_init,                        /* tp_init */
1449     0,                                                  /* tp_alloc */
1450     0,                                                  /* tp_new */
1451     0,                                                  /* tp_free */
1452 };
1453 
1454 static PyObject *
kqueue_queue_err_closed(void)1455 kqueue_queue_err_closed(void)
1456 {
1457     PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd");
1458     return NULL;
1459 }
1460 
1461 static int
kqueue_queue_internal_close(kqueue_queue_Object * self)1462 kqueue_queue_internal_close(kqueue_queue_Object *self)
1463 {
1464     int save_errno = 0;
1465     if (self->kqfd >= 0) {
1466         int kqfd = self->kqfd;
1467         self->kqfd = -1;
1468         Py_BEGIN_ALLOW_THREADS
1469         if (close(kqfd) < 0)
1470             save_errno = errno;
1471         Py_END_ALLOW_THREADS
1472     }
1473     return save_errno;
1474 }
1475 
1476 static PyObject *
newKqueue_Object(PyTypeObject * type,SOCKET fd)1477 newKqueue_Object(PyTypeObject *type, SOCKET fd)
1478 {
1479     kqueue_queue_Object *self;
1480     assert(type != NULL && type->tp_alloc != NULL);
1481     self = (kqueue_queue_Object *) type->tp_alloc(type, 0);
1482     if (self == NULL) {
1483         return NULL;
1484     }
1485 
1486     if (fd == -1) {
1487         Py_BEGIN_ALLOW_THREADS
1488         self->kqfd = kqueue();
1489         Py_END_ALLOW_THREADS
1490     }
1491     else {
1492         self->kqfd = fd;
1493     }
1494     if (self->kqfd < 0) {
1495         Py_DECREF(self);
1496         PyErr_SetFromErrno(PyExc_IOError);
1497         return NULL;
1498     }
1499     return (PyObject *)self;
1500 }
1501 
1502 static PyObject *
kqueue_queue_new(PyTypeObject * type,PyObject * args,PyObject * kwds)1503 kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1504 {
1505 
1506     if ((args != NULL && PyObject_Size(args)) ||
1507                     (kwds != NULL && PyObject_Size(kwds))) {
1508         PyErr_SetString(PyExc_ValueError,
1509                         "select.kqueue doesn't accept arguments");
1510         return NULL;
1511     }
1512 
1513     return newKqueue_Object(type, -1);
1514 }
1515 
1516 static void
kqueue_queue_dealloc(kqueue_queue_Object * self)1517 kqueue_queue_dealloc(kqueue_queue_Object *self)
1518 {
1519     kqueue_queue_internal_close(self);
1520     Py_TYPE(self)->tp_free(self);
1521 }
1522 
1523 static PyObject*
kqueue_queue_close(kqueue_queue_Object * self)1524 kqueue_queue_close(kqueue_queue_Object *self)
1525 {
1526     errno = kqueue_queue_internal_close(self);
1527     if (errno < 0) {
1528         PyErr_SetFromErrno(PyExc_IOError);
1529         return NULL;
1530     }
1531     Py_RETURN_NONE;
1532 }
1533 
1534 PyDoc_STRVAR(kqueue_queue_close_doc,
1535 "close() -> None\n\
1536 \n\
1537 Close the kqueue control file descriptor. Further operations on the kqueue\n\
1538 object will raise an exception.");
1539 
1540 static PyObject*
kqueue_queue_get_closed(kqueue_queue_Object * self)1541 kqueue_queue_get_closed(kqueue_queue_Object *self)
1542 {
1543     if (self->kqfd < 0)
1544         Py_RETURN_TRUE;
1545     else
1546         Py_RETURN_FALSE;
1547 }
1548 
1549 static PyObject*
kqueue_queue_fileno(kqueue_queue_Object * self)1550 kqueue_queue_fileno(kqueue_queue_Object *self)
1551 {
1552     if (self->kqfd < 0)
1553         return kqueue_queue_err_closed();
1554     return PyInt_FromLong(self->kqfd);
1555 }
1556 
1557 PyDoc_STRVAR(kqueue_queue_fileno_doc,
1558 "fileno() -> int\n\
1559 \n\
1560 Return the kqueue control file descriptor.");
1561 
1562 static PyObject*
kqueue_queue_fromfd(PyObject * cls,PyObject * args)1563 kqueue_queue_fromfd(PyObject *cls, PyObject *args)
1564 {
1565     SOCKET fd;
1566 
1567     if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
1568         return NULL;
1569 
1570     return newKqueue_Object((PyTypeObject*)cls, fd);
1571 }
1572 
1573 PyDoc_STRVAR(kqueue_queue_fromfd_doc,
1574 "fromfd(fd) -> kqueue\n\
1575 \n\
1576 Create a kqueue object from a given control fd.");
1577 
1578 static PyObject *
kqueue_queue_control(kqueue_queue_Object * self,PyObject * args)1579 kqueue_queue_control(kqueue_queue_Object *self, PyObject *args)
1580 {
1581     int nevents = 0;
1582     int gotevents = 0;
1583     int nchanges = 0;
1584     int i = 0;
1585     PyObject *otimeout = NULL;
1586     PyObject *ch = NULL;
1587     PyObject *seq = NULL, *ei = NULL;
1588     PyObject *result = NULL;
1589     struct kevent *evl = NULL;
1590     struct kevent *chl = NULL;
1591     struct timespec timeoutspec;
1592     struct timespec *ptimeoutspec;
1593 
1594     if (self->kqfd < 0)
1595         return kqueue_queue_err_closed();
1596 
1597     if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout))
1598         return NULL;
1599 
1600     if (nevents < 0) {
1601         PyErr_Format(PyExc_ValueError,
1602             "Length of eventlist must be 0 or positive, got %d",
1603             nevents);
1604         return NULL;
1605     }
1606 
1607     if (otimeout == Py_None || otimeout == NULL) {
1608         ptimeoutspec = NULL;
1609     }
1610     else if (PyNumber_Check(otimeout)) {
1611         double timeout;
1612         long seconds;
1613 
1614         timeout = PyFloat_AsDouble(otimeout);
1615         if (timeout == -1 && PyErr_Occurred())
1616             return NULL;
1617         if (timeout > (double)LONG_MAX) {
1618             PyErr_SetString(PyExc_OverflowError,
1619                             "timeout period too long");
1620             return NULL;
1621         }
1622         if (timeout < 0) {
1623             PyErr_SetString(PyExc_ValueError,
1624                             "timeout must be positive or None");
1625             return NULL;
1626         }
1627 
1628         seconds = (long)timeout;
1629         timeout = timeout - (double)seconds;
1630         timeoutspec.tv_sec = seconds;
1631         timeoutspec.tv_nsec = (long)(timeout * 1E9);
1632         ptimeoutspec = &timeoutspec;
1633     }
1634     else {
1635         PyErr_Format(PyExc_TypeError,
1636             "timeout argument must be an number "
1637             "or None, got %.200s",
1638             Py_TYPE(otimeout)->tp_name);
1639         return NULL;
1640     }
1641 
1642     if (ch != NULL && ch != Py_None) {
1643         seq = PySequence_Fast(ch, "changelist is not iterable");
1644         if (seq == NULL) {
1645             return NULL;
1646         }
1647         if (PySequence_Fast_GET_SIZE(seq) > INT_MAX) {
1648             PyErr_SetString(PyExc_OverflowError,
1649                             "changelist is too long");
1650             goto error;
1651         }
1652         nchanges = (int)PySequence_Fast_GET_SIZE(seq);
1653 
1654         chl = PyMem_New(struct kevent, nchanges);
1655         if (chl == NULL) {
1656             PyErr_NoMemory();
1657             goto error;
1658         }
1659         for (i = 0; i < nchanges; ++i) {
1660             ei = PySequence_Fast_GET_ITEM(seq, i);
1661             if (!kqueue_event_Check(ei)) {
1662                 PyErr_SetString(PyExc_TypeError,
1663                     "changelist must be an iterable of "
1664                     "select.kevent objects");
1665                 goto error;
1666             }
1667             chl[i] = ((kqueue_event_Object *)ei)->e;
1668         }
1669         Py_CLEAR(seq);
1670     }
1671 
1672     /* event list */
1673     if (nevents) {
1674         evl = PyMem_New(struct kevent, nevents);
1675         if (evl == NULL) {
1676             PyErr_NoMemory();
1677             goto error;
1678         }
1679     }
1680 
1681     Py_BEGIN_ALLOW_THREADS
1682     gotevents = kevent(self->kqfd, chl, nchanges,
1683                        evl, nevents, ptimeoutspec);
1684     Py_END_ALLOW_THREADS
1685 
1686     if (gotevents == -1) {
1687         PyErr_SetFromErrno(PyExc_OSError);
1688         goto error;
1689     }
1690 
1691     result = PyList_New(gotevents);
1692     if (result == NULL) {
1693         goto error;
1694     }
1695 
1696     for (i = 0; i < gotevents; i++) {
1697         kqueue_event_Object *ch;
1698 
1699         ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type);
1700         if (ch == NULL) {
1701             goto error;
1702         }
1703         ch->e = evl[i];
1704         PyList_SET_ITEM(result, i, (PyObject *)ch);
1705     }
1706     PyMem_Free(chl);
1707     PyMem_Free(evl);
1708     return result;
1709 
1710     error:
1711     PyMem_Free(chl);
1712     PyMem_Free(evl);
1713     Py_XDECREF(result);
1714     Py_XDECREF(seq);
1715     return NULL;
1716 }
1717 
1718 PyDoc_STRVAR(kqueue_queue_control_doc,
1719 "control(changelist, max_events[, timeout=None]) -> eventlist\n\
1720 \n\
1721 Calls the kernel kevent function.\n\
1722 - changelist must be an iterable of kevent objects describing the changes\n\
1723   to be made to the kernel's watch list or None.\n\
1724 - max_events lets you specify the maximum number of events that the\n\
1725   kernel will return.\n\
1726 - timeout is the maximum time to wait in seconds, or else None,\n\
1727   to wait forever. timeout accepts floats for smaller timeouts, too.");
1728 
1729 
1730 static PyMethodDef kqueue_queue_methods[] = {
1731     {"fromfd",          (PyCFunction)kqueue_queue_fromfd,
1732      METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc},
1733     {"close",           (PyCFunction)kqueue_queue_close,        METH_NOARGS,
1734      kqueue_queue_close_doc},
1735     {"fileno",          (PyCFunction)kqueue_queue_fileno,       METH_NOARGS,
1736      kqueue_queue_fileno_doc},
1737     {"control",         (PyCFunction)kqueue_queue_control,
1738      METH_VARARGS ,     kqueue_queue_control_doc},
1739     {NULL,      NULL},
1740 };
1741 
1742 static PyGetSetDef kqueue_queue_getsetlist[] = {
1743     {"closed", (getter)kqueue_queue_get_closed, NULL,
1744      "True if the kqueue handler is closed"},
1745     {0},
1746 };
1747 
1748 PyDoc_STRVAR(kqueue_queue_doc,
1749 "Kqueue syscall wrapper.\n\
1750 \n\
1751 For example, to start watching a socket for input:\n\
1752 >>> kq = kqueue()\n\
1753 >>> sock = socket()\n\
1754 >>> sock.connect((host, port))\n\
1755 >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\
1756 \n\
1757 To wait one second for it to become writeable:\n\
1758 >>> kq.control(None, 1, 1000)\n\
1759 \n\
1760 To stop listening:\n\
1761 >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)");
1762 
1763 static PyTypeObject kqueue_queue_Type = {
1764     PyVarObject_HEAD_INIT(NULL, 0)
1765     "select.kqueue",                                    /* tp_name */
1766     sizeof(kqueue_queue_Object),                        /* tp_basicsize */
1767     0,                                                  /* tp_itemsize */
1768     (destructor)kqueue_queue_dealloc,                   /* tp_dealloc */
1769     0,                                                  /* tp_print */
1770     0,                                                  /* tp_getattr */
1771     0,                                                  /* tp_setattr */
1772     0,                                                  /* tp_compare */
1773     0,                                                  /* tp_repr */
1774     0,                                                  /* tp_as_number */
1775     0,                                                  /* tp_as_sequence */
1776     0,                                                  /* tp_as_mapping */
1777     0,                                                  /* tp_hash */
1778     0,                                                  /* tp_call */
1779     0,                                                  /* tp_str */
1780     0,                                                  /* tp_getattro */
1781     0,                                                  /* tp_setattro */
1782     0,                                                  /* tp_as_buffer */
1783     Py_TPFLAGS_DEFAULT,                                 /* tp_flags */
1784     kqueue_queue_doc,                                   /* tp_doc */
1785     0,                                                  /* tp_traverse */
1786     0,                                                  /* tp_clear */
1787     0,                                                  /* tp_richcompare */
1788     0,                                                  /* tp_weaklistoffset */
1789     0,                                                  /* tp_iter */
1790     0,                                                  /* tp_iternext */
1791     kqueue_queue_methods,                               /* tp_methods */
1792     0,                                                  /* tp_members */
1793     kqueue_queue_getsetlist,                            /* tp_getset */
1794     0,                                                  /* tp_base */
1795     0,                                                  /* tp_dict */
1796     0,                                                  /* tp_descr_get */
1797     0,                                                  /* tp_descr_set */
1798     0,                                                  /* tp_dictoffset */
1799     0,                                                  /* tp_init */
1800     0,                                                  /* tp_alloc */
1801     kqueue_queue_new,                                   /* tp_new */
1802     0,                                                  /* tp_free */
1803 };
1804 
1805 #endif /* HAVE_KQUEUE */
1806 /* ************************************************************************ */
1807 
1808 PyDoc_STRVAR(select_doc,
1809 "select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\
1810 \n\
1811 Wait until one or more file descriptors are ready for some kind of I/O.\n\
1812 The first three arguments are sequences of file descriptors to be waited for:\n\
1813 rlist -- wait until ready for reading\n\
1814 wlist -- wait until ready for writing\n\
1815 xlist -- wait for an ``exceptional condition''\n\
1816 If only one kind of condition is required, pass [] for the other lists.\n\
1817 A file descriptor is either a socket or file object, or a small integer\n\
1818 gotten from a fileno() method call on one of those.\n\
1819 \n\
1820 The optional 4th argument specifies a timeout in seconds; it may be\n\
1821 a floating point number to specify fractions of seconds.  If it is absent\n\
1822 or None, the call will never time out.\n\
1823 \n\
1824 The return value is a tuple of three lists corresponding to the first three\n\
1825 arguments; each contains the subset of the corresponding file descriptors\n\
1826 that are ready.\n\
1827 \n\
1828 *** IMPORTANT NOTICE ***\n\
1829 On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\
1830 descriptors can be used.");
1831 
1832 static PyMethodDef select_methods[] = {
1833     {"select",          select_select,  METH_VARARGS,   select_doc},
1834 #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
1835     {"poll",            select_poll,    METH_NOARGS,    poll_doc},
1836 #endif /* HAVE_POLL */
1837     {0,         0},     /* sentinel */
1838 };
1839 
1840 PyDoc_STRVAR(module_doc,
1841 "This module supports asynchronous I/O on multiple file descriptors.\n\
1842 \n\
1843 *** IMPORTANT NOTICE ***\n\
1844 On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors.");
1845 
1846 PyMODINIT_FUNC
initselect(void)1847 initselect(void)
1848 {
1849     PyObject *m;
1850     m = Py_InitModule3("select", select_methods, module_doc);
1851     if (m == NULL)
1852         return;
1853 
1854     SelectError = PyErr_NewException("select.error", NULL, NULL);
1855     Py_INCREF(SelectError);
1856     PyModule_AddObject(m, "error", SelectError);
1857 
1858 #ifdef PIPE_BUF
1859 #ifdef HAVE_BROKEN_PIPE_BUF
1860 #undef PIPE_BUF
1861 #define PIPE_BUF 512
1862 #endif
1863     PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF);
1864 #endif
1865 
1866 #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
1867 #ifdef __APPLE__
1868     if (select_have_broken_poll()) {
1869         if (PyObject_DelAttrString(m, "poll") == -1) {
1870             PyErr_Clear();
1871         }
1872     } else {
1873 #else
1874     {
1875 #endif
1876         Py_TYPE(&poll_Type) = &PyType_Type;
1877         PyModule_AddIntConstant(m, "POLLIN", POLLIN);
1878         PyModule_AddIntConstant(m, "POLLPRI", POLLPRI);
1879         PyModule_AddIntConstant(m, "POLLOUT", POLLOUT);
1880         PyModule_AddIntConstant(m, "POLLERR", POLLERR);
1881         PyModule_AddIntConstant(m, "POLLHUP", POLLHUP);
1882         PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL);
1883 
1884 #ifdef POLLRDNORM
1885         PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM);
1886 #endif
1887 #ifdef POLLRDBAND
1888         PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND);
1889 #endif
1890 #ifdef POLLWRNORM
1891         PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM);
1892 #endif
1893 #ifdef POLLWRBAND
1894         PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND);
1895 #endif
1896 #ifdef POLLMSG
1897         PyModule_AddIntConstant(m, "POLLMSG", POLLMSG);
1898 #endif
1899     }
1900 #endif /* HAVE_POLL */
1901 
1902 #ifdef HAVE_EPOLL
1903     Py_TYPE(&pyEpoll_Type) = &PyType_Type;
1904     if (PyType_Ready(&pyEpoll_Type) < 0)
1905         return;
1906 
1907     Py_INCREF(&pyEpoll_Type);
1908     PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type);
1909 
1910     PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN);
1911     PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT);
1912     PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI);
1913     PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR);
1914     PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP);
1915     PyModule_AddIntConstant(m, "EPOLLET", EPOLLET);
1916 #ifdef EPOLLONESHOT
1917     /* Kernel 2.6.2+ */
1918     PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT);
1919 #endif
1920     /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */
1921 #ifdef EPOLLRDNORM
1922     PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM);
1923 #endif
1924 #ifdef EPOLLRDBAND
1925     PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND);
1926 #endif
1927 #ifdef EPOLLWRNORM
1928     PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM);
1929 #endif
1930 #ifdef EPOLLWRBAND
1931     PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND);
1932 #endif
1933 #ifdef EPOLLMSG
1934     PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG);
1935 #endif
1936 #endif /* HAVE_EPOLL */
1937 
1938 #ifdef HAVE_KQUEUE
1939     kqueue_event_Type.tp_new = PyType_GenericNew;
1940     Py_TYPE(&kqueue_event_Type) = &PyType_Type;
1941     if(PyType_Ready(&kqueue_event_Type) < 0)
1942         return;
1943 
1944     Py_INCREF(&kqueue_event_Type);
1945     PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type);
1946 
1947     Py_TYPE(&kqueue_queue_Type) = &PyType_Type;
1948     if(PyType_Ready(&kqueue_queue_Type) < 0)
1949         return;
1950     Py_INCREF(&kqueue_queue_Type);
1951     PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type);
1952 
1953     /* event filters */
1954     PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);
1955     PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);
1956     PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
1957     PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
1958     PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
1959 #ifdef EVFILT_NETDEV
1960     PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
1961 #endif
1962     PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
1963     PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);
1964 
1965     /* event flags */
1966     PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);
1967     PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);
1968     PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);
1969     PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);
1970     PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);
1971     PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);
1972 
1973     PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
1974     PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);
1975 
1976     PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
1977     PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);
1978 
1979     /* READ WRITE filter flag */
1980     PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);
1981 
1982     /* VNODE filter flags  */
1983     PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);
1984     PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);
1985     PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);
1986     PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);
1987     PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);
1988     PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);
1989     PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);
1990 
1991     /* PROC filter flags  */
1992     PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);
1993     PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);
1994     PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);
1995     PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);
1996     PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);
1997 
1998     PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);
1999     PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);
2000     PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);
2001 
2002     /* NETDEV filter flags */
2003 #ifdef EVFILT_NETDEV
2004     PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);
2005     PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);
2006     PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);
2007 #endif
2008 
2009 #endif /* HAVE_KQUEUE */
2010 }
2011