fakepoll.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /* Copyright 2002,2003 Nick Mathewson, Roger Dingledine */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char fakepoll_c_id[] = "$Id$";
  5. /**
  6. * \file fakepoll.c
  7. *
  8. * \brief On systems where poll() doesn't exist, fake it with select().
  9. **/
  10. #include "orconfig.h"
  11. #include "fakepoll.h"
  12. #define MAXCONNECTIONS 10000 /* XXXX copied from or.h */
  13. #define FD_SETSIZE MAXCONNECTIONS
  14. #ifdef HAVE_SYS_TYPES_H
  15. #include <sys/types.h>
  16. #endif
  17. #ifdef HAVE_UNISTD_H
  18. #include <unistd.h>
  19. #endif
  20. #ifdef HAVE_STRING_H
  21. #include <string.h>
  22. #endif
  23. #ifdef HAVE_SYS_TIME_H
  24. #include <sys/time.h>
  25. #endif
  26. #include <assert.h>
  27. #include <stdlib.h>
  28. #include "util.h"
  29. #include "log.h"
  30. #ifndef USE_FAKE_POLL
  31. int
  32. tor_poll(struct pollfd *ufds, unsigned int nfds, int timeout)
  33. {
  34. unsigned int i;
  35. for (i=0;i<nfds;++i) {
  36. tor_assert(ufds[i].fd >= 0);
  37. }
  38. return poll(ufds,nfds,timeout);
  39. }
  40. #else
  41. int
  42. tor_poll(struct pollfd *ufds, unsigned int nfds, int timeout)
  43. {
  44. unsigned int idx;
  45. int maxfd, fd;
  46. int r;
  47. #ifdef MS_WINDOWS
  48. int any_fds_set = 0;
  49. #endif
  50. fd_set readfds, writefds, exceptfds;
  51. #ifdef USING_FAKE_TIMEVAL
  52. #undef timeval
  53. #undef tv_sec
  54. #undef tv_usec
  55. #endif
  56. struct timeval _timeout;
  57. _timeout.tv_sec = timeout/1000;
  58. _timeout.tv_usec = (timeout%1000)*1000;
  59. FD_ZERO(&readfds);
  60. FD_ZERO(&writefds);
  61. FD_ZERO(&exceptfds);
  62. maxfd = -1;
  63. for (idx = 0; idx < nfds; ++idx) {
  64. ufds[idx].revents = 0;
  65. fd = ufds[idx].fd;
  66. tor_assert(fd >= 0);
  67. if (fd > maxfd) {
  68. maxfd = fd;
  69. #ifdef MS_WINDOWS
  70. any_fds_set = 1;
  71. #endif
  72. }
  73. if (ufds[idx].events & POLLIN)
  74. FD_SET(fd, &readfds);
  75. if (ufds[idx].events & POLLOUT)
  76. FD_SET(fd, &writefds);
  77. FD_SET(fd, &exceptfds);
  78. }
  79. #ifdef MS_WINDOWS
  80. if (!any_fds_set) {
  81. Sleep(timeout);
  82. return 0;
  83. }
  84. #endif
  85. r = select(maxfd+1, &readfds, &writefds, &exceptfds,
  86. timeout == -1 ? NULL : &_timeout);
  87. if (r <= 0)
  88. return r;
  89. r = 0;
  90. for (idx = 0; idx < nfds; ++idx) {
  91. fd = ufds[idx].fd;
  92. if (FD_ISSET(fd, &readfds))
  93. ufds[idx].revents |= POLLIN;
  94. if (FD_ISSET(fd, &writefds))
  95. ufds[idx].revents |= POLLOUT;
  96. if (FD_ISSET(fd, &exceptfds))
  97. ufds[idx].revents |= POLLERR;
  98. if (ufds[idx].revents)
  99. ++r;
  100. }
  101. return r;
  102. }
  103. #endif