PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/Modules/selectmodule.c

https://bitbucket.org/mirror/cpython/
C | 2591 lines | 2086 code | 344 blank | 161 comment | 362 complexity | 7d995046bb216cb558c4f325ad52a0ea MD5 | raw file
Possible License(s): Unlicense, 0BSD, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. /* select - Module containing unix select(2) call.
  2. Under Unix, the file descriptors are small integers.
  3. Under Win32, select only exists for sockets, and sockets may
  4. have any value except INVALID_SOCKET.
  5. */
  6. #if defined(HAVE_POLL_H) && !defined(_GNU_SOURCE)
  7. #define _GNU_SOURCE
  8. #endif
  9. #include "Python.h"
  10. #include <structmember.h>
  11. #ifdef HAVE_SYS_DEVPOLL_H
  12. #include <sys/resource.h>
  13. #include <sys/devpoll.h>
  14. #include <sys/types.h>
  15. #include <sys/stat.h>
  16. #include <fcntl.h>
  17. #endif
  18. #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. /* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined.
  25. 64 is too small (too many people have bumped into that limit).
  26. Here we boost it.
  27. Users who want even more than the boosted limit should #define
  28. FD_SETSIZE higher before this; e.g., via compiler /D switch.
  29. */
  30. #if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
  31. #define FD_SETSIZE 512
  32. #endif
  33. #if defined(HAVE_POLL_H)
  34. #include <poll.h>
  35. #elif defined(HAVE_SYS_POLL_H)
  36. #include <sys/poll.h>
  37. #endif
  38. #ifdef __sgi
  39. /* This is missing from unistd.h */
  40. extern void bzero(void *, int);
  41. #endif
  42. #ifdef HAVE_SYS_TYPES_H
  43. #include <sys/types.h>
  44. #endif
  45. #ifdef MS_WINDOWS
  46. # define WIN32_LEAN_AND_MEAN
  47. # include <winsock.h>
  48. #else
  49. # define SOCKET int
  50. #endif
  51. /* list of Python objects and their file descriptor */
  52. typedef struct {
  53. PyObject *obj; /* owned reference */
  54. SOCKET fd;
  55. int sentinel; /* -1 == sentinel */
  56. } pylist;
  57. static void
  58. reap_obj(pylist fd2obj[FD_SETSIZE + 1])
  59. {
  60. int i;
  61. for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
  62. Py_CLEAR(fd2obj[i].obj);
  63. }
  64. fd2obj[0].sentinel = -1;
  65. }
  66. /* returns -1 and sets the Python exception if an error occurred, otherwise
  67. returns a number >= 0
  68. */
  69. static int
  70. seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
  71. {
  72. int max = -1;
  73. int index = 0;
  74. Py_ssize_t i;
  75. PyObject* fast_seq = NULL;
  76. PyObject* o = NULL;
  77. fd2obj[0].obj = (PyObject*)0; /* set list to zero size */
  78. FD_ZERO(set);
  79. fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
  80. if (!fast_seq)
  81. return -1;
  82. for (i = 0; i < PySequence_Fast_GET_SIZE(fast_seq); i++) {
  83. SOCKET v;
  84. /* any intervening fileno() calls could decr this refcnt */
  85. if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
  86. goto finally;
  87. Py_INCREF(o);
  88. v = PyObject_AsFileDescriptor( o );
  89. if (v == -1) goto finally;
  90. #if defined(_MSC_VER)
  91. max = 0; /* not used for Win32 */
  92. #else /* !_MSC_VER */
  93. if (!_PyIsSelectable_fd(v)) {
  94. PyErr_SetString(PyExc_ValueError,
  95. "filedescriptor out of range in select()");
  96. goto finally;
  97. }
  98. if (v > max)
  99. max = v;
  100. #endif /* _MSC_VER */
  101. FD_SET(v, set);
  102. /* add object and its file descriptor to the list */
  103. if (index >= FD_SETSIZE) {
  104. PyErr_SetString(PyExc_ValueError,
  105. "too many file descriptors in select()");
  106. goto finally;
  107. }
  108. fd2obj[index].obj = o;
  109. fd2obj[index].fd = v;
  110. fd2obj[index].sentinel = 0;
  111. fd2obj[++index].sentinel = -1;
  112. }
  113. Py_DECREF(fast_seq);
  114. return max+1;
  115. finally:
  116. Py_XDECREF(o);
  117. Py_DECREF(fast_seq);
  118. return -1;
  119. }
  120. /* returns NULL and sets the Python exception if an error occurred */
  121. static PyObject *
  122. set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
  123. {
  124. int i, j, count=0;
  125. PyObject *list, *o;
  126. SOCKET fd;
  127. for (j = 0; fd2obj[j].sentinel >= 0; j++) {
  128. if (FD_ISSET(fd2obj[j].fd, set))
  129. count++;
  130. }
  131. list = PyList_New(count);
  132. if (!list)
  133. return NULL;
  134. i = 0;
  135. for (j = 0; fd2obj[j].sentinel >= 0; j++) {
  136. fd = fd2obj[j].fd;
  137. if (FD_ISSET(fd, set)) {
  138. o = fd2obj[j].obj;
  139. fd2obj[j].obj = NULL;
  140. /* transfer ownership */
  141. if (PyList_SetItem(list, i, o) < 0)
  142. goto finally;
  143. i++;
  144. }
  145. }
  146. return list;
  147. finally:
  148. Py_DECREF(list);
  149. return NULL;
  150. }
  151. #undef SELECT_USES_HEAP
  152. #if FD_SETSIZE > 1024
  153. #define SELECT_USES_HEAP
  154. #endif /* FD_SETSIZE > 1024 */
  155. static PyObject *
  156. select_select(PyObject *self, PyObject *args)
  157. {
  158. #ifdef SELECT_USES_HEAP
  159. pylist *rfd2obj, *wfd2obj, *efd2obj;
  160. #else /* !SELECT_USES_HEAP */
  161. /* XXX: All this should probably be implemented as follows:
  162. * - find the highest descriptor we're interested in
  163. * - add one
  164. * - that's the size
  165. * See: Stevens, APitUE, $12.5.1
  166. */
  167. pylist rfd2obj[FD_SETSIZE + 1];
  168. pylist wfd2obj[FD_SETSIZE + 1];
  169. pylist efd2obj[FD_SETSIZE + 1];
  170. #endif /* SELECT_USES_HEAP */
  171. PyObject *ifdlist, *ofdlist, *efdlist;
  172. PyObject *ret = NULL;
  173. PyObject *timeout_obj = Py_None;
  174. fd_set ifdset, ofdset, efdset;
  175. struct timeval tv, *tvp;
  176. int imax, omax, emax, max;
  177. int n;
  178. _PyTime_t timeout, deadline = 0;
  179. /* convert arguments */
  180. if (!PyArg_UnpackTuple(args, "select", 3, 4,
  181. &ifdlist, &ofdlist, &efdlist, &timeout_obj))
  182. return NULL;
  183. if (timeout_obj == Py_None)
  184. tvp = (struct timeval *)NULL;
  185. else {
  186. if (_PyTime_FromSecondsObject(&timeout, timeout_obj,
  187. _PyTime_ROUND_CEILING) < 0) {
  188. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  189. PyErr_SetString(PyExc_TypeError,
  190. "timeout must be a float or None");
  191. }
  192. return NULL;
  193. }
  194. if (_PyTime_AsTimeval(timeout, &tv, _PyTime_ROUND_CEILING) == -1)
  195. return NULL;
  196. if (tv.tv_sec < 0) {
  197. PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
  198. return NULL;
  199. }
  200. tvp = &tv;
  201. }
  202. #ifdef SELECT_USES_HEAP
  203. /* Allocate memory for the lists */
  204. rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
  205. wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
  206. efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
  207. if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
  208. if (rfd2obj) PyMem_DEL(rfd2obj);
  209. if (wfd2obj) PyMem_DEL(wfd2obj);
  210. if (efd2obj) PyMem_DEL(efd2obj);
  211. return PyErr_NoMemory();
  212. }
  213. #endif /* SELECT_USES_HEAP */
  214. /* Convert sequences to fd_sets, and get maximum fd number
  215. * propagates the Python exception set in seq2set()
  216. */
  217. rfd2obj[0].sentinel = -1;
  218. wfd2obj[0].sentinel = -1;
  219. efd2obj[0].sentinel = -1;
  220. if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
  221. goto finally;
  222. if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
  223. goto finally;
  224. if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
  225. goto finally;
  226. max = imax;
  227. if (omax > max) max = omax;
  228. if (emax > max) max = emax;
  229. if (tvp)
  230. deadline = _PyTime_GetMonotonicClock() + timeout;
  231. do {
  232. Py_BEGIN_ALLOW_THREADS
  233. errno = 0;
  234. n = select(max, &ifdset, &ofdset, &efdset, tvp);
  235. Py_END_ALLOW_THREADS
  236. if (errno != EINTR)
  237. break;
  238. /* select() was interrupted by a signal */
  239. if (PyErr_CheckSignals())
  240. goto finally;
  241. if (tvp) {
  242. timeout = deadline - _PyTime_GetMonotonicClock();
  243. if (timeout < 0) {
  244. n = 0;
  245. break;
  246. }
  247. _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
  248. /* retry select() with the recomputed timeout */
  249. }
  250. } while (1);
  251. #ifdef MS_WINDOWS
  252. if (n == SOCKET_ERROR) {
  253. PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
  254. }
  255. #else
  256. if (n < 0) {
  257. PyErr_SetFromErrno(PyExc_OSError);
  258. }
  259. #endif
  260. else {
  261. /* any of these three calls can raise an exception. it's more
  262. convenient to test for this after all three calls... but
  263. is that acceptable?
  264. */
  265. ifdlist = set2list(&ifdset, rfd2obj);
  266. ofdlist = set2list(&ofdset, wfd2obj);
  267. efdlist = set2list(&efdset, efd2obj);
  268. if (PyErr_Occurred())
  269. ret = NULL;
  270. else
  271. ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);
  272. Py_XDECREF(ifdlist);
  273. Py_XDECREF(ofdlist);
  274. Py_XDECREF(efdlist);
  275. }
  276. finally:
  277. reap_obj(rfd2obj);
  278. reap_obj(wfd2obj);
  279. reap_obj(efd2obj);
  280. #ifdef SELECT_USES_HEAP
  281. PyMem_DEL(rfd2obj);
  282. PyMem_DEL(wfd2obj);
  283. PyMem_DEL(efd2obj);
  284. #endif /* SELECT_USES_HEAP */
  285. return ret;
  286. }
  287. #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
  288. /*
  289. * poll() support
  290. */
  291. typedef struct {
  292. PyObject_HEAD
  293. PyObject *dict;
  294. int ufd_uptodate;
  295. int ufd_len;
  296. struct pollfd *ufds;
  297. int poll_running;
  298. } pollObject;
  299. static PyTypeObject poll_Type;
  300. /* Update the malloc'ed array of pollfds to match the dictionary
  301. contained within a pollObject. Return 1 on success, 0 on an error.
  302. */
  303. static int
  304. update_ufd_array(pollObject *self)
  305. {
  306. Py_ssize_t i, pos;
  307. PyObject *key, *value;
  308. struct pollfd *old_ufds = self->ufds;
  309. self->ufd_len = PyDict_Size(self->dict);
  310. PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
  311. if (self->ufds == NULL) {
  312. self->ufds = old_ufds;
  313. PyErr_NoMemory();
  314. return 0;
  315. }
  316. i = pos = 0;
  317. while (PyDict_Next(self->dict, &pos, &key, &value)) {
  318. assert(i < self->ufd_len);
  319. /* Never overflow */
  320. self->ufds[i].fd = (int)PyLong_AsLong(key);
  321. self->ufds[i].events = (short)(unsigned short)PyLong_AsLong(value);
  322. i++;
  323. }
  324. assert(i == self->ufd_len);
  325. self->ufd_uptodate = 1;
  326. return 1;
  327. }
  328. static int
  329. ushort_converter(PyObject *obj, void *ptr)
  330. {
  331. unsigned long uval;
  332. uval = PyLong_AsUnsignedLong(obj);
  333. if (uval == (unsigned long)-1 && PyErr_Occurred())
  334. return 0;
  335. if (uval > USHRT_MAX) {
  336. PyErr_SetString(PyExc_OverflowError,
  337. "Python int too large for C unsigned short");
  338. return 0;
  339. }
  340. *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
  341. return 1;
  342. }
  343. PyDoc_STRVAR(poll_register_doc,
  344. "register(fd [, eventmask] ) -> None\n\n\
  345. Register a file descriptor with the polling object.\n\
  346. fd -- either an integer, or an object with a fileno() method returning an\n\
  347. int.\n\
  348. events -- an optional bitmask describing the type of events to check for");
  349. static PyObject *
  350. poll_register(pollObject *self, PyObject *args)
  351. {
  352. PyObject *o, *key, *value;
  353. int fd;
  354. unsigned short events = POLLIN | POLLPRI | POLLOUT;
  355. int err;
  356. if (!PyArg_ParseTuple(args, "O|O&:register", &o, ushort_converter, &events))
  357. return NULL;
  358. fd = PyObject_AsFileDescriptor(o);
  359. if (fd == -1) return NULL;
  360. /* Add entry to the internal dictionary: the key is the
  361. file descriptor, and the value is the event mask. */
  362. key = PyLong_FromLong(fd);
  363. if (key == NULL)
  364. return NULL;
  365. value = PyLong_FromLong(events);
  366. if (value == NULL) {
  367. Py_DECREF(key);
  368. return NULL;
  369. }
  370. err = PyDict_SetItem(self->dict, key, value);
  371. Py_DECREF(key);
  372. Py_DECREF(value);
  373. if (err < 0)
  374. return NULL;
  375. self->ufd_uptodate = 0;
  376. Py_INCREF(Py_None);
  377. return Py_None;
  378. }
  379. PyDoc_STRVAR(poll_modify_doc,
  380. "modify(fd, eventmask) -> None\n\n\
  381. Modify an already registered file descriptor.\n\
  382. fd -- either an integer, or an object with a fileno() method returning an\n\
  383. int.\n\
  384. events -- an optional bitmask describing the type of events to check for");
  385. static PyObject *
  386. poll_modify(pollObject *self, PyObject *args)
  387. {
  388. PyObject *o, *key, *value;
  389. int fd;
  390. unsigned short events;
  391. int err;
  392. if (!PyArg_ParseTuple(args, "OO&:modify", &o, ushort_converter, &events))
  393. return NULL;
  394. fd = PyObject_AsFileDescriptor(o);
  395. if (fd == -1) return NULL;
  396. /* Modify registered fd */
  397. key = PyLong_FromLong(fd);
  398. if (key == NULL)
  399. return NULL;
  400. if (PyDict_GetItem(self->dict, key) == NULL) {
  401. errno = ENOENT;
  402. PyErr_SetFromErrno(PyExc_OSError);
  403. Py_DECREF(key);
  404. return NULL;
  405. }
  406. value = PyLong_FromLong(events);
  407. if (value == NULL) {
  408. Py_DECREF(key);
  409. return NULL;
  410. }
  411. err = PyDict_SetItem(self->dict, key, value);
  412. Py_DECREF(key);
  413. Py_DECREF(value);
  414. if (err < 0)
  415. return NULL;
  416. self->ufd_uptodate = 0;
  417. Py_INCREF(Py_None);
  418. return Py_None;
  419. }
  420. PyDoc_STRVAR(poll_unregister_doc,
  421. "unregister(fd) -> None\n\n\
  422. Remove a file descriptor being tracked by the polling object.");
  423. static PyObject *
  424. poll_unregister(pollObject *self, PyObject *o)
  425. {
  426. PyObject *key;
  427. int fd;
  428. fd = PyObject_AsFileDescriptor( o );
  429. if (fd == -1)
  430. return NULL;
  431. /* Check whether the fd is already in the array */
  432. key = PyLong_FromLong(fd);
  433. if (key == NULL)
  434. return NULL;
  435. if (PyDict_DelItem(self->dict, key) == -1) {
  436. Py_DECREF(key);
  437. /* This will simply raise the KeyError set by PyDict_DelItem
  438. if the file descriptor isn't registered. */
  439. return NULL;
  440. }
  441. Py_DECREF(key);
  442. self->ufd_uptodate = 0;
  443. Py_INCREF(Py_None);
  444. return Py_None;
  445. }
  446. PyDoc_STRVAR(poll_poll_doc,
  447. "poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
  448. Polls the set of registered file descriptors, returning a list containing \n\
  449. any descriptors that have events or errors to report.");
  450. static PyObject *
  451. poll_poll(pollObject *self, PyObject *args)
  452. {
  453. PyObject *result_list = NULL, *timeout_obj = NULL;
  454. int poll_result, i, j;
  455. PyObject *value = NULL, *num = NULL;
  456. _PyTime_t timeout, ms, deadline;
  457. int async_err = 0;
  458. if (!PyArg_ParseTuple(args, "|O:poll", &timeout_obj)) {
  459. return NULL;
  460. }
  461. /* Check values for timeout */
  462. if (timeout_obj == NULL || timeout_obj == Py_None) {
  463. timeout = -1;
  464. ms = -1;
  465. deadline = 0; /* initialize to prevent gcc warning */
  466. }
  467. else {
  468. if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
  469. _PyTime_ROUND_CEILING) < 0) {
  470. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  471. PyErr_SetString(PyExc_TypeError,
  472. "timeout must be an integer or None");
  473. }
  474. return NULL;
  475. }
  476. ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
  477. if (ms < INT_MIN || ms > INT_MAX) {
  478. PyErr_SetString(PyExc_OverflowError, "timeout is too large");
  479. return NULL;
  480. }
  481. deadline = _PyTime_GetMonotonicClock() + timeout;
  482. }
  483. /* Avoid concurrent poll() invocation, issue 8865 */
  484. if (self->poll_running) {
  485. PyErr_SetString(PyExc_RuntimeError,
  486. "concurrent poll() invocation");
  487. return NULL;
  488. }
  489. /* Ensure the ufd array is up to date */
  490. if (!self->ufd_uptodate)
  491. if (update_ufd_array(self) == 0)
  492. return NULL;
  493. self->poll_running = 1;
  494. /* call poll() */
  495. async_err = 0;
  496. do {
  497. Py_BEGIN_ALLOW_THREADS
  498. errno = 0;
  499. poll_result = poll(self->ufds, self->ufd_len, (int)ms);
  500. Py_END_ALLOW_THREADS
  501. if (errno != EINTR)
  502. break;
  503. /* poll() was interrupted by a signal */
  504. if (PyErr_CheckSignals()) {
  505. async_err = 1;
  506. break;
  507. }
  508. if (timeout >= 0) {
  509. timeout = deadline - _PyTime_GetMonotonicClock();
  510. if (timeout < 0) {
  511. poll_result = 0;
  512. break;
  513. }
  514. ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
  515. /* retry poll() with the recomputed timeout */
  516. }
  517. } while (1);
  518. self->poll_running = 0;
  519. if (poll_result < 0) {
  520. if (!async_err)
  521. PyErr_SetFromErrno(PyExc_OSError);
  522. return NULL;
  523. }
  524. /* build the result list */
  525. result_list = PyList_New(poll_result);
  526. if (!result_list)
  527. return NULL;
  528. for (i = 0, j = 0; j < poll_result; j++) {
  529. /* skip to the next fired descriptor */
  530. while (!self->ufds[i].revents) {
  531. i++;
  532. }
  533. /* if we hit a NULL return, set value to NULL
  534. and break out of loop; code at end will
  535. clean up result_list */
  536. value = PyTuple_New(2);
  537. if (value == NULL)
  538. goto error;
  539. num = PyLong_FromLong(self->ufds[i].fd);
  540. if (num == NULL) {
  541. Py_DECREF(value);
  542. goto error;
  543. }
  544. PyTuple_SET_ITEM(value, 0, num);
  545. /* The &0xffff is a workaround for AIX. 'revents'
  546. is a 16-bit short, and IBM assigned POLLNVAL
  547. to be 0x8000, so the conversion to int results
  548. in a negative number. See SF bug #923315. */
  549. num = PyLong_FromLong(self->ufds[i].revents & 0xffff);
  550. if (num == NULL) {
  551. Py_DECREF(value);
  552. goto error;
  553. }
  554. PyTuple_SET_ITEM(value, 1, num);
  555. if ((PyList_SetItem(result_list, j, value)) == -1) {
  556. Py_DECREF(value);
  557. goto error;
  558. }
  559. i++;
  560. }
  561. return result_list;
  562. error:
  563. Py_DECREF(result_list);
  564. return NULL;
  565. }
  566. static PyMethodDef poll_methods[] = {
  567. {"register", (PyCFunction)poll_register,
  568. METH_VARARGS, poll_register_doc},
  569. {"modify", (PyCFunction)poll_modify,
  570. METH_VARARGS, poll_modify_doc},
  571. {"unregister", (PyCFunction)poll_unregister,
  572. METH_O, poll_unregister_doc},
  573. {"poll", (PyCFunction)poll_poll,
  574. METH_VARARGS, poll_poll_doc},
  575. {NULL, NULL} /* sentinel */
  576. };
  577. static pollObject *
  578. newPollObject(void)
  579. {
  580. pollObject *self;
  581. self = PyObject_New(pollObject, &poll_Type);
  582. if (self == NULL)
  583. return NULL;
  584. /* ufd_uptodate is a Boolean, denoting whether the
  585. array pointed to by ufds matches the contents of the dictionary. */
  586. self->ufd_uptodate = 0;
  587. self->ufds = NULL;
  588. self->poll_running = 0;
  589. self->dict = PyDict_New();
  590. if (self->dict == NULL) {
  591. Py_DECREF(self);
  592. return NULL;
  593. }
  594. return self;
  595. }
  596. static void
  597. poll_dealloc(pollObject *self)
  598. {
  599. if (self->ufds != NULL)
  600. PyMem_DEL(self->ufds);
  601. Py_XDECREF(self->dict);
  602. PyObject_Del(self);
  603. }
  604. static PyTypeObject poll_Type = {
  605. /* The ob_type field must be initialized in the module init function
  606. * to be portable to Windows without using C++. */
  607. PyVarObject_HEAD_INIT(NULL, 0)
  608. "select.poll", /*tp_name*/
  609. sizeof(pollObject), /*tp_basicsize*/
  610. 0, /*tp_itemsize*/
  611. /* methods */
  612. (destructor)poll_dealloc, /*tp_dealloc*/
  613. 0, /*tp_print*/
  614. 0, /*tp_getattr*/
  615. 0, /*tp_setattr*/
  616. 0, /*tp_reserved*/
  617. 0, /*tp_repr*/
  618. 0, /*tp_as_number*/
  619. 0, /*tp_as_sequence*/
  620. 0, /*tp_as_mapping*/
  621. 0, /*tp_hash*/
  622. 0, /*tp_call*/
  623. 0, /*tp_str*/
  624. 0, /*tp_getattro*/
  625. 0, /*tp_setattro*/
  626. 0, /*tp_as_buffer*/
  627. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  628. 0, /*tp_doc*/
  629. 0, /*tp_traverse*/
  630. 0, /*tp_clear*/
  631. 0, /*tp_richcompare*/
  632. 0, /*tp_weaklistoffset*/
  633. 0, /*tp_iter*/
  634. 0, /*tp_iternext*/
  635. poll_methods, /*tp_methods*/
  636. };
  637. #ifdef HAVE_SYS_DEVPOLL_H
  638. typedef struct {
  639. PyObject_HEAD
  640. int fd_devpoll;
  641. int max_n_fds;
  642. int n_fds;
  643. struct pollfd *fds;
  644. } devpollObject;
  645. static PyTypeObject devpoll_Type;
  646. static PyObject *
  647. devpoll_err_closed(void)
  648. {
  649. PyErr_SetString(PyExc_ValueError, "I/O operation on closed devpoll object");
  650. return NULL;
  651. }
  652. static int devpoll_flush(devpollObject *self)
  653. {
  654. int size, n;
  655. if (!self->n_fds) return 0;
  656. size = sizeof(struct pollfd)*self->n_fds;
  657. self->n_fds = 0;
  658. n = _Py_write(self->fd_devpoll, self->fds, size);
  659. if (n == -1)
  660. return -1;
  661. if (n < size) {
  662. /*
  663. ** Data writed to /dev/poll is a binary data structure. It is not
  664. ** clear what to do if a partial write occurred. For now, raise
  665. ** an exception and see if we actually found this problem in
  666. ** the wild.
  667. ** See http://bugs.python.org/issue6397.
  668. */
  669. PyErr_Format(PyExc_IOError, "failed to write all pollfds. "
  670. "Please, report at http://bugs.python.org/. "
  671. "Data to report: Size tried: %d, actual size written: %d.",
  672. size, n);
  673. return -1;
  674. }
  675. return 0;
  676. }
  677. static PyObject *
  678. internal_devpoll_register(devpollObject *self, PyObject *args, int remove)
  679. {
  680. PyObject *o;
  681. int fd;
  682. unsigned short events = POLLIN | POLLPRI | POLLOUT;
  683. if (self->fd_devpoll < 0)
  684. return devpoll_err_closed();
  685. if (!PyArg_ParseTuple(args, "O|O&:register", &o, ushort_converter, &events))
  686. return NULL;
  687. fd = PyObject_AsFileDescriptor(o);
  688. if (fd == -1) return NULL;
  689. if (remove) {
  690. self->fds[self->n_fds].fd = fd;
  691. self->fds[self->n_fds].events = POLLREMOVE;
  692. if (++self->n_fds == self->max_n_fds) {
  693. if (devpoll_flush(self))
  694. return NULL;
  695. }
  696. }
  697. self->fds[self->n_fds].fd = fd;
  698. self->fds[self->n_fds].events = (signed short)events;
  699. if (++self->n_fds == self->max_n_fds) {
  700. if (devpoll_flush(self))
  701. return NULL;
  702. }
  703. Py_RETURN_NONE;
  704. }
  705. PyDoc_STRVAR(devpoll_register_doc,
  706. "register(fd [, eventmask] ) -> None\n\n\
  707. Register a file descriptor with the polling object.\n\
  708. fd -- either an integer, or an object with a fileno() method returning an\n\
  709. int.\n\
  710. events -- an optional bitmask describing the type of events to check for");
  711. static PyObject *
  712. devpoll_register(devpollObject *self, PyObject *args)
  713. {
  714. return internal_devpoll_register(self, args, 0);
  715. }
  716. PyDoc_STRVAR(devpoll_modify_doc,
  717. "modify(fd[, eventmask]) -> None\n\n\
  718. Modify a possible already registered file descriptor.\n\
  719. fd -- either an integer, or an object with a fileno() method returning an\n\
  720. int.\n\
  721. events -- an optional bitmask describing the type of events to check for");
  722. static PyObject *
  723. devpoll_modify(devpollObject *self, PyObject *args)
  724. {
  725. return internal_devpoll_register(self, args, 1);
  726. }
  727. PyDoc_STRVAR(devpoll_unregister_doc,
  728. "unregister(fd) -> None\n\n\
  729. Remove a file descriptor being tracked by the polling object.");
  730. static PyObject *
  731. devpoll_unregister(devpollObject *self, PyObject *o)
  732. {
  733. int fd;
  734. if (self->fd_devpoll < 0)
  735. return devpoll_err_closed();
  736. fd = PyObject_AsFileDescriptor( o );
  737. if (fd == -1)
  738. return NULL;
  739. self->fds[self->n_fds].fd = fd;
  740. self->fds[self->n_fds].events = POLLREMOVE;
  741. if (++self->n_fds == self->max_n_fds) {
  742. if (devpoll_flush(self))
  743. return NULL;
  744. }
  745. Py_RETURN_NONE;
  746. }
  747. PyDoc_STRVAR(devpoll_poll_doc,
  748. "poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
  749. Polls the set of registered file descriptors, returning a list containing \n\
  750. any descriptors that have events or errors to report.");
  751. static PyObject *
  752. devpoll_poll(devpollObject *self, PyObject *args)
  753. {
  754. struct dvpoll dvp;
  755. PyObject *result_list = NULL, *timeout_obj = NULL;
  756. int poll_result, i;
  757. PyObject *value, *num1, *num2;
  758. _PyTime_t timeout, ms, deadline = 0;
  759. if (self->fd_devpoll < 0)
  760. return devpoll_err_closed();
  761. if (!PyArg_ParseTuple(args, "|O:poll", &timeout_obj)) {
  762. return NULL;
  763. }
  764. /* Check values for timeout */
  765. if (timeout_obj == NULL || timeout_obj == Py_None) {
  766. timeout = -1;
  767. ms = -1;
  768. }
  769. else {
  770. if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
  771. _PyTime_ROUND_CEILING) < 0) {
  772. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  773. PyErr_SetString(PyExc_TypeError,
  774. "timeout must be an integer or None");
  775. }
  776. return NULL;
  777. }
  778. ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
  779. if (ms < -1 || ms > INT_MAX) {
  780. PyErr_SetString(PyExc_OverflowError, "timeout is too large");
  781. return NULL;
  782. }
  783. }
  784. if (devpoll_flush(self))
  785. return NULL;
  786. dvp.dp_fds = self->fds;
  787. dvp.dp_nfds = self->max_n_fds;
  788. dvp.dp_timeout = (int)ms;
  789. if (timeout >= 0)
  790. deadline = _PyTime_GetMonotonicClock() + timeout;
  791. do {
  792. /* call devpoll() */
  793. Py_BEGIN_ALLOW_THREADS
  794. errno = 0;
  795. poll_result = ioctl(self->fd_devpoll, DP_POLL, &dvp);
  796. Py_END_ALLOW_THREADS
  797. if (errno != EINTR)
  798. break;
  799. /* devpoll() was interrupted by a signal */
  800. if (PyErr_CheckSignals())
  801. return NULL;
  802. if (timeout >= 0) {
  803. timeout = deadline - _PyTime_GetMonotonicClock();
  804. if (timeout < 0) {
  805. poll_result = 0;
  806. break;
  807. }
  808. ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
  809. dvp.dp_timeout = (int)ms;
  810. /* retry devpoll() with the recomputed timeout */
  811. }
  812. } while (1);
  813. if (poll_result < 0) {
  814. PyErr_SetFromErrno(PyExc_IOError);
  815. return NULL;
  816. }
  817. /* build the result list */
  818. result_list = PyList_New(poll_result);
  819. if (!result_list)
  820. return NULL;
  821. for (i = 0; i < poll_result; i++) {
  822. num1 = PyLong_FromLong(self->fds[i].fd);
  823. num2 = PyLong_FromLong(self->fds[i].revents);
  824. if ((num1 == NULL) || (num2 == NULL)) {
  825. Py_XDECREF(num1);
  826. Py_XDECREF(num2);
  827. goto error;
  828. }
  829. value = PyTuple_Pack(2, num1, num2);
  830. Py_DECREF(num1);
  831. Py_DECREF(num2);
  832. if (value == NULL)
  833. goto error;
  834. if ((PyList_SetItem(result_list, i, value)) == -1) {
  835. Py_DECREF(value);
  836. goto error;
  837. }
  838. }
  839. return result_list;
  840. error:
  841. Py_DECREF(result_list);
  842. return NULL;
  843. }
  844. static int
  845. devpoll_internal_close(devpollObject *self)
  846. {
  847. int save_errno = 0;
  848. if (self->fd_devpoll >= 0) {
  849. int fd = self->fd_devpoll;
  850. self->fd_devpoll = -1;
  851. Py_BEGIN_ALLOW_THREADS
  852. if (close(fd) < 0)
  853. save_errno = errno;
  854. Py_END_ALLOW_THREADS
  855. }
  856. return save_errno;
  857. }
  858. static PyObject*
  859. devpoll_close(devpollObject *self)
  860. {
  861. errno = devpoll_internal_close(self);
  862. if (errno < 0) {
  863. PyErr_SetFromErrno(PyExc_OSError);
  864. return NULL;
  865. }
  866. Py_RETURN_NONE;
  867. }
  868. PyDoc_STRVAR(devpoll_close_doc,
  869. "close() -> None\n\
  870. \n\
  871. Close the devpoll file descriptor. Further operations on the devpoll\n\
  872. object will raise an exception.");
  873. static PyObject*
  874. devpoll_get_closed(devpollObject *self)
  875. {
  876. if (self->fd_devpoll < 0)
  877. Py_RETURN_TRUE;
  878. else
  879. Py_RETURN_FALSE;
  880. }
  881. static PyObject*
  882. devpoll_fileno(devpollObject *self)
  883. {
  884. if (self->fd_devpoll < 0)
  885. return devpoll_err_closed();
  886. return PyLong_FromLong(self->fd_devpoll);
  887. }
  888. PyDoc_STRVAR(devpoll_fileno_doc,
  889. "fileno() -> int\n\
  890. \n\
  891. Return the file descriptor.");
  892. static PyMethodDef devpoll_methods[] = {
  893. {"register", (PyCFunction)devpoll_register,
  894. METH_VARARGS, devpoll_register_doc},
  895. {"modify", (PyCFunction)devpoll_modify,
  896. METH_VARARGS, devpoll_modify_doc},
  897. {"unregister", (PyCFunction)devpoll_unregister,
  898. METH_O, devpoll_unregister_doc},
  899. {"poll", (PyCFunction)devpoll_poll,
  900. METH_VARARGS, devpoll_poll_doc},
  901. {"close", (PyCFunction)devpoll_close, METH_NOARGS,
  902. devpoll_close_doc},
  903. {"fileno", (PyCFunction)devpoll_fileno, METH_NOARGS,
  904. devpoll_fileno_doc},
  905. {NULL, NULL} /* sentinel */
  906. };
  907. static PyGetSetDef devpoll_getsetlist[] = {
  908. {"closed", (getter)devpoll_get_closed, NULL,
  909. "True if the devpoll object is closed"},
  910. {0},
  911. };
  912. static devpollObject *
  913. newDevPollObject(void)
  914. {
  915. devpollObject *self;
  916. int fd_devpoll, limit_result;
  917. struct pollfd *fds;
  918. struct rlimit limit;
  919. /*
  920. ** If we try to process more that getrlimit()
  921. ** fds, the kernel will give an error, so
  922. ** we set the limit here. It is a dynamic
  923. ** value, because we can change rlimit() anytime.
  924. */
  925. limit_result = getrlimit(RLIMIT_NOFILE, &limit);
  926. if (limit_result == -1) {
  927. PyErr_SetFromErrno(PyExc_OSError);
  928. return NULL;
  929. }
  930. fd_devpoll = _Py_open("/dev/poll", O_RDWR);
  931. if (fd_devpoll == -1)
  932. return NULL;
  933. fds = PyMem_NEW(struct pollfd, limit.rlim_cur);
  934. if (fds == NULL) {
  935. close(fd_devpoll);
  936. PyErr_NoMemory();
  937. return NULL;
  938. }
  939. self = PyObject_New(devpollObject, &devpoll_Type);
  940. if (self == NULL) {
  941. close(fd_devpoll);
  942. PyMem_DEL(fds);
  943. return NULL;
  944. }
  945. self->fd_devpoll = fd_devpoll;
  946. self->max_n_fds = limit.rlim_cur;
  947. self->n_fds = 0;
  948. self->fds = fds;
  949. return self;
  950. }
  951. static void
  952. devpoll_dealloc(devpollObject *self)
  953. {
  954. (void)devpoll_internal_close(self);
  955. PyMem_DEL(self->fds);
  956. PyObject_Del(self);
  957. }
  958. static PyTypeObject devpoll_Type = {
  959. /* The ob_type field must be initialized in the module init function
  960. * to be portable to Windows without using C++. */
  961. PyVarObject_HEAD_INIT(NULL, 0)
  962. "select.devpoll", /*tp_name*/
  963. sizeof(devpollObject), /*tp_basicsize*/
  964. 0, /*tp_itemsize*/
  965. /* methods */
  966. (destructor)devpoll_dealloc, /*tp_dealloc*/
  967. 0, /*tp_print*/
  968. 0, /*tp_getattr*/
  969. 0, /*tp_setattr*/
  970. 0, /*tp_reserved*/
  971. 0, /*tp_repr*/
  972. 0, /*tp_as_number*/
  973. 0, /*tp_as_sequence*/
  974. 0, /*tp_as_mapping*/
  975. 0, /*tp_hash*/
  976. 0, /*tp_call*/
  977. 0, /*tp_str*/
  978. 0, /*tp_getattro*/
  979. 0, /*tp_setattro*/
  980. 0, /*tp_as_buffer*/
  981. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  982. 0, /*tp_doc*/
  983. 0, /*tp_traverse*/
  984. 0, /*tp_clear*/
  985. 0, /*tp_richcompare*/
  986. 0, /*tp_weaklistoffset*/
  987. 0, /*tp_iter*/
  988. 0, /*tp_iternext*/
  989. devpoll_methods, /*tp_methods*/
  990. 0, /* tp_members */
  991. devpoll_getsetlist, /* tp_getset */
  992. };
  993. #endif /* HAVE_SYS_DEVPOLL_H */
  994. PyDoc_STRVAR(poll_doc,
  995. "Returns a polling object, which supports registering and\n\
  996. unregistering file descriptors, and then polling them for I/O events.");
  997. static PyObject *
  998. select_poll(PyObject *self, PyObject *unused)
  999. {
  1000. return (PyObject *)newPollObject();
  1001. }
  1002. #ifdef HAVE_SYS_DEVPOLL_H
  1003. PyDoc_STRVAR(devpoll_doc,
  1004. "Returns a polling object, which supports registering and\n\
  1005. unregistering file descriptors, and then polling them for I/O events.");
  1006. static PyObject *
  1007. select_devpoll(PyObject *self, PyObject *unused)
  1008. {
  1009. return (PyObject *)newDevPollObject();
  1010. }
  1011. #endif
  1012. #ifdef __APPLE__
  1013. /*
  1014. * On some systems poll() sets errno on invalid file descriptors. We test
  1015. * for this at runtime because this bug may be fixed or introduced between
  1016. * OS releases.
  1017. */
  1018. static int select_have_broken_poll(void)
  1019. {
  1020. int poll_test;
  1021. int filedes[2];
  1022. struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };
  1023. /* Create a file descriptor to make invalid */
  1024. if (pipe(filedes) < 0) {
  1025. return 1;
  1026. }
  1027. poll_struct.fd = filedes[0];
  1028. close(filedes[0]);
  1029. close(filedes[1]);
  1030. poll_test = poll(&poll_struct, 1, 0);
  1031. if (poll_test < 0) {
  1032. return 1;
  1033. } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
  1034. return 1;
  1035. }
  1036. return 0;
  1037. }
  1038. #endif /* __APPLE__ */
  1039. #endif /* HAVE_POLL */
  1040. #ifdef HAVE_EPOLL
  1041. /* **************************************************************************
  1042. * epoll interface for Linux 2.6
  1043. *
  1044. * Written by Christian Heimes
  1045. * Inspired by Twisted's _epoll.pyx and select.poll()
  1046. */
  1047. #ifdef HAVE_SYS_EPOLL_H
  1048. #include <sys/epoll.h>
  1049. #endif
  1050. typedef struct {
  1051. PyObject_HEAD
  1052. SOCKET epfd; /* epoll control file descriptor */
  1053. } pyEpoll_Object;
  1054. static PyTypeObject pyEpoll_Type;
  1055. #define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type))
  1056. static PyObject *
  1057. pyepoll_err_closed(void)
  1058. {
  1059. PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll object");
  1060. return NULL;
  1061. }
  1062. static int
  1063. pyepoll_internal_close(pyEpoll_Object *self)
  1064. {
  1065. int save_errno = 0;
  1066. if (self->epfd >= 0) {
  1067. int epfd = self->epfd;
  1068. self->epfd = -1;
  1069. Py_BEGIN_ALLOW_THREADS
  1070. if (close(epfd) < 0)
  1071. save_errno = errno;
  1072. Py_END_ALLOW_THREADS
  1073. }
  1074. return save_errno;
  1075. }
  1076. static PyObject *
  1077. newPyEpoll_Object(PyTypeObject *type, int sizehint, int flags, SOCKET fd)
  1078. {
  1079. pyEpoll_Object *self;
  1080. assert(type != NULL && type->tp_alloc != NULL);
  1081. self = (pyEpoll_Object *) type->tp_alloc(type, 0);
  1082. if (self == NULL)
  1083. return NULL;
  1084. if (fd == -1) {
  1085. Py_BEGIN_ALLOW_THREADS
  1086. #ifdef HAVE_EPOLL_CREATE1
  1087. flags |= EPOLL_CLOEXEC;
  1088. if (flags)
  1089. self->epfd = epoll_create1(flags);
  1090. else
  1091. #endif
  1092. self->epfd = epoll_create(sizehint);
  1093. Py_END_ALLOW_THREADS
  1094. }
  1095. else {
  1096. self->epfd = fd;
  1097. }
  1098. if (self->epfd < 0) {
  1099. Py_DECREF(self);
  1100. PyErr_SetFromErrno(PyExc_OSError);
  1101. return NULL;
  1102. }
  1103. #ifndef HAVE_EPOLL_CREATE1
  1104. if (fd == -1 && _Py_set_inheritable(self->epfd, 0, NULL) < 0) {
  1105. Py_DECREF(self);
  1106. return NULL;
  1107. }
  1108. #endif
  1109. return (PyObject *)self;
  1110. }
  1111. static PyObject *
  1112. pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1113. {
  1114. int flags = 0, sizehint = FD_SETSIZE - 1;
  1115. static char *kwlist[] = {"sizehint", "flags", NULL};
  1116. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:epoll", kwlist,
  1117. &sizehint, &flags))
  1118. return NULL;
  1119. if (sizehint < 0) {
  1120. PyErr_SetString(PyExc_ValueError, "negative sizehint");
  1121. return NULL;
  1122. }
  1123. return newPyEpoll_Object(type, sizehint, flags, -1);
  1124. }
  1125. static void
  1126. pyepoll_dealloc(pyEpoll_Object *self)
  1127. {
  1128. (void)pyepoll_internal_close(self);
  1129. Py_TYPE(self)->tp_free(self);
  1130. }
  1131. static PyObject*
  1132. pyepoll_close(pyEpoll_Object *self)
  1133. {
  1134. errno = pyepoll_internal_close(self);
  1135. if (errno < 0) {
  1136. PyErr_SetFromErrno(PyExc_OSError);
  1137. return NULL;
  1138. }
  1139. Py_RETURN_NONE;
  1140. }
  1141. PyDoc_STRVAR(pyepoll_close_doc,
  1142. "close() -> None\n\
  1143. \n\
  1144. Close the epoll control file descriptor. Further operations on the epoll\n\
  1145. object will raise an exception.");
  1146. static PyObject*
  1147. pyepoll_get_closed(pyEpoll_Object *self)
  1148. {
  1149. if (self->epfd < 0)
  1150. Py_RETURN_TRUE;
  1151. else
  1152. Py_RETURN_FALSE;
  1153. }
  1154. static PyObject*
  1155. pyepoll_fileno(pyEpoll_Object *self)
  1156. {
  1157. if (self->epfd < 0)
  1158. return pyepoll_err_closed();
  1159. return PyLong_FromLong(self->epfd);
  1160. }
  1161. PyDoc_STRVAR(pyepoll_fileno_doc,
  1162. "fileno() -> int\n\
  1163. \n\
  1164. Return the epoll control file descriptor.");
  1165. static PyObject*
  1166. pyepoll_fromfd(PyObject *cls, PyObject *args)
  1167. {
  1168. SOCKET fd;
  1169. if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
  1170. return NULL;
  1171. return newPyEpoll_Object((PyTypeObject*)cls, FD_SETSIZE - 1, 0, fd);
  1172. }
  1173. PyDoc_STRVAR(pyepoll_fromfd_doc,
  1174. "fromfd(fd) -> epoll\n\
  1175. \n\
  1176. Create an epoll object from a given control fd.");
  1177. static PyObject *
  1178. pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events)
  1179. {
  1180. struct epoll_event ev;
  1181. int result;
  1182. int fd;
  1183. if (epfd < 0)
  1184. return pyepoll_err_closed();
  1185. fd = PyObject_AsFileDescriptor(pfd);
  1186. if (fd == -1) {
  1187. return NULL;
  1188. }
  1189. switch (op) {
  1190. case EPOLL_CTL_ADD:
  1191. case EPOLL_CTL_MOD:
  1192. ev.events = events;
  1193. ev.data.fd = fd;
  1194. Py_BEGIN_ALLOW_THREADS
  1195. result = epoll_ctl(epfd, op, fd, &ev);
  1196. Py_END_ALLOW_THREADS
  1197. break;
  1198. case EPOLL_CTL_DEL:
  1199. /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
  1200. * operation required a non-NULL pointer in event, even
  1201. * though this argument is ignored. */
  1202. Py_BEGIN_ALLOW_THREADS
  1203. result = epoll_ctl(epfd, op, fd, &ev);
  1204. if (errno == EBADF) {
  1205. /* fd already closed */
  1206. result = 0;
  1207. errno = 0;
  1208. }
  1209. Py_END_ALLOW_THREADS
  1210. break;
  1211. default:
  1212. result = -1;
  1213. errno = EINVAL;
  1214. }
  1215. if (result < 0) {
  1216. PyErr_SetFromErrno(PyExc_OSError);
  1217. return NULL;
  1218. }
  1219. Py_RETURN_NONE;
  1220. }
  1221. static PyObject *
  1222. pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
  1223. {
  1224. PyObject *pfd;
  1225. unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;
  1226. static char *kwlist[] = {"fd", "eventmask", NULL};
  1227. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
  1228. &pfd, &events)) {
  1229. return NULL;
  1230. }
  1231. return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
  1232. }
  1233. PyDoc_STRVAR(pyepoll_register_doc,
  1234. "register(fd[, eventmask]) -> None\n\
  1235. \n\
  1236. Registers a new fd or raises an OSError if the fd is already registered.\n\
  1237. fd is the target file descriptor of the operation.\n\
  1238. events is a bit set composed of the various EPOLL constants; the default\n\
  1239. is EPOLLIN | EPOLLOUT | EPOLLPRI.\n\
  1240. \n\
  1241. The epoll interface supports all file descriptors that support poll.");
  1242. static PyObject *
  1243. pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
  1244. {
  1245. PyObject *pfd;
  1246. unsigned int events;
  1247. static char *kwlist[] = {"fd", "eventmask", NULL};
  1248. if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
  1249. &pfd, &events)) {
  1250. return NULL;
  1251. }
  1252. return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
  1253. }
  1254. PyDoc_STRVAR(pyepoll_modify_doc,
  1255. "modify(fd, eventmask) -> None\n\
  1256. \n\
  1257. fd is the target file descriptor of the operation\n\
  1258. events is a bit set composed of the various EPOLL constants");
  1259. static PyObject *
  1260. pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
  1261. {
  1262. PyObject *pfd;
  1263. static char *kwlist[] = {"fd", NULL};
  1264. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
  1265. &pfd)) {
  1266. return NULL;
  1267. }
  1268. return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
  1269. }
  1270. PyDoc_STRVAR(pyepoll_unregister_doc,
  1271. "unregister(fd) -> None\n\
  1272. \n\
  1273. fd is the target file descriptor of the operation.");
  1274. static PyObject *
  1275. pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
  1276. {
  1277. static char *kwlist[] = {"timeout", "maxevents", NULL};
  1278. PyObject *timeout_obj = NULL;
  1279. int maxevents = -1;
  1280. int nfds, i;
  1281. PyObject *elist = NULL, *etuple = NULL;
  1282. struct epoll_event *evs = NULL;
  1283. _PyTime_t timeout, ms, deadline;
  1284. if (self->epfd < 0)
  1285. return pyepoll_err_closed();
  1286. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:poll", kwlist,
  1287. &timeout_obj, &maxevents)) {
  1288. return NULL;
  1289. }
  1290. if (timeout_obj == NULL || timeout_obj == Py_None) {
  1291. timeout = -1;
  1292. ms = -1;
  1293. deadline = 0; /* initialize to prevent gcc warning */
  1294. }
  1295. else {
  1296. /* epoll_wait() has a resolution of 1 millisecond, round towards
  1297. infinity to wait at least timeout seconds. */
  1298. if (_PyTime_FromSecondsObject(&timeout, timeout_obj,
  1299. _PyTime_ROUND_CEILING) < 0) {
  1300. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  1301. PyErr_SetString(PyExc_TypeError,
  1302. "timeout must be an integer or None");
  1303. }
  1304. return NULL;
  1305. }
  1306. ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
  1307. if (ms < INT_MIN || ms > INT_MAX) {
  1308. PyErr_SetString(PyExc_OverflowError, "timeout is too large");
  1309. return NULL;
  1310. }
  1311. deadline = _PyTime_GetMonotonicClock() + timeout;
  1312. }
  1313. if (maxevents == -1) {
  1314. maxevents = FD_SETSIZE-1;
  1315. }
  1316. else if (maxevents < 1) {
  1317. PyErr_Format(PyExc_ValueError,
  1318. "maxevents must be greater than 0, got %d",
  1319. maxevents);
  1320. return NULL;
  1321. }
  1322. evs = PyMem_New(struct epoll_event, maxevents);
  1323. if (evs == NULL) {
  1324. PyErr_NoMemory();
  1325. return NULL;
  1326. }
  1327. do {
  1328. Py_BEGIN_ALLOW_THREADS
  1329. errno = 0;
  1330. nfds = epoll_wait(self->epfd, evs, maxevents, (int)ms);
  1331. Py_END_ALLOW_THREADS
  1332. if (errno != EINTR)
  1333. break;
  1334. /* poll() was interrupted by a signal */
  1335. if (PyErr_CheckSignals())
  1336. goto error;
  1337. if (timeout >= 0) {
  1338. timeout = deadline - _PyTime_GetMonotonicClock();
  1339. if (timeout < 0) {
  1340. nfds = 0;
  1341. break;
  1342. }
  1343. ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
  1344. /* retry epoll_wait() with the recomputed timeout */
  1345. }
  1346. } while(1);
  1347. if (nfds < 0) {
  1348. PyErr_SetFromErrno(PyExc_OSError);
  1349. goto error;
  1350. }
  1351. elist = PyList_New(nfds);
  1352. if (elist == NULL) {
  1353. goto error;
  1354. }
  1355. for (i = 0; i < nfds; i++) {
  1356. etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
  1357. if (etuple == NULL) {
  1358. Py_CLEAR(elist);
  1359. goto error;
  1360. }
  1361. PyList_SET_ITEM(elist, i, etuple);
  1362. }
  1363. error:
  1364. PyMem_Free(evs);
  1365. return elist;
  1366. }
  1367. PyDoc_STRVAR(pyepoll_poll_doc,
  1368. "poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\
  1369. \n\
  1370. Wait for events on the epoll file descriptor for a maximum time of timeout\n\
  1371. in seconds (as float). -1 makes poll wait indefinitely.\n\
  1372. Up to maxevents are returned to the caller.");
  1373. static PyObject *
  1374. pyepoll_enter(pyEpoll_Object *self, PyObject *args)
  1375. {
  1376. if (self->epfd < 0)
  1377. return pyepoll_err_closed();
  1378. Py_INCREF(self);
  1379. return (PyObject *)self;
  1380. }
  1381. static PyObject *
  1382. pyepoll_exit(PyObject *self, PyObject *args)
  1383. {
  1384. _Py_IDENTIFIER(close);
  1385. return _PyObject_CallMethodId(self, &PyId_close, NULL);
  1386. }
  1387. static PyMethodDef pyepoll_methods[] = {
  1388. {"fromfd", (PyCFunction)pyepoll_fromfd,
  1389. METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},
  1390. {"close", (PyCFunction)pyepoll_close, METH_NOARGS,
  1391. pyepoll_close_doc},
  1392. {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS,
  1393. pyepoll_fileno_doc},
  1394. {"modify", (PyCFunction)pyepoll_modify,
  1395. METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc},
  1396. {"register", (PyCFunction)pyepoll_register,
  1397. METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc},
  1398. {"unregister", (PyCFunction)pyepoll_unregister,
  1399. METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc},
  1400. {"poll", (PyCFunction)pyepoll_poll,
  1401. METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc},
  1402. {"__enter__", (PyCFunction)pyepoll_enter, METH_NOARGS,
  1403. NULL},
  1404. {"__exit__", (PyCFunction)pyepoll_exit, METH_VARARGS,
  1405. NULL},
  1406. {NULL, NULL},
  1407. };
  1408. static PyGetSetDef pyepoll_getsetlist[] = {
  1409. {"closed", (getter)pyepoll_get_closed, NULL,
  1410. "True if the epoll handler is closed"},
  1411. {0},
  1412. };
  1413. PyDoc_STRVAR(pyepoll_doc,
  1414. "select.epoll(sizehint=-1, flags=0)\n\
  1415. \n\
  1416. Returns an epolling object\n\
  1417. \n\
  1418. sizehint must be a positive integer or -1 for the default size. The\n\
  1419. sizehint is used to optimize internal data structures. It doesn't limit\n\
  1420. the maximum number of monitored events.");
  1421. static PyTypeObject pyEpoll_Type = {
  1422. PyVarObject_HEAD_INIT(NULL, 0)
  1423. "select.epoll", /* tp_name */
  1424. sizeof(pyEpoll_Object), /* tp_basicsize */
  1425. 0, /* tp_itemsize */
  1426. (destructor)pyepoll_dealloc, /* tp_dealloc */
  1427. 0, /* tp_print */
  1428. 0, /* tp_getattr */
  1429. 0, /* tp_setattr */
  1430. 0, /* tp_reserved */
  1431. 0, /* tp_repr */
  1432. 0, /* tp_as_number */
  1433. 0, /* tp_as_sequence */
  1434. 0, /* tp_as_mapping */
  1435. 0, /* tp_hash */
  1436. 0, /* tp_call */
  1437. 0, /* tp_str */
  1438. PyObject_GenericGetAttr, /* tp_getattro */
  1439. 0, /* tp_setattro */
  1440. 0, /* tp_as_buffer */
  1441. Py_TPFLAGS_DEFAULT, /* tp_flags */
  1442. pyepoll_doc, /* tp_doc */
  1443. 0, /* tp_traverse */
  1444. 0, /* tp_clear */
  1445. 0, /* tp_richcompare */
  1446. 0, /* tp_weaklistoffset */
  1447. 0, /* tp_iter */
  1448. 0, /* tp_iternext */
  1449. pyepoll_methods, /* tp_methods */
  1450. 0, /* tp_members */
  1451. pyepoll_getsetlist, /* tp_getset */
  1452. 0, /* tp_base */
  1453. 0, /* tp_dict */
  1454. 0, /* tp_descr_get */
  1455. 0, /* tp_descr_set */
  1456. 0, /* tp_dictoffset */
  1457. 0, /* tp_init */
  1458. 0, /* tp_alloc */
  1459. pyepoll_new, /* tp_new */
  1460. 0, /* tp_free */
  1461. };
  1462. #endif /* HAVE_EPOLL */
  1463. #ifdef HAVE_KQUEUE
  1464. /* **************************************************************************
  1465. * kqueue interface for BSD
  1466. *
  1467. * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
  1468. * All rights reserved.
  1469. *
  1470. * Redistribution and use in source and binary forms, with or without
  1471. * modification, are permitted provided that the following conditions
  1472. * are met:
  1473. * 1. Redistributions of source code must retain the above copyright
  1474. * notice, this list of conditions and the following disclaimer.
  1475. * 2. Redistributions in binary form must reproduce the above copyright
  1476. * notice, this list of conditions and the following disclaimer in the
  1477. * documentation and/or other materials provided with the distribution.
  1478. *
  1479. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  1480. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  1481. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  1482. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  1483. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  1484. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  1485. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  1486. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  1487. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  1488. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  1489. * SUCH DAMAGE.
  1490. */
  1491. #ifdef HAVE_SYS_EVENT_H
  1492. #include <sys/event.h>
  1493. #endif
  1494. PyDoc_STRVAR(kqueue_event_doc,
  1495. "kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\
  1496. \n\
  1497. This object is the equivalent of the struct kevent for the C API.\n\
  1498. \n\
  1499. See the kqueue manpage for more detailed information about the meaning\n\
  1500. of the arguments.\n\
  1501. \n\
  1502. One minor note: while you might hope that udata could store a\n\
  1503. reference to a python object, it cannot, because it is impossible to\n\
  1504. keep a proper reference count of the object once it's passed into the\n\
  1505. kernel. Therefore, I have restricted it to only storing an integer. I\n\
  1506. recommend ignoring it and simply using the 'ident' field to key off\n\
  1507. of. You could also set up a diction

Large files files are truncated, but you can click here to view the full file