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