blob: 4d9925005d9ca5173129f9c20255606d19e96cd5 [file] [log] [blame]
Guido van Rossum4f0fbf81996-06-12 04:22:53 +00001/* select - Module containing unix select(2) call.
Barry Warsawe4ac0aa1996-12-12 00:04:35 +00002 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.
Guido van Rossum4f0fbf81996-06-12 04:22:53 +00005*/
Guido van Rossumed233a51992-06-23 09:07:03 +00006
Barry Warsawe4ac0aa1996-12-12 00:04:35 +00007#include "Python.h"
Christian Heimes4fbc72b2008-03-22 00:47:35 +00008#include <structmember.h>
Guido van Rossumed233a51992-06-23 09:07:03 +00009
Jesus Cead8b9ae62011-11-14 19:07:41 +010010#ifdef HAVE_SYS_DEVPOLL_H
11#include <sys/resource.h>
12#include <sys/devpoll.h>
13#include <sys/types.h>
14#include <sys/stat.h>
15#include <fcntl.h>
16#endif
17
Thomas Wouters477c8d52006-05-27 19:21:47 +000018#ifdef __APPLE__
19 /* Perform runtime testing for a broken poll on OSX to make it easier
20 * to use the same binary on multiple releases of the OS.
21 */
22#undef HAVE_BROKEN_POLL
23#endif
24
Tim Petersd92dfe02000-12-12 01:18:41 +000025/* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined.
26 64 is too small (too many people have bumped into that limit).
27 Here we boost it.
28 Users who want even more than the boosted limit should #define
29 FD_SETSIZE higher before this; e.g., via compiler /D switch.
30*/
31#if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
32#define FD_SETSIZE 512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033#endif
Tim Petersd92dfe02000-12-12 01:18:41 +000034
Andrew M. Kuchling737fbb32001-07-14 20:54:37 +000035#if defined(HAVE_POLL_H)
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +000036#include <poll.h>
Andrew M. Kuchling737fbb32001-07-14 20:54:37 +000037#elif defined(HAVE_SYS_POLL_H)
38#include <sys/poll.h>
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +000039#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000040
Guido van Rossum37273171996-12-09 18:47:43 +000041#ifdef __sgi
42/* This is missing from unistd.h */
Thomas Woutersbd4bc4e2000-07-22 23:57:55 +000043extern void bzero(void *, int);
Guido van Rossum37273171996-12-09 18:47:43 +000044#endif
45
Thomas Wouters0e3f5912006-08-11 14:57:12 +000046#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000047#include <sys/types.h>
Guido van Rossumff7e83d1999-08-27 20:39:37 +000048#endif
Guido van Rossum4f0fbf81996-06-12 04:22:53 +000049
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000050#if defined(PYOS_OS2) && !defined(PYCC_GCC)
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000051#include <sys/time.h>
52#include <utils.h>
53#endif
54
Guido van Rossum6f489d91996-06-28 20:15:15 +000055#ifdef MS_WINDOWS
Christian Heimesc36625b2008-01-04 13:33:00 +000056# define WIN32_LEAN_AND_MEAN
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057# include <winsock.h>
Guido van Rossum4f0fbf81996-06-12 04:22:53 +000058#else
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059# define SOCKET int
Skip Montanaroeb33e5a2007-08-17 12:57:41 +000060# if defined(__VMS)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000061# include <socket.h>
62# endif
Guido van Rossumbcc20741998-08-04 22:53:56 +000063#endif
Guido van Rossumed233a51992-06-23 09:07:03 +000064
Barry Warsawc1cb3601996-12-12 22:16:21 +000065/* list of Python objects and their file descriptor */
66typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 PyObject *obj; /* owned reference */
68 SOCKET fd;
69 int sentinel; /* -1 == sentinel */
Guido van Rossum4f0fbf81996-06-12 04:22:53 +000070} pylist;
71
Barry Warsawc1cb3601996-12-12 22:16:21 +000072static void
Tim Peters4b046c22001-08-16 21:59:46 +000073reap_obj(pylist fd2obj[FD_SETSIZE + 1])
Barry Warsawc1cb3601996-12-12 22:16:21 +000074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 int i;
76 for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
77 Py_XDECREF(fd2obj[i].obj);
78 fd2obj[i].obj = NULL;
79 }
80 fd2obj[0].sentinel = -1;
Barry Warsawc1cb3601996-12-12 22:16:21 +000081}
82
83
Barry Warsawe4ac0aa1996-12-12 00:04:35 +000084/* returns -1 and sets the Python exception if an error occurred, otherwise
85 returns a number >= 0
86*/
Guido van Rossum4f0fbf81996-06-12 04:22:53 +000087static int
Brett Cannon62dba4c2003-09-10 19:37:42 +000088seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
Guido van Rossumed233a51992-06-23 09:07:03 +000089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 int max = -1;
91 int index = 0;
Victor Stinner0fcab4a2011-01-04 12:59:15 +000092 Py_ssize_t i, len = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 PyObject* fast_seq = NULL;
94 PyObject* o = NULL;
Guido van Rossum07432c01995-03-29 16:47:45 +000095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 fd2obj[0].obj = (PyObject*)0; /* set list to zero size */
97 FD_ZERO(set);
Barry Warsawc1cb3601996-12-12 22:16:21 +000098
Benjamin Petersone0edb8b2010-06-27 23:49:45 +000099 fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (!fast_seq)
101 return -1;
102
103 len = PySequence_Fast_GET_SIZE(fast_seq);
104
105 for (i = 0; i < len; i++) {
106 SOCKET v;
107
108 /* any intervening fileno() calls could decr this refcnt */
109 if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
Brett Cannon62dba4c2003-09-10 19:37:42 +0000110 return -1;
111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 Py_INCREF(o);
113 v = PyObject_AsFileDescriptor( o );
114 if (v == -1) goto finally;
Barry Warsawc1cb3601996-12-12 22:16:21 +0000115
Guido van Rossum947a0fa2000-01-14 16:33:09 +0000116#if defined(_MSC_VER)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 max = 0; /* not used for Win32 */
Barry Warsawc1cb3601996-12-12 22:16:21 +0000118#else /* !_MSC_VER */
Charles-François Nataliaa26b272011-08-28 17:51:43 +0200119 if (!_PyIsSelectable_fd(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyErr_SetString(PyExc_ValueError,
121 "filedescriptor out of range in select()");
122 goto finally;
123 }
124 if (v > max)
125 max = v;
Barry Warsawc1cb3601996-12-12 22:16:21 +0000126#endif /* _MSC_VER */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 FD_SET(v, set);
Barry Warsawc1cb3601996-12-12 22:16:21 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 /* add object and its file descriptor to the list */
130 if (index >= FD_SETSIZE) {
131 PyErr_SetString(PyExc_ValueError,
132 "too many file descriptors in select()");
133 goto finally;
134 }
135 fd2obj[index].obj = o;
136 fd2obj[index].fd = v;
137 fd2obj[index].sentinel = 0;
138 fd2obj[++index].sentinel = -1;
139 }
140 Py_DECREF(fast_seq);
141 return max+1;
Barry Warsawc1cb3601996-12-12 22:16:21 +0000142
143 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 Py_XDECREF(o);
145 Py_DECREF(fast_seq);
146 return -1;
Guido van Rossumed233a51992-06-23 09:07:03 +0000147}
148
Barry Warsawe4ac0aa1996-12-12 00:04:35 +0000149/* returns NULL and sets the Python exception if an error occurred */
150static PyObject *
Tim Peters4b046c22001-08-16 21:59:46 +0000151set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
Guido van Rossumed233a51992-06-23 09:07:03 +0000152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 int i, j, count=0;
154 PyObject *list, *o;
155 SOCKET fd;
Guido van Rossumed233a51992-06-23 09:07:03 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 for (j = 0; fd2obj[j].sentinel >= 0; j++) {
158 if (FD_ISSET(fd2obj[j].fd, set))
159 count++;
160 }
161 list = PyList_New(count);
162 if (!list)
163 return NULL;
Barry Warsawe4ac0aa1996-12-12 00:04:35 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 i = 0;
166 for (j = 0; fd2obj[j].sentinel >= 0; j++) {
167 fd = fd2obj[j].fd;
168 if (FD_ISSET(fd, set)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 o = fd2obj[j].obj;
170 fd2obj[j].obj = NULL;
171 /* transfer ownership */
172 if (PyList_SetItem(list, i, o) < 0)
173 goto finally;
Barry Warsawc1cb3601996-12-12 22:16:21 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 i++;
176 }
177 }
178 return list;
Barry Warsawc1cb3601996-12-12 22:16:21 +0000179 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 Py_DECREF(list);
181 return NULL;
Guido van Rossumed233a51992-06-23 09:07:03 +0000182}
Barry Warsawc1cb3601996-12-12 22:16:21 +0000183
Barry Warsawb44740f2001-08-16 16:52:59 +0000184#undef SELECT_USES_HEAP
185#if FD_SETSIZE > 1024
186#define SELECT_USES_HEAP
187#endif /* FD_SETSIZE > 1024 */
188
Barry Warsawe4ac0aa1996-12-12 00:04:35 +0000189static PyObject *
Peter Schneider-Kamp41c36ff2000-07-10 12:29:26 +0000190select_select(PyObject *self, PyObject *args)
Guido van Rossumed233a51992-06-23 09:07:03 +0000191{
Barry Warsawb44740f2001-08-16 16:52:59 +0000192#ifdef SELECT_USES_HEAP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 pylist *rfd2obj, *wfd2obj, *efd2obj;
Barry Warsawb44740f2001-08-16 16:52:59 +0000194#else /* !SELECT_USES_HEAP */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 /* XXX: All this should probably be implemented as follows:
196 * - find the highest descriptor we're interested in
197 * - add one
198 * - that's the size
199 * See: Stevens, APitUE, $12.5.1
200 */
201 pylist rfd2obj[FD_SETSIZE + 1];
202 pylist wfd2obj[FD_SETSIZE + 1];
203 pylist efd2obj[FD_SETSIZE + 1];
Barry Warsawb44740f2001-08-16 16:52:59 +0000204#endif /* SELECT_USES_HEAP */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 PyObject *ifdlist, *ofdlist, *efdlist;
206 PyObject *ret = NULL;
207 PyObject *tout = Py_None;
208 fd_set ifdset, ofdset, efdset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 struct timeval tv, *tvp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 int imax, omax, emax, max;
211 int n;
Guido van Rossumed233a51992-06-23 09:07:03 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* convert arguments */
214 if (!PyArg_UnpackTuple(args, "select", 3, 4,
215 &ifdlist, &ofdlist, &efdlist, &tout))
216 return NULL;
Guido van Rossumed233a51992-06-23 09:07:03 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (tout == Py_None)
219 tvp = (struct timeval *)0;
220 else if (!PyNumber_Check(tout)) {
221 PyErr_SetString(PyExc_TypeError,
222 "timeout must be a float or None");
223 return NULL;
224 }
225 else {
Victor Stinner5d272cc2012-03-13 13:35:55 +0100226 if (_PyTime_ObjectToTimeval(tout, &tv.tv_sec, &tv.tv_usec) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +0100228 if (tv.tv_sec < 0) {
229 PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 return NULL;
231 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 tvp = &tv;
233 }
Guido van Rossumed233a51992-06-23 09:07:03 +0000234
Guido van Rossumed233a51992-06-23 09:07:03 +0000235
Barry Warsawb44740f2001-08-16 16:52:59 +0000236#ifdef SELECT_USES_HEAP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 /* Allocate memory for the lists */
238 rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
239 wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
240 efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
241 if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
242 if (rfd2obj) PyMem_DEL(rfd2obj);
243 if (wfd2obj) PyMem_DEL(wfd2obj);
244 if (efd2obj) PyMem_DEL(efd2obj);
245 return PyErr_NoMemory();
246 }
Barry Warsawb44740f2001-08-16 16:52:59 +0000247#endif /* SELECT_USES_HEAP */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 /* Convert sequences to fd_sets, and get maximum fd number
249 * propagates the Python exception set in seq2set()
250 */
251 rfd2obj[0].sentinel = -1;
252 wfd2obj[0].sentinel = -1;
253 efd2obj[0].sentinel = -1;
254 if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
255 goto finally;
256 if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
257 goto finally;
258 if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
259 goto finally;
260 max = imax;
261 if (omax > max) max = omax;
262 if (emax > max) max = emax;
Guido van Rossumed233a51992-06-23 09:07:03 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 Py_BEGIN_ALLOW_THREADS
265 n = select(max, &ifdset, &ofdset, &efdset, tvp);
266 Py_END_ALLOW_THREADS
Guido van Rossumed233a51992-06-23 09:07:03 +0000267
Thomas Heller106f4c72002-09-24 16:51:00 +0000268#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (n == SOCKET_ERROR) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200270 PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 }
Thomas Heller106f4c72002-09-24 16:51:00 +0000272#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (n < 0) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200274 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 }
Thomas Heller106f4c72002-09-24 16:51:00 +0000276#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 else {
278 /* any of these three calls can raise an exception. it's more
279 convenient to test for this after all three calls... but
280 is that acceptable?
281 */
282 ifdlist = set2list(&ifdset, rfd2obj);
283 ofdlist = set2list(&ofdset, wfd2obj);
284 efdlist = set2list(&efdset, efd2obj);
285 if (PyErr_Occurred())
286 ret = NULL;
287 else
288 ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);
Barry Warsawe4ac0aa1996-12-12 00:04:35 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 Py_DECREF(ifdlist);
291 Py_DECREF(ofdlist);
292 Py_DECREF(efdlist);
293 }
294
Barry Warsawc1cb3601996-12-12 22:16:21 +0000295 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 reap_obj(rfd2obj);
297 reap_obj(wfd2obj);
298 reap_obj(efd2obj);
Barry Warsawb44740f2001-08-16 16:52:59 +0000299#ifdef SELECT_USES_HEAP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 PyMem_DEL(rfd2obj);
301 PyMem_DEL(wfd2obj);
302 PyMem_DEL(efd2obj);
Barry Warsawb44740f2001-08-16 16:52:59 +0000303#endif /* SELECT_USES_HEAP */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return ret;
Guido van Rossumed233a51992-06-23 09:07:03 +0000305}
306
Nicholas Bastine62c5c82004-03-21 23:45:42 +0000307#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308/*
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000309 * poll() support
310 */
311
312typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 PyObject_HEAD
314 PyObject *dict;
315 int ufd_uptodate;
316 int ufd_len;
317 struct pollfd *ufds;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000318} pollObject;
319
Jeremy Hylton938ace62002-07-17 16:30:39 +0000320static PyTypeObject poll_Type;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322/* Update the malloc'ed array of pollfds to match the dictionary
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000323 contained within a pollObject. Return 1 on success, 0 on an error.
324*/
325
326static int
327update_ufd_array(pollObject *self)
328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 Py_ssize_t i, pos;
330 PyObject *key, *value;
331 struct pollfd *old_ufds = self->ufds;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 self->ufd_len = PyDict_Size(self->dict);
334 PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
335 if (self->ufds == NULL) {
336 self->ufds = old_ufds;
337 PyErr_NoMemory();
338 return 0;
339 }
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 i = pos = 0;
342 while (PyDict_Next(self->dict, &pos, &key, &value)) {
343 self->ufds[i].fd = PyLong_AsLong(key);
344 self->ufds[i].events = (short)PyLong_AsLong(value);
345 i++;
346 }
347 self->ufd_uptodate = 1;
348 return 1;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000349}
350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000351PyDoc_STRVAR(poll_register_doc,
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000352"register(fd [, eventmask] ) -> None\n\n\
353Register a file descriptor with the polling object.\n\
Barry Warsaw2f704552001-08-16 16:55:10 +0000354fd -- either an integer, or an object with a fileno() method returning an\n\
355 int.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000356events -- an optional bitmask describing the type of events to check for");
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000357
358static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359poll_register(pollObject *self, PyObject *args)
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 PyObject *o, *key, *value;
362 int fd, events = POLLIN | POLLPRI | POLLOUT;
363 int err;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) {
366 return NULL;
367 }
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 fd = PyObject_AsFileDescriptor(o);
370 if (fd == -1) return NULL;
Guido van Rossuma0dfc852001-10-25 20:18:35 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 /* Add entry to the internal dictionary: the key is the
373 file descriptor, and the value is the event mask. */
374 key = PyLong_FromLong(fd);
375 if (key == NULL)
376 return NULL;
377 value = PyLong_FromLong(events);
378 if (value == NULL) {
379 Py_DECREF(key);
380 return NULL;
381 }
382 err = PyDict_SetItem(self->dict, key, value);
383 Py_DECREF(key);
384 Py_DECREF(value);
385 if (err < 0)
386 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 self->ufd_uptodate = 0;
389
390 Py_INCREF(Py_None);
391 return Py_None;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000392}
393
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000394PyDoc_STRVAR(poll_modify_doc,
395"modify(fd, eventmask) -> None\n\n\
Christian Heimesf6cd9672008-03-26 13:45:42 +0000396Modify an already registered file descriptor.\n\
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000397fd -- either an integer, or an object with a fileno() method returning an\n\
398 int.\n\
399events -- an optional bitmask describing the type of events to check for");
400
401static PyObject *
402poll_modify(pollObject *self, PyObject *args)
403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 PyObject *o, *key, *value;
405 int fd, events;
406 int err;
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) {
409 return NULL;
410 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 fd = PyObject_AsFileDescriptor(o);
413 if (fd == -1) return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 /* Modify registered fd */
416 key = PyLong_FromLong(fd);
417 if (key == NULL)
418 return NULL;
419 if (PyDict_GetItem(self->dict, key) == NULL) {
420 errno = ENOENT;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200421 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 return NULL;
423 }
424 value = PyLong_FromLong(events);
425 if (value == NULL) {
426 Py_DECREF(key);
427 return NULL;
428 }
429 err = PyDict_SetItem(self->dict, key, value);
430 Py_DECREF(key);
431 Py_DECREF(value);
432 if (err < 0)
433 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 self->ufd_uptodate = 0;
436
437 Py_INCREF(Py_None);
438 return Py_None;
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000439}
440
441
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000442PyDoc_STRVAR(poll_unregister_doc,
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000443"unregister(fd) -> None\n\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000444Remove a file descriptor being tracked by the polling object.");
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000445
446static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447poll_unregister(pollObject *self, PyObject *o)
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 PyObject *key;
450 int fd;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 fd = PyObject_AsFileDescriptor( o );
453 if (fd == -1)
454 return NULL;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 /* Check whether the fd is already in the array */
457 key = PyLong_FromLong(fd);
458 if (key == NULL)
459 return NULL;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (PyDict_DelItem(self->dict, key) == -1) {
462 Py_DECREF(key);
463 /* This will simply raise the KeyError set by PyDict_DelItem
464 if the file descriptor isn't registered. */
465 return NULL;
466 }
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 Py_DECREF(key);
469 self->ufd_uptodate = 0;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_INCREF(Py_None);
472 return Py_None;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000473}
474
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000475PyDoc_STRVAR(poll_poll_doc,
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000476"poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
477Polls the set of registered file descriptors, returning a list containing \n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000478any descriptors that have events or errors to report.");
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000479
480static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481poll_poll(pollObject *self, PyObject *args)
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 PyObject *result_list = NULL, *tout = NULL;
484 int timeout = 0, poll_result, i, j;
485 PyObject *value = NULL, *num = NULL;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {
488 return NULL;
489 }
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 /* Check values for timeout */
492 if (tout == NULL || tout == Py_None)
493 timeout = -1;
494 else if (!PyNumber_Check(tout)) {
495 PyErr_SetString(PyExc_TypeError,
496 "timeout must be an integer or None");
497 return NULL;
498 }
499 else {
500 tout = PyNumber_Long(tout);
501 if (!tout)
502 return NULL;
503 timeout = PyLong_AsLong(tout);
504 Py_DECREF(tout);
505 if (timeout == -1 && PyErr_Occurred())
506 return NULL;
507 }
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* Ensure the ufd array is up to date */
510 if (!self->ufd_uptodate)
511 if (update_ufd_array(self) == 0)
512 return NULL;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 /* call poll() */
515 Py_BEGIN_ALLOW_THREADS
516 poll_result = poll(self->ufds, self->ufd_len, timeout);
517 Py_END_ALLOW_THREADS
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (poll_result < 0) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200520 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return NULL;
522 }
523
524 /* build the result list */
525
526 result_list = PyList_New(poll_result);
527 if (!result_list)
528 return NULL;
529 else {
530 for (i = 0, j = 0; j < poll_result; j++) {
531 /* skip to the next fired descriptor */
532 while (!self->ufds[i].revents) {
533 i++;
534 }
535 /* if we hit a NULL return, set value to NULL
536 and break out of loop; code at end will
537 clean up result_list */
538 value = PyTuple_New(2);
539 if (value == NULL)
540 goto error;
541 num = PyLong_FromLong(self->ufds[i].fd);
542 if (num == NULL) {
543 Py_DECREF(value);
544 goto error;
545 }
546 PyTuple_SET_ITEM(value, 0, num);
547
548 /* The &0xffff is a workaround for AIX. 'revents'
549 is a 16-bit short, and IBM assigned POLLNVAL
550 to be 0x8000, so the conversion to int results
551 in a negative number. See SF bug #923315. */
552 num = PyLong_FromLong(self->ufds[i].revents & 0xffff);
553 if (num == NULL) {
554 Py_DECREF(value);
555 goto error;
556 }
557 PyTuple_SET_ITEM(value, 1, num);
558 if ((PyList_SetItem(result_list, j, value)) == -1) {
559 Py_DECREF(value);
560 goto error;
561 }
562 i++;
563 }
564 }
565 return result_list;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000566
567 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 Py_DECREF(result_list);
569 return NULL;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000570}
571
572static PyMethodDef poll_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 {"register", (PyCFunction)poll_register,
574 METH_VARARGS, poll_register_doc},
575 {"modify", (PyCFunction)poll_modify,
576 METH_VARARGS, poll_modify_doc},
577 {"unregister", (PyCFunction)poll_unregister,
578 METH_O, poll_unregister_doc},
579 {"poll", (PyCFunction)poll_poll,
580 METH_VARARGS, poll_poll_doc},
581 {NULL, NULL} /* sentinel */
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000582};
583
584static pollObject *
Fred Drake8ce159a2000-08-31 05:18:54 +0000585newPollObject(void)
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 pollObject *self;
588 self = PyObject_New(pollObject, &poll_Type);
589 if (self == NULL)
590 return NULL;
591 /* ufd_uptodate is a Boolean, denoting whether the
592 array pointed to by ufds matches the contents of the dictionary. */
593 self->ufd_uptodate = 0;
594 self->ufds = NULL;
595 self->dict = PyDict_New();
596 if (self->dict == NULL) {
597 Py_DECREF(self);
598 return NULL;
599 }
600 return self;
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000601}
602
603static void
604poll_dealloc(pollObject *self)
605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (self->ufds != NULL)
607 PyMem_DEL(self->ufds);
608 Py_XDECREF(self->dict);
609 PyObject_Del(self);
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000610}
611
Tim Peters0c322792002-07-17 16:49:03 +0000612static PyTypeObject poll_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* The ob_type field must be initialized in the module init function
614 * to be portable to Windows without using C++. */
615 PyVarObject_HEAD_INIT(NULL, 0)
616 "select.poll", /*tp_name*/
617 sizeof(pollObject), /*tp_basicsize*/
618 0, /*tp_itemsize*/
619 /* methods */
620 (destructor)poll_dealloc, /*tp_dealloc*/
621 0, /*tp_print*/
622 0, /*tp_getattr*/
623 0, /*tp_setattr*/
624 0, /*tp_reserved*/
625 0, /*tp_repr*/
626 0, /*tp_as_number*/
627 0, /*tp_as_sequence*/
628 0, /*tp_as_mapping*/
629 0, /*tp_hash*/
630 0, /*tp_call*/
631 0, /*tp_str*/
632 0, /*tp_getattro*/
633 0, /*tp_setattro*/
634 0, /*tp_as_buffer*/
635 Py_TPFLAGS_DEFAULT, /*tp_flags*/
636 0, /*tp_doc*/
637 0, /*tp_traverse*/
638 0, /*tp_clear*/
639 0, /*tp_richcompare*/
640 0, /*tp_weaklistoffset*/
641 0, /*tp_iter*/
642 0, /*tp_iternext*/
643 poll_methods, /*tp_methods*/
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000644};
645
Jesus Cead8b9ae62011-11-14 19:07:41 +0100646#ifdef HAVE_SYS_DEVPOLL_H
647typedef struct {
648 PyObject_HEAD
649 int fd_devpoll;
650 int max_n_fds;
651 int n_fds;
652 struct pollfd *fds;
653} devpollObject;
654
655static PyTypeObject devpoll_Type;
656
657static int devpoll_flush(devpollObject *self)
658{
659 int size, n;
660
661 if (!self->n_fds) return 0;
662
663 size = sizeof(struct pollfd)*self->n_fds;
664 self->n_fds = 0;
665
666 Py_BEGIN_ALLOW_THREADS
667 n = write(self->fd_devpoll, self->fds, size);
668 Py_END_ALLOW_THREADS
669
670 if (n == -1 ) {
671 PyErr_SetFromErrno(PyExc_IOError);
672 return -1;
673 }
674 if (n < size) {
675 /*
676 ** Data writed to /dev/poll is a binary data structure. It is not
677 ** clear what to do if a partial write occurred. For now, raise
678 ** an exception and see if we actually found this problem in
679 ** the wild.
680 ** See http://bugs.python.org/issue6397.
681 */
682 PyErr_Format(PyExc_IOError, "failed to write all pollfds. "
683 "Please, report at http://bugs.python.org/. "
684 "Data to report: Size tried: %d, actual size written: %d.",
685 size, n);
686 return -1;
687 }
688 return 0;
689}
690
691static PyObject *
692internal_devpoll_register(devpollObject *self, PyObject *args, int remove)
693{
694 PyObject *o;
695 int fd, events = POLLIN | POLLPRI | POLLOUT;
696
697 if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) {
698 return NULL;
699 }
700
701 fd = PyObject_AsFileDescriptor(o);
702 if (fd == -1) return NULL;
703
704 if (remove) {
705 self->fds[self->n_fds].fd = fd;
706 self->fds[self->n_fds].events = POLLREMOVE;
707
708 if (++self->n_fds == self->max_n_fds) {
709 if (devpoll_flush(self))
710 return NULL;
711 }
712 }
713
714 self->fds[self->n_fds].fd = fd;
715 self->fds[self->n_fds].events = events;
716
717 if (++self->n_fds == self->max_n_fds) {
718 if (devpoll_flush(self))
719 return NULL;
720 }
721
722 Py_RETURN_NONE;
723}
724
725PyDoc_STRVAR(devpoll_register_doc,
726"register(fd [, eventmask] ) -> None\n\n\
727Register a file descriptor with the polling object.\n\
728fd -- either an integer, or an object with a fileno() method returning an\n\
729 int.\n\
730events -- an optional bitmask describing the type of events to check for");
731
732static PyObject *
733devpoll_register(devpollObject *self, PyObject *args)
734{
735 return internal_devpoll_register(self, args, 0);
736}
737
738PyDoc_STRVAR(devpoll_modify_doc,
739"modify(fd[, eventmask]) -> None\n\n\
740Modify a possible already registered file descriptor.\n\
741fd -- either an integer, or an object with a fileno() method returning an\n\
742 int.\n\
743events -- an optional bitmask describing the type of events to check for");
744
745static PyObject *
746devpoll_modify(devpollObject *self, PyObject *args)
747{
748 return internal_devpoll_register(self, args, 1);
749}
750
751
752PyDoc_STRVAR(devpoll_unregister_doc,
753"unregister(fd) -> None\n\n\
754Remove a file descriptor being tracked by the polling object.");
755
756static PyObject *
757devpoll_unregister(devpollObject *self, PyObject *o)
758{
759 int fd;
760
761 fd = PyObject_AsFileDescriptor( o );
762 if (fd == -1)
763 return NULL;
764
765 self->fds[self->n_fds].fd = fd;
766 self->fds[self->n_fds].events = POLLREMOVE;
767
768 if (++self->n_fds == self->max_n_fds) {
769 if (devpoll_flush(self))
770 return NULL;
771 }
772
773 Py_RETURN_NONE;
774}
775
776PyDoc_STRVAR(devpoll_poll_doc,
777"poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
778Polls the set of registered file descriptors, returning a list containing \n\
779any descriptors that have events or errors to report.");
780
781static PyObject *
782devpoll_poll(devpollObject *self, PyObject *args)
783{
784 struct dvpoll dvp;
785 PyObject *result_list = NULL, *tout = NULL;
786 int poll_result, i;
787 long timeout;
788 PyObject *value, *num1, *num2;
789
790 if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {
791 return NULL;
792 }
793
794 /* Check values for timeout */
795 if (tout == NULL || tout == Py_None)
796 timeout = -1;
797 else if (!PyNumber_Check(tout)) {
798 PyErr_SetString(PyExc_TypeError,
799 "timeout must be an integer or None");
800 return NULL;
801 }
802 else {
803 tout = PyNumber_Long(tout);
804 if (!tout)
805 return NULL;
806 timeout = PyLong_AsLong(tout);
807 Py_DECREF(tout);
808 if (timeout == -1 && PyErr_Occurred())
809 return NULL;
810 }
811
812 if ((timeout < -1) || (timeout > INT_MAX)) {
813 PyErr_SetString(PyExc_OverflowError,
814 "timeout is out of range");
815 return NULL;
816 }
817
818 if (devpoll_flush(self))
819 return NULL;
820
821 dvp.dp_fds = self->fds;
822 dvp.dp_nfds = self->max_n_fds;
823 dvp.dp_timeout = timeout;
824
825 /* call devpoll() */
826 Py_BEGIN_ALLOW_THREADS
827 poll_result = ioctl(self->fd_devpoll, DP_POLL, &dvp);
828 Py_END_ALLOW_THREADS
829
830 if (poll_result < 0) {
831 PyErr_SetFromErrno(PyExc_IOError);
832 return NULL;
833 }
834
835 /* build the result list */
836
837 result_list = PyList_New(poll_result);
838 if (!result_list)
839 return NULL;
840 else {
841 for (i = 0; i < poll_result; i++) {
842 num1 = PyLong_FromLong(self->fds[i].fd);
843 num2 = PyLong_FromLong(self->fds[i].revents);
844 if ((num1 == NULL) || (num2 == NULL)) {
845 Py_XDECREF(num1);
846 Py_XDECREF(num2);
847 goto error;
848 }
849 value = PyTuple_Pack(2, num1, num2);
850 Py_DECREF(num1);
851 Py_DECREF(num2);
852 if (value == NULL)
853 goto error;
854 if ((PyList_SetItem(result_list, i, value)) == -1) {
855 Py_DECREF(value);
856 goto error;
857 }
858 }
859 }
860
861 return result_list;
862
863 error:
864 Py_DECREF(result_list);
865 return NULL;
866}
867
868static PyMethodDef devpoll_methods[] = {
869 {"register", (PyCFunction)devpoll_register,
870 METH_VARARGS, devpoll_register_doc},
871 {"modify", (PyCFunction)devpoll_modify,
872 METH_VARARGS, devpoll_modify_doc},
873 {"unregister", (PyCFunction)devpoll_unregister,
874 METH_O, devpoll_unregister_doc},
875 {"poll", (PyCFunction)devpoll_poll,
876 METH_VARARGS, devpoll_poll_doc},
877 {NULL, NULL} /* sentinel */
878};
879
880static devpollObject *
881newDevPollObject(void)
882{
883 devpollObject *self;
884 int fd_devpoll, limit_result;
885 struct pollfd *fds;
886 struct rlimit limit;
887
888 Py_BEGIN_ALLOW_THREADS
889 /*
890 ** If we try to process more that getrlimit()
891 ** fds, the kernel will give an error, so
892 ** we set the limit here. It is a dynamic
893 ** value, because we can change rlimit() anytime.
894 */
895 limit_result = getrlimit(RLIMIT_NOFILE, &limit);
896 if (limit_result != -1)
897 fd_devpoll = open("/dev/poll", O_RDWR);
898 Py_END_ALLOW_THREADS
899
900 if (limit_result == -1) {
901 PyErr_SetFromErrno(PyExc_OSError);
902 return NULL;
903 }
904 if (fd_devpoll == -1) {
905 PyErr_SetFromErrnoWithFilename(PyExc_IOError, "/dev/poll");
906 return NULL;
907 }
908
909 fds = PyMem_NEW(struct pollfd, limit.rlim_cur);
910 if (fds == NULL) {
911 close(fd_devpoll);
912 PyErr_NoMemory();
913 return NULL;
914 }
915
916 self = PyObject_New(devpollObject, &devpoll_Type);
917 if (self == NULL) {
918 close(fd_devpoll);
919 PyMem_DEL(fds);
920 return NULL;
921 }
922 self->fd_devpoll = fd_devpoll;
923 self->max_n_fds = limit.rlim_cur;
924 self->n_fds = 0;
925 self->fds = fds;
926
927 return self;
928}
929
930static void
931devpoll_dealloc(devpollObject *self)
932{
933 Py_BEGIN_ALLOW_THREADS
934 close(self->fd_devpoll);
935 Py_END_ALLOW_THREADS
936
937 PyMem_DEL(self->fds);
938
939 PyObject_Del(self);
940}
941
942static PyTypeObject devpoll_Type = {
943 /* The ob_type field must be initialized in the module init function
944 * to be portable to Windows without using C++. */
945 PyVarObject_HEAD_INIT(NULL, 0)
946 "select.devpoll", /*tp_name*/
947 sizeof(devpollObject), /*tp_basicsize*/
948 0, /*tp_itemsize*/
949 /* methods */
950 (destructor)devpoll_dealloc, /*tp_dealloc*/
951 0, /*tp_print*/
952 0, /*tp_getattr*/
953 0, /*tp_setattr*/
954 0, /*tp_reserved*/
955 0, /*tp_repr*/
956 0, /*tp_as_number*/
957 0, /*tp_as_sequence*/
958 0, /*tp_as_mapping*/
959 0, /*tp_hash*/
960 0, /*tp_call*/
961 0, /*tp_str*/
962 0, /*tp_getattro*/
963 0, /*tp_setattro*/
964 0, /*tp_as_buffer*/
965 Py_TPFLAGS_DEFAULT, /*tp_flags*/
966 0, /*tp_doc*/
967 0, /*tp_traverse*/
968 0, /*tp_clear*/
969 0, /*tp_richcompare*/
970 0, /*tp_weaklistoffset*/
971 0, /*tp_iter*/
972 0, /*tp_iternext*/
973 devpoll_methods, /*tp_methods*/
974};
975#endif /* HAVE_SYS_DEVPOLL_H */
976
977
978
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000979PyDoc_STRVAR(poll_doc,
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000980"Returns a polling object, which supports registering and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000981unregistering file descriptors, and then polling them for I/O events.");
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000982
983static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000984select_poll(PyObject *self, PyObject *unused)
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 return (PyObject *)newPollObject();
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +0000987}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000988
Jesus Cead8b9ae62011-11-14 19:07:41 +0100989#ifdef HAVE_SYS_DEVPOLL_H
990PyDoc_STRVAR(devpoll_doc,
991"Returns a polling object, which supports registering and\n\
992unregistering file descriptors, and then polling them for I/O events.");
993
994static PyObject *
995select_devpoll(PyObject *self, PyObject *unused)
996{
997 return (PyObject *)newDevPollObject();
998}
999#endif
1000
1001
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002#ifdef __APPLE__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003/*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001004 * On some systems poll() sets errno on invalid file descriptors. We test
1005 * for this at runtime because this bug may be fixed or introduced between
1006 * OS releases.
1007 */
1008static int select_have_broken_poll(void)
1009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 int poll_test;
1011 int filedes[2];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };
Thomas Wouters477c8d52006-05-27 19:21:47 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 /* Create a file descriptor to make invalid */
1016 if (pipe(filedes) < 0) {
1017 return 1;
1018 }
1019 poll_struct.fd = filedes[0];
1020 close(filedes[0]);
1021 close(filedes[1]);
1022 poll_test = poll(&poll_struct, 1, 0);
1023 if (poll_test < 0) {
1024 return 1;
1025 } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
1026 return 1;
1027 }
1028 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001029}
1030#endif /* __APPLE__ */
1031
1032#endif /* HAVE_POLL */
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +00001033
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001034#ifdef HAVE_EPOLL
1035/* **************************************************************************
1036 * epoll interface for Linux 2.6
1037 *
1038 * Written by Christian Heimes
1039 * Inspired by Twisted's _epoll.pyx and select.poll()
1040 */
1041
1042#ifdef HAVE_SYS_EPOLL_H
1043#include <sys/epoll.h>
1044#endif
1045
1046typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyObject_HEAD
1048 SOCKET epfd; /* epoll control file descriptor */
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001049} pyEpoll_Object;
1050
1051static PyTypeObject pyEpoll_Type;
1052#define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type))
1053
1054static PyObject *
1055pyepoll_err_closed(void)
1056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd");
1058 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001059}
1060
1061static int
1062pyepoll_internal_close(pyEpoll_Object *self)
1063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 int save_errno = 0;
1065 if (self->epfd >= 0) {
1066 int epfd = self->epfd;
1067 self->epfd = -1;
1068 Py_BEGIN_ALLOW_THREADS
1069 if (close(epfd) < 0)
1070 save_errno = errno;
1071 Py_END_ALLOW_THREADS
1072 }
1073 return save_errno;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001074}
1075
1076static PyObject *
Benjamin Peterson95c16622011-12-27 15:36:32 -06001077newPyEpoll_Object(PyTypeObject *type, int sizehint, int flags, SOCKET fd)
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 pyEpoll_Object *self;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 assert(type != NULL && type->tp_alloc != NULL);
1082 self = (pyEpoll_Object *) type->tp_alloc(type, 0);
1083 if (self == NULL)
1084 return NULL;
1085
1086 if (fd == -1) {
1087 Py_BEGIN_ALLOW_THREADS
Benjamin Peterson95c16622011-12-27 15:36:32 -06001088#ifdef HAVE_EPOLL_CREATE1
Benjamin Peterson83251c12011-12-27 16:01:21 -06001089 if (flags)
1090 self->epfd = epoll_create1(flags);
1091 else
Benjamin Peterson95c16622011-12-27 15:36:32 -06001092#endif
Benjamin Peterson83251c12011-12-27 16:01:21 -06001093 self->epfd = epoll_create(sizehint);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 Py_END_ALLOW_THREADS
1095 }
1096 else {
1097 self->epfd = fd;
1098 }
1099 if (self->epfd < 0) {
1100 Py_DECREF(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001101 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 return NULL;
1103 }
1104 return (PyObject *)self;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001105}
1106
1107
1108static PyObject *
1109pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1110{
Benjamin Peterson83251c12011-12-27 16:01:21 -06001111 int flags = 0, sizehint = FD_SETSIZE - 1;
Benjamin Peterson2fb9ae92011-12-27 15:15:41 -06001112 static char *kwlist[] = {"sizehint", "flags", NULL};
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001113
Benjamin Peterson2fb9ae92011-12-27 15:15:41 -06001114 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:epoll", kwlist,
1115 &sizehint, &flags))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 return NULL;
Benjamin Peterson2fb9ae92011-12-27 15:15:41 -06001117 if (sizehint < 0) {
1118 PyErr_SetString(PyExc_ValueError, "negative sizehint");
1119 return NULL;
1120 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001121
Benjamin Peterson95c16622011-12-27 15:36:32 -06001122 return newPyEpoll_Object(type, sizehint, flags, -1);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001123}
1124
1125
1126static void
1127pyepoll_dealloc(pyEpoll_Object *self)
1128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 (void)pyepoll_internal_close(self);
1130 Py_TYPE(self)->tp_free(self);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001131}
1132
1133static PyObject*
1134pyepoll_close(pyEpoll_Object *self)
1135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 errno = pyepoll_internal_close(self);
1137 if (errno < 0) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001138 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 return NULL;
1140 }
1141 Py_RETURN_NONE;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001142}
1143
1144PyDoc_STRVAR(pyepoll_close_doc,
1145"close() -> None\n\
1146\n\
1147Close the epoll control file descriptor. Further operations on the epoll\n\
1148object will raise an exception.");
1149
1150static PyObject*
1151pyepoll_get_closed(pyEpoll_Object *self)
1152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (self->epfd < 0)
1154 Py_RETURN_TRUE;
1155 else
1156 Py_RETURN_FALSE;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001157}
1158
1159static PyObject*
1160pyepoll_fileno(pyEpoll_Object *self)
1161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (self->epfd < 0)
1163 return pyepoll_err_closed();
1164 return PyLong_FromLong(self->epfd);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001165}
1166
1167PyDoc_STRVAR(pyepoll_fileno_doc,
1168"fileno() -> int\n\
1169\n\
1170Return the epoll control file descriptor.");
1171
1172static PyObject*
1173pyepoll_fromfd(PyObject *cls, PyObject *args)
1174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 SOCKET fd;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
1178 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001179
Benjamin Peterson95c16622011-12-27 15:36:32 -06001180 return newPyEpoll_Object((PyTypeObject*)cls, FD_SETSIZE - 1, 0, fd);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001181}
1182
1183PyDoc_STRVAR(pyepoll_fromfd_doc,
1184"fromfd(fd) -> epoll\n\
1185\n\
1186Create an epoll object from a given control fd.");
1187
1188static PyObject *
1189pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events)
1190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 struct epoll_event ev;
1192 int result;
1193 int fd;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (epfd < 0)
1196 return pyepoll_err_closed();
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 fd = PyObject_AsFileDescriptor(pfd);
1199 if (fd == -1) {
1200 return NULL;
1201 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 switch(op) {
1204 case EPOLL_CTL_ADD:
1205 case EPOLL_CTL_MOD:
1206 ev.events = events;
1207 ev.data.fd = fd;
1208 Py_BEGIN_ALLOW_THREADS
1209 result = epoll_ctl(epfd, op, fd, &ev);
1210 Py_END_ALLOW_THREADS
1211 break;
1212 case EPOLL_CTL_DEL:
1213 /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
1214 * operation required a non-NULL pointer in event, even
1215 * though this argument is ignored. */
1216 Py_BEGIN_ALLOW_THREADS
1217 result = epoll_ctl(epfd, op, fd, &ev);
1218 if (errno == EBADF) {
1219 /* fd already closed */
1220 result = 0;
1221 errno = 0;
1222 }
1223 Py_END_ALLOW_THREADS
1224 break;
1225 default:
1226 result = -1;
1227 errno = EINVAL;
1228 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (result < 0) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001231 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 return NULL;
1233 }
1234 Py_RETURN_NONE;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001235}
1236
1237static PyObject *
1238pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
1239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 PyObject *pfd;
1241 unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;
1242 static char *kwlist[] = {"fd", "eventmask", NULL};
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
1245 &pfd, &events)) {
1246 return NULL;
1247 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001250}
1251
1252PyDoc_STRVAR(pyepoll_register_doc,
Georg Brandl222569d2010-08-02 20:47:56 +00001253"register(fd[, eventmask]) -> None\n\
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001254\n\
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001255Registers a new fd or raises an OSError if the fd is already registered.\n\
Christian Heimesf6cd9672008-03-26 13:45:42 +00001256fd is the target file descriptor of the operation.\n\
1257events is a bit set composed of the various EPOLL constants; the default\n\
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001258is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\
1259\n\
1260The epoll interface supports all file descriptors that support poll.");
1261
1262static PyObject *
1263pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
1264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyObject *pfd;
1266 unsigned int events;
1267 static char *kwlist[] = {"fd", "eventmask", NULL};
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
1270 &pfd, &events)) {
1271 return NULL;
1272 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001275}
1276
1277PyDoc_STRVAR(pyepoll_modify_doc,
1278"modify(fd, eventmask) -> None\n\
1279\n\
1280fd is the target file descriptor of the operation\n\
1281events is a bit set composed of the various EPOLL constants");
1282
1283static PyObject *
1284pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
1285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 PyObject *pfd;
1287 static char *kwlist[] = {"fd", NULL};
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
1290 &pfd)) {
1291 return NULL;
1292 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001295}
1296
1297PyDoc_STRVAR(pyepoll_unregister_doc,
1298"unregister(fd) -> None\n\
1299\n\
1300fd is the target file descriptor of the operation.");
1301
1302static PyObject *
1303pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
1304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 double dtimeout = -1.;
1306 int timeout;
1307 int maxevents = -1;
1308 int nfds, i;
1309 PyObject *elist = NULL, *etuple = NULL;
1310 struct epoll_event *evs = NULL;
1311 static char *kwlist[] = {"timeout", "maxevents", NULL};
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (self->epfd < 0)
1314 return pyepoll_err_closed();
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist,
1317 &dtimeout, &maxevents)) {
1318 return NULL;
1319 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (dtimeout < 0) {
1322 timeout = -1;
1323 }
1324 else if (dtimeout * 1000.0 > INT_MAX) {
1325 PyErr_SetString(PyExc_OverflowError,
1326 "timeout is too large");
1327 return NULL;
1328 }
1329 else {
1330 timeout = (int)(dtimeout * 1000.0);
1331 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (maxevents == -1) {
1334 maxevents = FD_SETSIZE-1;
1335 }
1336 else if (maxevents < 1) {
1337 PyErr_Format(PyExc_ValueError,
1338 "maxevents must be greater than 0, got %d",
1339 maxevents);
1340 return NULL;
1341 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 evs = PyMem_New(struct epoll_event, maxevents);
1344 if (evs == NULL) {
1345 Py_DECREF(self);
1346 PyErr_NoMemory();
1347 return NULL;
1348 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 Py_BEGIN_ALLOW_THREADS
1351 nfds = epoll_wait(self->epfd, evs, maxevents, timeout);
1352 Py_END_ALLOW_THREADS
1353 if (nfds < 0) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001354 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 goto error;
1356 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 elist = PyList_New(nfds);
1359 if (elist == NULL) {
1360 goto error;
1361 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 for (i = 0; i < nfds; i++) {
1364 etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
1365 if (etuple == NULL) {
1366 Py_CLEAR(elist);
1367 goto error;
1368 }
1369 PyList_SET_ITEM(elist, i, etuple);
1370 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001371
Christian Heimesf6cd9672008-03-26 13:45:42 +00001372 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyMem_Free(evs);
1374 return elist;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001375}
1376
1377PyDoc_STRVAR(pyepoll_poll_doc,
1378"poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\
1379\n\
1380Wait for events on the epoll file descriptor for a maximum time of timeout\n\
1381in seconds (as float). -1 makes poll wait indefinitely.\n\
1382Up to maxevents are returned to the caller.");
1383
1384static PyMethodDef pyepoll_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 {"fromfd", (PyCFunction)pyepoll_fromfd,
1386 METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},
1387 {"close", (PyCFunction)pyepoll_close, METH_NOARGS,
1388 pyepoll_close_doc},
1389 {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS,
1390 pyepoll_fileno_doc},
1391 {"modify", (PyCFunction)pyepoll_modify,
1392 METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc},
1393 {"register", (PyCFunction)pyepoll_register,
1394 METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc},
1395 {"unregister", (PyCFunction)pyepoll_unregister,
1396 METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc},
1397 {"poll", (PyCFunction)pyepoll_poll,
1398 METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc},
1399 {NULL, NULL},
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001400};
1401
1402static PyGetSetDef pyepoll_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 {"closed", (getter)pyepoll_get_closed, NULL,
1404 "True if the epoll handler is closed"},
1405 {0},
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001406};
1407
1408PyDoc_STRVAR(pyepoll_doc,
Benjamin Peterson2fb9ae92011-12-27 15:15:41 -06001409"select.epoll(sizehint=-1, flags=0)\n\
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001410\n\
1411Returns an epolling object\n\
1412\n\
1413sizehint must be a positive integer or -1 for the default size. The\n\
1414sizehint is used to optimize internal data structures. It doesn't limit\n\
1415the maximum number of monitored events.");
1416
1417static PyTypeObject pyEpoll_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 PyVarObject_HEAD_INIT(NULL, 0)
1419 "select.epoll", /* tp_name */
1420 sizeof(pyEpoll_Object), /* tp_basicsize */
1421 0, /* tp_itemsize */
1422 (destructor)pyepoll_dealloc, /* tp_dealloc */
1423 0, /* tp_print */
1424 0, /* tp_getattr */
1425 0, /* tp_setattr */
1426 0, /* tp_reserved */
1427 0, /* tp_repr */
1428 0, /* tp_as_number */
1429 0, /* tp_as_sequence */
1430 0, /* tp_as_mapping */
1431 0, /* tp_hash */
1432 0, /* tp_call */
1433 0, /* tp_str */
1434 PyObject_GenericGetAttr, /* tp_getattro */
1435 0, /* tp_setattro */
1436 0, /* tp_as_buffer */
1437 Py_TPFLAGS_DEFAULT, /* tp_flags */
1438 pyepoll_doc, /* tp_doc */
1439 0, /* tp_traverse */
1440 0, /* tp_clear */
1441 0, /* tp_richcompare */
1442 0, /* tp_weaklistoffset */
1443 0, /* tp_iter */
1444 0, /* tp_iternext */
1445 pyepoll_methods, /* tp_methods */
1446 0, /* tp_members */
1447 pyepoll_getsetlist, /* tp_getset */
1448 0, /* tp_base */
1449 0, /* tp_dict */
1450 0, /* tp_descr_get */
1451 0, /* tp_descr_set */
1452 0, /* tp_dictoffset */
1453 0, /* tp_init */
1454 0, /* tp_alloc */
1455 pyepoll_new, /* tp_new */
1456 0, /* tp_free */
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001457};
1458
1459#endif /* HAVE_EPOLL */
1460
1461#ifdef HAVE_KQUEUE
1462/* **************************************************************************
1463 * kqueue interface for BSD
1464 *
1465 * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
1466 * All rights reserved.
1467 *
1468 * Redistribution and use in source and binary forms, with or without
1469 * modification, are permitted provided that the following conditions
1470 * are met:
1471 * 1. Redistributions of source code must retain the above copyright
1472 * notice, this list of conditions and the following disclaimer.
1473 * 2. Redistributions in binary form must reproduce the above copyright
1474 * notice, this list of conditions and the following disclaimer in the
1475 * documentation and/or other materials provided with the distribution.
1476 *
1477 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1478 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1479 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1480 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1481 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1482 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1483 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1484 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1485 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1486 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1487 * SUCH DAMAGE.
1488 */
1489
1490#ifdef HAVE_SYS_EVENT_H
1491#include <sys/event.h>
1492#endif
1493
1494PyDoc_STRVAR(kqueue_event_doc,
Benjamin Peterson1baf4652009-12-31 03:11:23 +00001495"kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001496\n\
1497This object is the equivalent of the struct kevent for the C API.\n\
1498\n\
1499See the kqueue manpage for more detailed information about the meaning\n\
1500of the arguments.\n\
1501\n\
1502One minor note: while you might hope that udata could store a\n\
1503reference to a python object, it cannot, because it is impossible to\n\
1504keep a proper reference count of the object once it's passed into the\n\
1505kernel. Therefore, I have restricted it to only storing an integer. I\n\
1506recommend ignoring it and simply using the 'ident' field to key off\n\
1507of. You could also set up a dictionary on the python side to store a\n\
1508udata->object mapping.");
1509
1510typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 PyObject_HEAD
1512 struct kevent e;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001513} kqueue_event_Object;
1514
1515static PyTypeObject kqueue_event_Type;
1516
1517#define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type))
1518
1519typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 PyObject_HEAD
1521 SOCKET kqfd; /* kqueue control fd */
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001522} kqueue_queue_Object;
1523
1524static PyTypeObject kqueue_queue_Type;
1525
1526#define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type))
1527
Antoine Pitroud83f1e62009-11-04 21:10:38 +00001528#if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P)
1529# error uintptr_t does not match void *!
1530#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG)
1531# define T_UINTPTRT T_ULONGLONG
1532# define T_INTPTRT T_LONGLONG
1533# define PyLong_AsUintptr_t PyLong_AsUnsignedLongLong
1534# define UINTPTRT_FMT_UNIT "K"
1535# define INTPTRT_FMT_UNIT "L"
1536#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG)
1537# define T_UINTPTRT T_ULONG
1538# define T_INTPTRT T_LONG
1539# define PyLong_AsUintptr_t PyLong_AsUnsignedLong
1540# define UINTPTRT_FMT_UNIT "k"
1541# define INTPTRT_FMT_UNIT "l"
1542#elif (SIZEOF_UINTPTR_T == SIZEOF_INT)
1543# define T_UINTPTRT T_UINT
1544# define T_INTPTRT T_INT
1545# define PyLong_AsUintptr_t PyLong_AsUnsignedLong
1546# define UINTPTRT_FMT_UNIT "I"
1547# define INTPTRT_FMT_UNIT "i"
1548#else
1549# error uintptr_t does not match int, long, or long long!
1550#endif
1551
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001552/* Unfortunately, we can't store python objects in udata, because
1553 * kevents in the kernel can be removed without warning, which would
1554 * forever lose the refcount on the object stored with it.
1555 */
1556
1557#define KQ_OFF(x) offsetof(kqueue_event_Object, x)
1558static struct PyMemberDef kqueue_event_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 {"ident", T_UINTPTRT, KQ_OFF(e.ident)},
1560 {"filter", T_SHORT, KQ_OFF(e.filter)},
1561 {"flags", T_USHORT, KQ_OFF(e.flags)},
1562 {"fflags", T_UINT, KQ_OFF(e.fflags)},
1563 {"data", T_INTPTRT, KQ_OFF(e.data)},
1564 {"udata", T_UINTPTRT, KQ_OFF(e.udata)},
1565 {NULL} /* Sentinel */
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001566};
1567#undef KQ_OFF
1568
1569static PyObject *
Georg Brandlc0e22b72010-03-14 10:51:01 +00001570
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001571kqueue_event_repr(kqueue_event_Object *s)
1572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 char buf[1024];
1574 PyOS_snprintf(
1575 buf, sizeof(buf),
1576 "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
1577 "data=0x%zd udata=%p>",
1578 (size_t)(s->e.ident), s->e.filter, s->e.flags,
1579 s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata);
1580 return PyUnicode_FromString(buf);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001581}
1582
1583static int
1584kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds)
1585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 PyObject *pfd;
1587 static char *kwlist[] = {"ident", "filter", "flags", "fflags",
1588 "data", "udata", NULL};
1589 static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent";
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1594 &pfd, &(self->e.filter), &(self->e.flags),
1595 &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
1596 return -1;
1597 }
1598
1599 if (PyLong_Check(pfd)) {
1600 self->e.ident = PyLong_AsUintptr_t(pfd);
1601 }
1602 else {
1603 self->e.ident = PyObject_AsFileDescriptor(pfd);
1604 }
1605 if (PyErr_Occurred()) {
1606 return -1;
1607 }
1608 return 0;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001609}
1610
1611static PyObject *
1612kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 int op)
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 Py_intptr_t result = 0;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 if (!kqueue_event_Check(o)) {
1618 if (op == Py_EQ || op == Py_NE) {
1619 PyObject *res = op == Py_EQ ? Py_False : Py_True;
1620 Py_INCREF(res);
1621 return res;
1622 }
1623 PyErr_Format(PyExc_TypeError,
1624 "can't compare %.200s to %.200s",
1625 Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name);
1626 return NULL;
1627 }
1628 if (((result = s->e.ident - o->e.ident) == 0) &&
1629 ((result = s->e.filter - o->e.filter) == 0) &&
1630 ((result = s->e.flags - o->e.flags) == 0) &&
1631 ((result = s->e.fflags - o->e.fflags) == 0) &&
1632 ((result = s->e.data - o->e.data) == 0) &&
1633 ((result = s->e.udata - o->e.udata) == 0)
1634 ) {
1635 result = 0;
1636 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 switch (op) {
1639 case Py_EQ:
1640 result = (result == 0);
1641 break;
1642 case Py_NE:
1643 result = (result != 0);
1644 break;
1645 case Py_LE:
1646 result = (result <= 0);
1647 break;
1648 case Py_GE:
1649 result = (result >= 0);
1650 break;
1651 case Py_LT:
1652 result = (result < 0);
1653 break;
1654 case Py_GT:
1655 result = (result > 0);
1656 break;
1657 }
1658 return PyBool_FromLong((long)result);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001659}
1660
1661static PyTypeObject kqueue_event_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 PyVarObject_HEAD_INIT(NULL, 0)
1663 "select.kevent", /* tp_name */
1664 sizeof(kqueue_event_Object), /* tp_basicsize */
1665 0, /* tp_itemsize */
1666 0, /* tp_dealloc */
1667 0, /* tp_print */
1668 0, /* tp_getattr */
1669 0, /* tp_setattr */
1670 0, /* tp_reserved */
1671 (reprfunc)kqueue_event_repr, /* tp_repr */
1672 0, /* tp_as_number */
1673 0, /* tp_as_sequence */
1674 0, /* tp_as_mapping */
1675 0, /* tp_hash */
1676 0, /* tp_call */
1677 0, /* tp_str */
1678 0, /* tp_getattro */
1679 0, /* tp_setattro */
1680 0, /* tp_as_buffer */
1681 Py_TPFLAGS_DEFAULT, /* tp_flags */
1682 kqueue_event_doc, /* tp_doc */
1683 0, /* tp_traverse */
1684 0, /* tp_clear */
1685 (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */
1686 0, /* tp_weaklistoffset */
1687 0, /* tp_iter */
1688 0, /* tp_iternext */
1689 0, /* tp_methods */
1690 kqueue_event_members, /* tp_members */
1691 0, /* tp_getset */
1692 0, /* tp_base */
1693 0, /* tp_dict */
1694 0, /* tp_descr_get */
1695 0, /* tp_descr_set */
1696 0, /* tp_dictoffset */
1697 (initproc)kqueue_event_init, /* tp_init */
1698 0, /* tp_alloc */
1699 0, /* tp_new */
1700 0, /* tp_free */
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001701};
1702
1703static PyObject *
1704kqueue_queue_err_closed(void)
1705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd");
1707 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001708}
1709
1710static int
1711kqueue_queue_internal_close(kqueue_queue_Object *self)
1712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 int save_errno = 0;
1714 if (self->kqfd >= 0) {
1715 int kqfd = self->kqfd;
1716 self->kqfd = -1;
1717 Py_BEGIN_ALLOW_THREADS
1718 if (close(kqfd) < 0)
1719 save_errno = errno;
1720 Py_END_ALLOW_THREADS
1721 }
1722 return save_errno;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001723}
1724
1725static PyObject *
1726newKqueue_Object(PyTypeObject *type, SOCKET fd)
1727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 kqueue_queue_Object *self;
1729 assert(type != NULL && type->tp_alloc != NULL);
1730 self = (kqueue_queue_Object *) type->tp_alloc(type, 0);
1731 if (self == NULL) {
1732 return NULL;
1733 }
1734
1735 if (fd == -1) {
1736 Py_BEGIN_ALLOW_THREADS
1737 self->kqfd = kqueue();
1738 Py_END_ALLOW_THREADS
1739 }
1740 else {
1741 self->kqfd = fd;
1742 }
1743 if (self->kqfd < 0) {
1744 Py_DECREF(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001745 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 return NULL;
1747 }
1748 return (PyObject *)self;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001749}
1750
1751static PyObject *
1752kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1753{
1754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 if ((args != NULL && PyObject_Size(args)) ||
1756 (kwds != NULL && PyObject_Size(kwds))) {
1757 PyErr_SetString(PyExc_ValueError,
1758 "select.kqueue doesn't accept arguments");
1759 return NULL;
1760 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 return newKqueue_Object(type, -1);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001763}
1764
1765static void
1766kqueue_queue_dealloc(kqueue_queue_Object *self)
1767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 kqueue_queue_internal_close(self);
1769 Py_TYPE(self)->tp_free(self);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001770}
1771
1772static PyObject*
1773kqueue_queue_close(kqueue_queue_Object *self)
1774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 errno = kqueue_queue_internal_close(self);
1776 if (errno < 0) {
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001777 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 return NULL;
1779 }
1780 Py_RETURN_NONE;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001781}
1782
1783PyDoc_STRVAR(kqueue_queue_close_doc,
1784"close() -> None\n\
1785\n\
1786Close the kqueue control file descriptor. Further operations on the kqueue\n\
1787object will raise an exception.");
1788
1789static PyObject*
1790kqueue_queue_get_closed(kqueue_queue_Object *self)
1791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 if (self->kqfd < 0)
1793 Py_RETURN_TRUE;
1794 else
1795 Py_RETURN_FALSE;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001796}
1797
1798static PyObject*
1799kqueue_queue_fileno(kqueue_queue_Object *self)
1800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (self->kqfd < 0)
1802 return kqueue_queue_err_closed();
1803 return PyLong_FromLong(self->kqfd);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001804}
1805
1806PyDoc_STRVAR(kqueue_queue_fileno_doc,
1807"fileno() -> int\n\
1808\n\
1809Return the kqueue control file descriptor.");
1810
1811static PyObject*
1812kqueue_queue_fromfd(PyObject *cls, PyObject *args)
1813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 SOCKET fd;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
1817 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 return newKqueue_Object((PyTypeObject*)cls, fd);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001820}
1821
1822PyDoc_STRVAR(kqueue_queue_fromfd_doc,
1823"fromfd(fd) -> kqueue\n\
1824\n\
1825Create a kqueue object from a given control fd.");
1826
1827static PyObject *
1828kqueue_queue_control(kqueue_queue_Object *self, PyObject *args)
1829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 int nevents = 0;
1831 int gotevents = 0;
1832 int nchanges = 0;
1833 int i = 0;
1834 PyObject *otimeout = NULL;
1835 PyObject *ch = NULL;
1836 PyObject *it = NULL, *ei = NULL;
1837 PyObject *result = NULL;
1838 struct kevent *evl = NULL;
1839 struct kevent *chl = NULL;
1840 struct timespec timeoutspec;
1841 struct timespec *ptimeoutspec;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (self->kqfd < 0)
1844 return kqueue_queue_err_closed();
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout))
1847 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (nevents < 0) {
1850 PyErr_Format(PyExc_ValueError,
1851 "Length of eventlist must be 0 or positive, got %d",
1852 nevents);
1853 return NULL;
1854 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 if (otimeout == Py_None || otimeout == NULL) {
1857 ptimeoutspec = NULL;
1858 }
1859 else if (PyNumber_Check(otimeout)) {
Victor Stinner5d272cc2012-03-13 13:35:55 +01001860 if (_PyTime_ObjectToTimespec(otimeout,
1861 &timeout.tv_sec, &timeout.tv_nsec) == -1)
1862 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001863
Victor Stinner5d272cc2012-03-13 13:35:55 +01001864 if (timeout.tv_sec < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PyErr_SetString(PyExc_ValueError,
1866 "timeout must be positive or None");
1867 return NULL;
1868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 ptimeoutspec = &timeoutspec;
1870 }
1871 else {
1872 PyErr_Format(PyExc_TypeError,
1873 "timeout argument must be an number "
1874 "or None, got %.200s",
1875 Py_TYPE(otimeout)->tp_name);
1876 return NULL;
1877 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 if (ch != NULL && ch != Py_None) {
1880 it = PyObject_GetIter(ch);
1881 if (it == NULL) {
1882 PyErr_SetString(PyExc_TypeError,
1883 "changelist is not iterable");
1884 return NULL;
1885 }
1886 nchanges = PyObject_Size(ch);
1887 if (nchanges < 0) {
1888 goto error;
1889 }
Georg Brandlc0e22b72010-03-14 10:51:01 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 chl = PyMem_New(struct kevent, nchanges);
1892 if (chl == NULL) {
1893 PyErr_NoMemory();
1894 goto error;
1895 }
1896 i = 0;
1897 while ((ei = PyIter_Next(it)) != NULL) {
1898 if (!kqueue_event_Check(ei)) {
1899 Py_DECREF(ei);
1900 PyErr_SetString(PyExc_TypeError,
1901 "changelist must be an iterable of "
1902 "select.kevent objects");
1903 goto error;
1904 } else {
1905 chl[i++] = ((kqueue_event_Object *)ei)->e;
1906 }
1907 Py_DECREF(ei);
1908 }
1909 }
1910 Py_CLEAR(it);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* event list */
1913 if (nevents) {
1914 evl = PyMem_New(struct kevent, nevents);
1915 if (evl == NULL) {
1916 PyErr_NoMemory();
1917 goto error;
1918 }
1919 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 Py_BEGIN_ALLOW_THREADS
1922 gotevents = kevent(self->kqfd, chl, nchanges,
1923 evl, nevents, ptimeoutspec);
1924 Py_END_ALLOW_THREADS
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 if (gotevents == -1) {
1927 PyErr_SetFromErrno(PyExc_OSError);
1928 goto error;
1929 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 result = PyList_New(gotevents);
1932 if (result == NULL) {
1933 goto error;
1934 }
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 for (i = 0; i < gotevents; i++) {
1937 kqueue_event_Object *ch;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type);
1940 if (ch == NULL) {
1941 goto error;
1942 }
1943 ch->e = evl[i];
1944 PyList_SET_ITEM(result, i, (PyObject *)ch);
1945 }
1946 PyMem_Free(chl);
1947 PyMem_Free(evl);
1948 return result;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001949
1950 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 PyMem_Free(chl);
1952 PyMem_Free(evl);
1953 Py_XDECREF(result);
1954 Py_XDECREF(it);
1955 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001956}
1957
1958PyDoc_STRVAR(kqueue_queue_control_doc,
Benjamin Peterson9bc93512008-09-22 22:10:59 +00001959"control(changelist, max_events[, timeout=None]) -> eventlist\n\
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001960\n\
1961Calls the kernel kevent function.\n\
1962- changelist must be a list of kevent objects describing the changes\n\
1963 to be made to the kernel's watch list or None.\n\
1964- max_events lets you specify the maximum number of events that the\n\
1965 kernel will return.\n\
1966- timeout is the maximum time to wait in seconds, or else None,\n\
1967 to wait forever. timeout accepts floats for smaller timeouts, too.");
1968
1969
1970static PyMethodDef kqueue_queue_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 {"fromfd", (PyCFunction)kqueue_queue_fromfd,
1972 METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc},
1973 {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS,
1974 kqueue_queue_close_doc},
1975 {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS,
1976 kqueue_queue_fileno_doc},
1977 {"control", (PyCFunction)kqueue_queue_control,
1978 METH_VARARGS , kqueue_queue_control_doc},
1979 {NULL, NULL},
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001980};
1981
1982static PyGetSetDef kqueue_queue_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 {"closed", (getter)kqueue_queue_get_closed, NULL,
1984 "True if the kqueue handler is closed"},
1985 {0},
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001986};
1987
1988PyDoc_STRVAR(kqueue_queue_doc,
1989"Kqueue syscall wrapper.\n\
1990\n\
1991For example, to start watching a socket for input:\n\
1992>>> kq = kqueue()\n\
1993>>> sock = socket()\n\
1994>>> sock.connect((host, port))\n\
1995>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\
1996\n\
1997To wait one second for it to become writeable:\n\
1998>>> kq.control(None, 1, 1000)\n\
1999\n\
2000To stop listening:\n\
2001>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)");
2002
2003static PyTypeObject kqueue_queue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyVarObject_HEAD_INIT(NULL, 0)
2005 "select.kqueue", /* tp_name */
2006 sizeof(kqueue_queue_Object), /* tp_basicsize */
2007 0, /* tp_itemsize */
2008 (destructor)kqueue_queue_dealloc, /* tp_dealloc */
2009 0, /* tp_print */
2010 0, /* tp_getattr */
2011 0, /* tp_setattr */
2012 0, /* tp_reserved */
2013 0, /* tp_repr */
2014 0, /* tp_as_number */
2015 0, /* tp_as_sequence */
2016 0, /* tp_as_mapping */
2017 0, /* tp_hash */
2018 0, /* tp_call */
2019 0, /* tp_str */
2020 0, /* tp_getattro */
2021 0, /* tp_setattro */
2022 0, /* tp_as_buffer */
2023 Py_TPFLAGS_DEFAULT, /* tp_flags */
2024 kqueue_queue_doc, /* tp_doc */
2025 0, /* tp_traverse */
2026 0, /* tp_clear */
2027 0, /* tp_richcompare */
2028 0, /* tp_weaklistoffset */
2029 0, /* tp_iter */
2030 0, /* tp_iternext */
2031 kqueue_queue_methods, /* tp_methods */
2032 0, /* tp_members */
2033 kqueue_queue_getsetlist, /* tp_getset */
2034 0, /* tp_base */
2035 0, /* tp_dict */
2036 0, /* tp_descr_get */
2037 0, /* tp_descr_set */
2038 0, /* tp_dictoffset */
2039 0, /* tp_init */
2040 0, /* tp_alloc */
2041 kqueue_queue_new, /* tp_new */
2042 0, /* tp_free */
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002043};
2044
2045#endif /* HAVE_KQUEUE */
Jesus Cead8b9ae62011-11-14 19:07:41 +01002046
2047
2048
2049
2050
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002051/* ************************************************************************ */
2052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002053PyDoc_STRVAR(select_doc,
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00002054"select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\
2055\n\
2056Wait until one or more file descriptors are ready for some kind of I/O.\n\
Brett Cannon62dba4c2003-09-10 19:37:42 +00002057The first three arguments are sequences of file descriptors to be waited for:\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00002058rlist -- wait until ready for reading\n\
2059wlist -- wait until ready for writing\n\
2060xlist -- wait for an ``exceptional condition''\n\
2061If only one kind of condition is required, pass [] for the other lists.\n\
2062A file descriptor is either a socket or file object, or a small integer\n\
2063gotten from a fileno() method call on one of those.\n\
2064\n\
2065The optional 4th argument specifies a timeout in seconds; it may be\n\
2066a floating point number to specify fractions of seconds. If it is absent\n\
2067or None, the call will never time out.\n\
2068\n\
2069The return value is a tuple of three lists corresponding to the first three\n\
2070arguments; each contains the subset of the corresponding file descriptors\n\
2071that are ready.\n\
2072\n\
2073*** IMPORTANT NOTICE ***\n\
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002074On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\
Christian Heimesf6cd9672008-03-26 13:45:42 +00002075descriptors can be used.");
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00002076
Barry Warsawe4ac0aa1996-12-12 00:04:35 +00002077static PyMethodDef select_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 {"select", select_select, METH_VARARGS, select_doc},
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002079#ifdef HAVE_POLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 {"poll", select_poll, METH_NOARGS, poll_doc},
Thomas Wouters477c8d52006-05-27 19:21:47 +00002081#endif /* HAVE_POLL */
Jesus Cead8b9ae62011-11-14 19:07:41 +01002082#ifdef HAVE_SYS_DEVPOLL_H
2083 {"devpoll", select_devpoll, METH_NOARGS, devpoll_doc},
2084#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 {0, 0}, /* sentinel */
Guido van Rossumed233a51992-06-23 09:07:03 +00002086};
2087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002088PyDoc_STRVAR(module_doc,
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00002089"This module supports asynchronous I/O on multiple file descriptors.\n\
2090\n\
2091*** IMPORTANT NOTICE ***\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002092On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors.");
Guido van Rossumed233a51992-06-23 09:07:03 +00002093
Martin v. Löwis1a214512008-06-11 05:26:20 +00002094
2095static struct PyModuleDef selectmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyModuleDef_HEAD_INIT,
2097 "select",
2098 module_doc,
2099 -1,
2100 select_methods,
2101 NULL,
2102 NULL,
2103 NULL,
2104 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002105};
2106
Jesus Cead8b9ae62011-11-14 19:07:41 +01002107
2108
2109
Mark Hammond62b1ab12002-07-23 06:31:15 +00002110PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002111PyInit_select(void)
Guido van Rossumed233a51992-06-23 09:07:03 +00002112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 PyObject *m;
2114 m = PyModule_Create(&selectmodule);
2115 if (m == NULL)
2116 return NULL;
Fred Drake4baedc12002-04-01 14:53:37 +00002117
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002118 Py_INCREF(PyExc_OSError);
2119 PyModule_AddObject(m, "error", PyExc_OSError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002120
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +00002121#ifdef PIPE_BUF
R. David Murraye16cda92010-10-15 23:12:57 +00002122#ifdef HAVE_BROKEN_PIPE_BUF
2123#undef PIPE_BUF
2124#define PIPE_BUF 512
2125#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF);
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +00002127#endif
Gregory P. Smithb970b862009-07-04 02:28:47 +00002128
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002129#if defined(HAVE_POLL)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002130#ifdef __APPLE__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 if (select_have_broken_poll()) {
2132 if (PyObject_DelAttrString(m, "poll") == -1) {
2133 PyErr_Clear();
2134 }
2135 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002136#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002138#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (PyType_Ready(&poll_Type) < 0)
2140 return NULL;
2141 PyModule_AddIntConstant(m, "POLLIN", POLLIN);
2142 PyModule_AddIntConstant(m, "POLLPRI", POLLPRI);
2143 PyModule_AddIntConstant(m, "POLLOUT", POLLOUT);
2144 PyModule_AddIntConstant(m, "POLLERR", POLLERR);
2145 PyModule_AddIntConstant(m, "POLLHUP", POLLHUP);
2146 PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL);
Andrew M. Kuchlingcf96dc82000-08-25 01:15:33 +00002147
Andrew M. Kuchling36d97eb2000-09-28 21:33:44 +00002148#ifdef POLLRDNORM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM);
Andrew M. Kuchling36d97eb2000-09-28 21:33:44 +00002150#endif
2151#ifdef POLLRDBAND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND);
Andrew M. Kuchling36d97eb2000-09-28 21:33:44 +00002153#endif
2154#ifdef POLLWRNORM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM);
Andrew M. Kuchling36d97eb2000-09-28 21:33:44 +00002156#endif
2157#ifdef POLLWRBAND
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND);
Andrew M. Kuchling36d97eb2000-09-28 21:33:44 +00002159#endif
Sjoerd Mullender239f8362000-08-25 13:59:18 +00002160#ifdef POLLMSG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyModule_AddIntConstant(m, "POLLMSG", POLLMSG);
Sjoerd Mullender239f8362000-08-25 13:59:18 +00002162#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002164#endif /* HAVE_POLL */
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002165
Jesus Cead8b9ae62011-11-14 19:07:41 +01002166#ifdef HAVE_SYS_DEVPOLL_H
2167 if (PyType_Ready(&devpoll_Type) < 0)
2168 return NULL;
2169#endif
2170
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002171#ifdef HAVE_EPOLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 Py_TYPE(&pyEpoll_Type) = &PyType_Type;
2173 if (PyType_Ready(&pyEpoll_Type) < 0)
2174 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 Py_INCREF(&pyEpoll_Type);
2177 PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN);
2180 PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT);
2181 PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI);
2182 PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR);
2183 PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP);
2184 PyModule_AddIntConstant(m, "EPOLLET", EPOLLET);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002185#ifdef EPOLLONESHOT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* Kernel 2.6.2+ */
2187 PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002188#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */
2190 PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM);
2191 PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND);
2192 PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM);
2193 PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND);
2194 PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG);
Benjamin Peterson2fb9ae92011-12-27 15:15:41 -06002195
Benjamin Peterson95c16622011-12-27 15:36:32 -06002196#ifdef EPOLL_CLOEXEC
Benjamin Peterson2fb9ae92011-12-27 15:15:41 -06002197 PyModule_AddIntConstant(m, "EPOLL_CLOEXEC", EPOLL_CLOEXEC);
Benjamin Peterson95c16622011-12-27 15:36:32 -06002198#endif
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002199#endif /* HAVE_EPOLL */
2200
2201#ifdef HAVE_KQUEUE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 kqueue_event_Type.tp_new = PyType_GenericNew;
2203 Py_TYPE(&kqueue_event_Type) = &PyType_Type;
2204 if(PyType_Ready(&kqueue_event_Type) < 0)
2205 return NULL;
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 Py_INCREF(&kqueue_event_Type);
2208 PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 Py_TYPE(&kqueue_queue_Type) = &PyType_Type;
2211 if(PyType_Ready(&kqueue_queue_Type) < 0)
2212 return NULL;
2213 Py_INCREF(&kqueue_queue_Type);
2214 PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type);
2215
2216 /* event filters */
2217 PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);
2218 PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);
2219 PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
2220 PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
2221 PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002222#ifdef EVFILT_NETDEV
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002224#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
2226 PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* event flags */
2229 PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);
2230 PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);
2231 PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);
2232 PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);
2233 PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);
2234 PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
2237 PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
2240 PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* READ WRITE filter flag */
2243 PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 /* VNODE filter flags */
2246 PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);
2247 PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);
2248 PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);
2249 PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);
2250 PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);
2251 PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);
2252 PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* PROC filter flags */
2255 PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);
2256 PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);
2257 PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);
2258 PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);
2259 PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);
2262 PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);
2263 PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);
2264
2265 /* NETDEV filter flags */
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002266#ifdef EVFILT_NETDEV
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);
2268 PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);
2269 PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);
Christian Heimes4fbc72b2008-03-22 00:47:35 +00002270#endif
2271
2272#endif /* HAVE_KQUEUE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 return m;
Guido van Rossumed233a51992-06-23 09:07:03 +00002274}