PageRenderTime 47ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/Modules/selectmodule.c

https://bitbucket.org/arigo/cpython-withatomic/
C | 2293 lines | 1853 code | 295 blank | 145 comment | 312 complexity | 8a6685c2978f18051d8384de76b1763d MD5 | raw file
Possible License(s): 0BSD

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

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