ยปCore Development>Code coverage>Modules/selectmodule.c

Python code coverage for Modules/selectmodule.c

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