BReactor.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. /**
  2. * @file BReactor.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * Event loop that supports file desciptor (Linux) or HANDLE (Windows) events
  25. * and timers.
  26. */
  27. #ifndef BADVPN_SYSTEM_BREACTOR_H
  28. #define BADVPN_SYSTEM_BREACTOR_H
  29. #if (defined(BADVPN_USE_WINAPI) + defined(BADVPN_USE_EPOLL) + defined(BADVPN_USE_KEVENT) + defined(BADVPN_USE_POLL)) != 1
  30. #error Unknown event backend or too many event backends
  31. #endif
  32. #ifdef BADVPN_USE_WINAPI
  33. #include <windows.h>
  34. #endif
  35. #ifdef BADVPN_USE_EPOLL
  36. #include <sys/epoll.h>
  37. #endif
  38. #ifdef BADVPN_USE_KEVENT
  39. #include <sys/types.h>
  40. #include <sys/event.h>
  41. #include <sys/time.h>
  42. #endif
  43. #ifdef BADVPN_USE_POLL
  44. #include <poll.h>
  45. #endif
  46. #include <stdint.h>
  47. #include <misc/debug.h>
  48. #include <misc/debugcounter.h>
  49. #include <base/DebugObject.h>
  50. #include <structure/LinkedList1.h>
  51. #include <structure/BHeap.h>
  52. #include <system/BTime.h>
  53. #include <base/BPending.h>
  54. struct BTimer_t;
  55. /**
  56. * Handler function invoked when the timer expires.
  57. * The timer was in running state.
  58. * The timer enters not running state before this function is invoked.
  59. * This function is being called from within the timer's previosly
  60. * associated reactor.
  61. *
  62. * @param user value passed to {@link BTimer_Init}
  63. */
  64. typedef void (*BTimer_handler) (void *user);
  65. /**
  66. * Timer object used with {@link BReactor}.
  67. */
  68. typedef struct BTimer_t {
  69. btime_t msTime;
  70. BTimer_handler handler;
  71. void *handler_pointer;
  72. uint8_t active;
  73. uint8_t expired;
  74. btime_t absTime;
  75. union {
  76. BHeapNode heap_node;
  77. LinkedList1Node list_node;
  78. };
  79. } BTimer;
  80. /**
  81. * Initializes the timer object.
  82. * The timer object is initialized in not running state.
  83. *
  84. * @param bt the object
  85. * @param msTime default timeout in milliseconds
  86. * @param handler handler function invoked when the timer expires
  87. * @param user value to pass to the handler function
  88. */
  89. void BTimer_Init (BTimer *bt, btime_t msTime, BTimer_handler handler, void *user);
  90. /**
  91. * Checks if the timer is running.
  92. *
  93. * @param bt the object
  94. * @return 1 if running, 0 if not running
  95. */
  96. int BTimer_IsRunning (BTimer *bt);
  97. #ifndef BADVPN_USE_WINAPI
  98. struct BFileDescriptor_t;
  99. #define BREACTOR_READ (1 << 0)
  100. #define BREACTOR_WRITE (1 << 1)
  101. #define BREACTOR_ERROR (1 << 2)
  102. /**
  103. * Handler function invoked by the reactor when one or more events are detected.
  104. * The events argument will contain a subset of the monitored events (BREACTOR_READ, BREACTOR_WRITE),
  105. * plus possibly the error event (BREACTOR_ERROR).
  106. * The file descriptor object is in active state, being called from within
  107. * the associated reactor.
  108. *
  109. * @param user value passed to {@link BFileDescriptor_Init}
  110. * @param events bitmask composed of a subset of monitored events (BREACTOR_READ, BREACTOR_WRITE),
  111. * and possibly the error event (BREACTOR_ERROR).
  112. * Will be nonzero.
  113. */
  114. typedef void (*BFileDescriptor_handler) (void *user, int events);
  115. /**
  116. * File descriptor object used with {@link BReactor}.
  117. */
  118. typedef struct BFileDescriptor_t {
  119. int fd;
  120. BFileDescriptor_handler handler;
  121. void *user;
  122. int active;
  123. int waitEvents;
  124. #ifdef BADVPN_USE_EPOLL
  125. struct BFileDescriptor_t **epoll_returned_ptr;
  126. #endif
  127. #ifdef BADVPN_USE_KEVENT
  128. int kevent_tag;
  129. int **kevent_returned_ptr;
  130. #endif
  131. #ifdef BADVPN_USE_POLL
  132. LinkedList1Node poll_enabled_fds_list_node;
  133. int poll_returned_index;
  134. #endif
  135. } BFileDescriptor;
  136. /**
  137. * Intializes the file descriptor object.
  138. * The object is initialized in not active state.
  139. *
  140. * @param bs file descriptor object to initialize
  141. * @param fb file descriptor to represent
  142. * @param handler handler function invoked by the reactor when a monitored event is detected
  143. * @param user value passed to the handler functuon
  144. */
  145. void BFileDescriptor_Init (BFileDescriptor *bs, int fd, BFileDescriptor_handler handler, void *user);
  146. #endif
  147. // BReactor
  148. #define BSYSTEM_MAX_RESULTS 64
  149. #define BSYSTEM_MAX_HANDLES 64
  150. #define BSYSTEM_MAX_POLL_FDS 4096
  151. /**
  152. * Event loop that supports file desciptor (Linux) or HANDLE (Windows) events
  153. * and timers.
  154. */
  155. typedef struct {
  156. int exiting;
  157. int exit_code;
  158. // jobs
  159. BPendingGroup pending_jobs;
  160. // timers
  161. BHeap timers_heap;
  162. LinkedList1 timers_expired_list;
  163. // limits
  164. LinkedList1 active_limits_list;
  165. #ifdef BADVPN_USE_WINAPI
  166. LinkedList1 iocp_list;
  167. HANDLE iocp_handle;
  168. LinkedList1 iocp_ready_list;
  169. #endif
  170. #ifdef BADVPN_USE_EPOLL
  171. int efd; // epoll fd
  172. struct epoll_event epoll_results[BSYSTEM_MAX_RESULTS]; // epoll returned events buffer
  173. int epoll_results_num; // number of events in the array
  174. int epoll_results_pos; // number of events processed so far
  175. #endif
  176. #ifdef BADVPN_USE_KEVENT
  177. int kqueue_fd;
  178. struct kevent kevent_results[BSYSTEM_MAX_RESULTS];
  179. int kevent_results_num;
  180. int kevent_results_pos;
  181. #endif
  182. #ifdef BADVPN_USE_POLL
  183. LinkedList1 poll_enabled_fds_list;
  184. int poll_num_enabled_fds;
  185. int poll_results_num;
  186. int poll_results_pos;
  187. struct pollfd *poll_results_pollfds;
  188. BFileDescriptor **poll_results_bfds;
  189. #endif
  190. DebugObject d_obj;
  191. #ifndef BADVPN_USE_WINAPI
  192. DebugCounter d_fds_counter;
  193. #endif
  194. #ifdef BADVPN_USE_KEVENT
  195. DebugCounter d_kevent_ctr;
  196. #endif
  197. DebugCounter d_limits_ctr;
  198. } BReactor;
  199. /**
  200. * Initializes the reactor.
  201. * {@link BLog_Init} must have been done.
  202. * {@link BTime_Init} must have been done.
  203. *
  204. * @param bsys the object
  205. * @return 1 on success, 0 on failure
  206. */
  207. int BReactor_Init (BReactor *bsys) WARN_UNUSED;
  208. /**
  209. * Frees the reactor.
  210. * Must not be called from within the event loop ({@link BReactor_Exec}).
  211. * There must be no {@link BPending} objects using the pending group
  212. * returned by {@link BReactor_PendingGroup}.
  213. * There must be no running timers in this reactor.
  214. * There must be no limit objects in this reactor.
  215. * There must be no file descriptors or handles registered
  216. * with this reactor.
  217. * There must be no {@link BReactorKEvent} objects in this reactor.
  218. *
  219. * @param bsys the object
  220. */
  221. void BReactor_Free (BReactor *bsys);
  222. /**
  223. * Runs the event loop.
  224. *
  225. * @param bsys the object
  226. * @return value passed to {@link BReactor_Quit}
  227. */
  228. int BReactor_Exec (BReactor *bsys);
  229. /**
  230. * Causes the event loop ({@link BReactor_Exec}) to cease
  231. * dispatching events and return.
  232. * Any further calls of {@link BReactor_Exec} will return immediately.
  233. *
  234. * @param bsys the object
  235. * @param code value {@link BReactor_Exec} should return. If this is
  236. * called more than once, it will return the last code.
  237. */
  238. void BReactor_Quit (BReactor *bsys, int code);
  239. /**
  240. * Starts a timer to expire after its default time.
  241. * The timer must have been initialized with {@link BTimer_Init}.
  242. * If the timer is in running state, it must be associated with this reactor.
  243. * The timer enters running state, associated with this reactor.
  244. *
  245. * @param bsys the object
  246. * @param bt timer to start
  247. */
  248. void BReactor_SetTimer (BReactor *bsys, BTimer *bt);
  249. /**
  250. * Starts a timer to expire after a given time.
  251. * The timer must have been initialized with {@link BTimer_Init}.
  252. * If the timer is in running state, it must be associated with this reactor.
  253. * The timer enters running state, associated with this reactor.
  254. *
  255. * @param bsys the object
  256. * @param bt timer to start
  257. * @param after relative expiration time
  258. */
  259. void BReactor_SetTimerAfter (BReactor *bsys, BTimer *bt, btime_t after);
  260. /**
  261. * Starts a timer to expire at the specified time.
  262. * The timer must have been initialized with {@link BTimer_Init}.
  263. * If the timer is in running state, it must be associated with this reactor.
  264. * The timer enters running state, associated with this reactor.
  265. * The timer's expiration time is set to the time argument.
  266. *
  267. * @param bsys the object
  268. * @param bt timer to start
  269. * @param time absolute expiration time (according to {@link btime_gettime})
  270. */
  271. void BReactor_SetTimerAbsolute (BReactor *bsys, BTimer *bt, btime_t time);
  272. /**
  273. * Stops a timer.
  274. * If the timer is in running state, it must be associated with this reactor.
  275. * The timer enters not running state.
  276. *
  277. * @param bsys the object
  278. * @param bt timer to stop
  279. */
  280. void BReactor_RemoveTimer (BReactor *bsys, BTimer *bt);
  281. /**
  282. * Returns a {@link BPendingGroup} object that can be used to schedule jobs for
  283. * the reactor to execute. These jobs have complete priority over other events
  284. * (timers, file descriptors and Windows handles).
  285. * The returned pending group may only be used as an argument to {@link BPending_Init},
  286. * and must not be accessed by other means.
  287. * All {@link BPending} objects using this group must be freed before freeing
  288. * the reactor.
  289. *
  290. * @param bsys the object
  291. * @return pending group for scheduling jobs for the reactor to execute
  292. */
  293. BPendingGroup * BReactor_PendingGroup (BReactor *bsys);
  294. /**
  295. * Executes pending jobs until either:
  296. * - the reference job is reached, or
  297. * - {@link BReactor_Quit} is called.
  298. * The reference job must be reached before the job list empties.
  299. * The reference job will not be executed.
  300. *
  301. * WARNING: Use with care. This should only be used to to work around third-party software
  302. * that does not integrade into the jobs system. In particular, you should think about:
  303. * - the effects the jobs to be executed may have, and
  304. * - the environment those jobs expect to be executed in.
  305. *
  306. * @param bsys the object
  307. * @param ref reference job. It is not accessed in any way, only its address is compared to
  308. * pending jobs before they are executed.
  309. * @return 1 if the reference job was reached,
  310. * 0 if {@link BReactor_Quit} was called (either while executing a job, or before)
  311. */
  312. int BReactor_Synchronize (BReactor *bsys, BPending *ref);
  313. #ifndef BADVPN_USE_WINAPI
  314. /**
  315. * Starts monitoring a file descriptor.
  316. *
  317. * @param bsys the object
  318. * @param bs file descriptor object. Must have been initialized with
  319. * {@link BFileDescriptor_Init} Must be in not active state.
  320. * On success, the file descriptor object enters active state,
  321. * associated with this reactor.
  322. * @return 1 on success, 0 on failure
  323. */
  324. int BReactor_AddFileDescriptor (BReactor *bsys, BFileDescriptor *bs) WARN_UNUSED;
  325. /**
  326. * Stops monitoring a file descriptor.
  327. *
  328. * @param bsys the object
  329. * @param bs {@link BFileDescriptor} object. Must be in active state,
  330. * associated with this reactor. The file descriptor object
  331. * enters not active state.
  332. */
  333. void BReactor_RemoveFileDescriptor (BReactor *bsys, BFileDescriptor *bs);
  334. /**
  335. * Sets monitored file descriptor events.
  336. *
  337. * @param bsys the object
  338. * @param bs {@link BFileDescriptor} object. Must be in active state,
  339. * associated with this reactor.
  340. * @param events events to watch for. Must not have any bits other than
  341. * BREACTOR_READ and BREACTOR_WRITE.
  342. * This overrides previosly monitored events.
  343. */
  344. void BReactor_SetFileDescriptorEvents (BReactor *bsys, BFileDescriptor *bs, int events);
  345. #endif
  346. typedef struct {
  347. BReactor *reactor;
  348. int limit;
  349. int count;
  350. LinkedList1Node active_limits_list_node;
  351. DebugObject d_obj;
  352. } BReactorLimit;
  353. /**
  354. * Initializes a limit object.
  355. * A limit object consists of a counter integer, which is initialized to
  356. * zero, is incremented by {@link BReactorLimit_Increment} up to \a limit,
  357. * and is reset to zero every time the event loop performs a wait.
  358. * If the event loop has processed all detected events, and before performing
  359. * a wait, it determines that timers have expired, the counter will not be reset.
  360. *
  361. * @param o the object
  362. * @param reactor reactor the object is tied to
  363. * @param limit maximum counter value. Must be >0.
  364. */
  365. void BReactorLimit_Init (BReactorLimit *o, BReactor *reactor, int limit);
  366. /**
  367. * Frees a limit object.
  368. *
  369. * @param o the object
  370. */
  371. void BReactorLimit_Free (BReactorLimit *o);
  372. /**
  373. * Attempts to increment the counter of a limit object.
  374. *
  375. * @param o the object
  376. * @return 1 if the counter was lesser than the limit and was incremented,
  377. * 0 if the counter was greater or equal to the limit and could not be
  378. * incremented
  379. */
  380. int BReactorLimit_Increment (BReactorLimit *o);
  381. /**
  382. * Sets the limit of a limit object.
  383. *
  384. * @param o the object
  385. * @param limit new limit. Must be >0.
  386. */
  387. void BReactorLimit_SetLimit (BReactorLimit *o, int limit);
  388. #ifdef BADVPN_USE_KEVENT
  389. typedef void (*BReactorKEvent_handler) (void *user, u_int fflags, intptr_t data);
  390. typedef struct {
  391. BReactor *reactor;
  392. BReactorKEvent_handler handler;
  393. void *user;
  394. uintptr_t ident;
  395. short filter;
  396. int kevent_tag;
  397. int **kevent_returned_ptr;
  398. DebugObject d_obj;
  399. } BReactorKEvent;
  400. int BReactorKEvent_Init (BReactorKEvent *o, BReactor *reactor, BReactorKEvent_handler handler, void *user, uintptr_t ident, short filter, u_int fflags, intptr_t data);
  401. void BReactorKEvent_Free (BReactorKEvent *o);
  402. #endif
  403. #ifdef BADVPN_USE_WINAPI
  404. #define BREACTOR_IOCP_EVENT_SUCCEEDED 1
  405. #define BREACTOR_IOCP_EVENT_FAILED 2
  406. #define BREACTOR_IOCP_EVENT_EXITING 3
  407. typedef void (*BReactorIOCPOverlapped_handler) (void *user, int event, DWORD bytes);
  408. typedef struct {
  409. OVERLAPPED olap;
  410. BReactor *reactor;
  411. void *user;
  412. BReactorIOCPOverlapped_handler handler;
  413. LinkedList1Node iocp_list_node;
  414. int is_ready;
  415. LinkedList1Node ready_list_node;
  416. int ready_succeeded;
  417. DWORD ready_bytes;
  418. DebugObject d_obj;
  419. } BReactorIOCPOverlapped;
  420. HANDLE BReactor_GetIOCPHandle (BReactor *reactor);
  421. void BReactorIOCPOverlapped_Init (BReactorIOCPOverlapped *o, BReactor *reactor, void *user, BReactorIOCPOverlapped_handler handler);
  422. void BReactorIOCPOverlapped_Free (BReactorIOCPOverlapped *o);
  423. void BReactorIOCPOverlapped_Wait (BReactorIOCPOverlapped *o, int *out_succeeded, DWORD *out_bytes);
  424. #endif
  425. #endif