BReactor.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. #ifdef BADVPN_USE_WINAPI
  98. /**
  99. * Handler function invoked by the reactor when the handle is signalled
  100. * The handle object is in active state, is being called from within
  101. * the associated reactor, and is in monitored state.
  102. *
  103. * @param user value passed to {@link BHandle_Init}
  104. */
  105. typedef void (*BHandle_handler) (void *user);
  106. struct BHandle_t;
  107. /**
  108. * Windows handle object used with {@link BReactor}.
  109. */
  110. typedef struct BHandle_t {
  111. HANDLE h;
  112. BHandle_handler handler;
  113. void *user;
  114. int active;
  115. int position;
  116. } BHandle;
  117. /**
  118. * Initializes the handle object.
  119. * The handle object is initialized in not active state.
  120. *
  121. * @param bh the object
  122. * @param handle underlying Windows handle
  123. * @param handler handler function invoked when the handle is signalled
  124. * @param user value to pass to the handler function
  125. */
  126. void BHandle_Init (BHandle *bh, HANDLE handle, BHandle_handler handler, void *user);
  127. #else
  128. struct BFileDescriptor_t;
  129. #define BREACTOR_READ (1 << 0)
  130. #define BREACTOR_WRITE (1 << 1)
  131. #define BREACTOR_ERROR (1 << 2)
  132. /**
  133. * Handler function invoked by the reactor when one or more events are detected.
  134. * The events argument will contain a subset of the monitored events (BREACTOR_READ, BREACTOR_WRITE),
  135. * plus possibly the error event (BREACTOR_ERROR).
  136. * The file descriptor object is in active state, being called from within
  137. * the associated reactor.
  138. *
  139. * @param user value passed to {@link BFileDescriptor_Init}
  140. * @param events bitmask composed of a subset of monitored events (BREACTOR_READ, BREACTOR_WRITE),
  141. * and possibly the error event (BREACTOR_ERROR).
  142. * Will be nonzero.
  143. */
  144. typedef void (*BFileDescriptor_handler) (void *user, int events);
  145. /**
  146. * File descriptor object used with {@link BReactor}.
  147. */
  148. typedef struct BFileDescriptor_t {
  149. int fd;
  150. BFileDescriptor_handler handler;
  151. void *user;
  152. int active;
  153. int waitEvents;
  154. #ifdef BADVPN_USE_EPOLL
  155. struct BFileDescriptor_t **epoll_returned_ptr;
  156. #endif
  157. #ifdef BADVPN_USE_KEVENT
  158. int kevent_tag;
  159. int **kevent_returned_ptr;
  160. #endif
  161. #ifdef BADVPN_USE_POLL
  162. LinkedList1Node poll_enabled_fds_list_node;
  163. int poll_returned_index;
  164. #endif
  165. } BFileDescriptor;
  166. /**
  167. * Intializes the file descriptor object.
  168. * The object is initialized in not active state.
  169. *
  170. * @param bs file descriptor object to initialize
  171. * @param fb file descriptor to represent
  172. * @param handler handler function invoked by the reactor when a monitored event is detected
  173. * @param user value passed to the handler functuon
  174. */
  175. void BFileDescriptor_Init (BFileDescriptor *bs, int fd, BFileDescriptor_handler handler, void *user);
  176. #endif
  177. // BReactor
  178. #define BSYSTEM_MAX_RESULTS 64
  179. #define BSYSTEM_MAX_HANDLES 64
  180. #define BSYSTEM_MAX_POLL_FDS 4096
  181. /**
  182. * Event loop that supports file desciptor (Linux) or HANDLE (Windows) events
  183. * and timers.
  184. */
  185. typedef struct {
  186. int exiting;
  187. int exit_code;
  188. // jobs
  189. BPendingGroup pending_jobs;
  190. // timers
  191. BHeap timers_heap;
  192. LinkedList1 timers_expired_list;
  193. // limits
  194. LinkedList1 active_limits_list;
  195. #ifdef BADVPN_USE_WINAPI
  196. int num_handles; // number of user handles
  197. int enabled_num; // number of user handles in the enabled array
  198. HANDLE enabled_handles[BSYSTEM_MAX_HANDLES]; // enabled user handles
  199. BHandle *enabled_objects[BSYSTEM_MAX_HANDLES]; // objects corresponding to enabled handles
  200. BHandle *returned_object;
  201. #endif
  202. #ifdef BADVPN_USE_EPOLL
  203. int efd; // epoll fd
  204. struct epoll_event epoll_results[BSYSTEM_MAX_RESULTS]; // epoll returned events buffer
  205. int epoll_results_num; // number of events in the array
  206. int epoll_results_pos; // number of events processed so far
  207. #endif
  208. #ifdef BADVPN_USE_KEVENT
  209. int kqueue_fd;
  210. struct kevent kevent_results[BSYSTEM_MAX_RESULTS];
  211. int kevent_results_num;
  212. int kevent_results_pos;
  213. #endif
  214. #ifdef BADVPN_USE_POLL
  215. LinkedList1 poll_enabled_fds_list;
  216. int poll_num_enabled_fds;
  217. int poll_results_num;
  218. int poll_results_pos;
  219. struct pollfd *poll_results_pollfds;
  220. BFileDescriptor **poll_results_bfds;
  221. #endif
  222. DebugObject d_obj;
  223. #ifndef BADVPN_USE_WINAPI
  224. DebugCounter d_fds_counter;
  225. #endif
  226. #ifdef BADVPN_USE_KEVENT
  227. DebugCounter d_kevent_ctr;
  228. #endif
  229. DebugCounter d_limits_ctr;
  230. } BReactor;
  231. /**
  232. * Initializes the reactor.
  233. * {@link BLog_Init} must have been done.
  234. * {@link BTime_Init} must have been done.
  235. *
  236. * @param bsys the object
  237. * @return 1 on success, 0 on failure
  238. */
  239. int BReactor_Init (BReactor *bsys) WARN_UNUSED;
  240. /**
  241. * Frees the reactor.
  242. * Must not be called from within the event loop ({@link BReactor_Exec}).
  243. * There must be no {@link BPending} objects using the pending group
  244. * returned by {@link BReactor_PendingGroup}.
  245. * There must be no running timers in this reactor.
  246. * There must be no limit objects in this reactor.
  247. * There must be no file descriptors or handles registered
  248. * with this reactor.
  249. * There must be no {@link BReactorKEvent} objects in this reactor.
  250. *
  251. * @param bsys the object
  252. */
  253. void BReactor_Free (BReactor *bsys);
  254. /**
  255. * Runs the event loop.
  256. *
  257. * @param bsys the object
  258. * @return value passed to {@link BReactor_Quit}
  259. */
  260. int BReactor_Exec (BReactor *bsys);
  261. /**
  262. * Causes the event loop ({@link BReactor_Exec}) to cease
  263. * dispatching events and return.
  264. * Any further calls of {@link BReactor_Exec} will return immediately.
  265. *
  266. * @param bsys the object
  267. * @param code value {@link BReactor_Exec} should return. If this is
  268. * called more than once, it will return the last code.
  269. */
  270. void BReactor_Quit (BReactor *bsys, int code);
  271. /**
  272. * Starts a timer to expire after its default time.
  273. * The timer must have been initialized with {@link BTimer_Init}.
  274. * If the timer is in running state, it must be associated with this reactor.
  275. * The timer enters running state, associated with this reactor.
  276. *
  277. * @param bsys the object
  278. * @param bt timer to start
  279. */
  280. void BReactor_SetTimer (BReactor *bsys, BTimer *bt);
  281. /**
  282. * Starts a timer to expire after a given time.
  283. * The timer must have been initialized with {@link BTimer_Init}.
  284. * If the timer is in running state, it must be associated with this reactor.
  285. * The timer enters running state, associated with this reactor.
  286. *
  287. * @param bsys the object
  288. * @param bt timer to start
  289. * @param after relative expiration time
  290. */
  291. void BReactor_SetTimerAfter (BReactor *bsys, BTimer *bt, btime_t after);
  292. /**
  293. * Starts a timer to expire at the specified time.
  294. * The timer must have been initialized with {@link BTimer_Init}.
  295. * If the timer is in running state, it must be associated with this reactor.
  296. * The timer enters running state, associated with this reactor.
  297. * The timer's expiration time is set to the time argument.
  298. *
  299. * @param bsys the object
  300. * @param bt timer to start
  301. * @param time absolute expiration time (according to {@link btime_gettime})
  302. */
  303. void BReactor_SetTimerAbsolute (BReactor *bsys, BTimer *bt, btime_t time);
  304. /**
  305. * Stops a timer.
  306. * If the timer is in running state, it must be associated with this reactor.
  307. * The timer enters not running state.
  308. *
  309. * @param bsys the object
  310. * @param bt timer to stop
  311. */
  312. void BReactor_RemoveTimer (BReactor *bsys, BTimer *bt);
  313. /**
  314. * Returns a {@link BPendingGroup} object that can be used to schedule jobs for
  315. * the reactor to execute. These jobs have complete priority over other events
  316. * (timers, file descriptors and Windows handles).
  317. * The returned pending group may only be used as an argument to {@link BPending_Init},
  318. * and must not be accessed by other means.
  319. * All {@link BPending} objects using this group must be freed before freeing
  320. * the reactor.
  321. *
  322. * @param bsys the object
  323. * @return pending group for scheduling jobs for the reactor to execute
  324. */
  325. BPendingGroup * BReactor_PendingGroup (BReactor *bsys);
  326. /**
  327. * Executes pending jobs until either:
  328. * - the reference job is reached, or
  329. * - {@link BReactor_Quit} is called.
  330. * The reference job must be reached before the job list empties.
  331. * The reference job will not be executed.
  332. *
  333. * WARNING: Use with care. This should only be used to to work around third-party software
  334. * that does not integrade into the jobs system. In particular, you should think about:
  335. * - the effects the jobs to be executed may have, and
  336. * - the environment those jobs expect to be executed in.
  337. *
  338. * @param bsys the object
  339. * @param ref reference job. It is not accessed in any way, only its address is compared to
  340. * pending jobs before they are executed.
  341. * @return 1 if the reference job was reached,
  342. * 0 if {@link BReactor_Quit} was called (either while executing a job, or before)
  343. */
  344. int BReactor_Synchronize (BReactor *bsys, BPending *ref);
  345. #ifdef BADVPN_USE_WINAPI
  346. /**
  347. * Registers a Windows handle to be monitored.
  348. *
  349. * @param bsys the object
  350. * @param bh handle object. Must have been initialized with {@link BHandle_Init}.
  351. * Must be in not active state. On success, the handle object enters
  352. * active state, associated with this reactor, and is initialized
  353. * to not monitored state.
  354. * @return 1 on success, 0 on failure
  355. */
  356. int BReactor_AddHandle (BReactor *bsys, BHandle *bh) WARN_UNUSED;
  357. /**
  358. * Unregisters a Windows handle.
  359. *
  360. * @param bsys the object
  361. * @param bh handle object. Must be in active state, associated with this reactor.
  362. * The handle object enters not active state.
  363. */
  364. void BReactor_RemoveHandle (BReactor *bsys, BHandle *bh);
  365. /**
  366. * Starts monitoring a Windows handle.
  367. *
  368. * @param bsys the object
  369. * @param bh handle object. Must be in active state, associated with this reactor.
  370. * Must be in not monitored state.
  371. * The handle object enters monitored state.
  372. */
  373. void BReactor_EnableHandle (BReactor *bsys, BHandle *bh);
  374. /**
  375. * Stops monitoring a Windows handle.
  376. *
  377. * @param bsys the object
  378. * @param bh handle object. Must be in active state, associated with this reactor.
  379. * Must be in monitored state.
  380. * The handle object enters not monitored state.
  381. */
  382. void BReactor_DisableHandle (BReactor *bsys, BHandle *bh);
  383. #else
  384. /**
  385. * Starts monitoring a file descriptor.
  386. *
  387. * @param bsys the object
  388. * @param bs file descriptor object. Must have been initialized with
  389. * {@link BFileDescriptor_Init} Must be in not active state.
  390. * On success, the file descriptor object enters active state,
  391. * associated with this reactor.
  392. * @return 1 on success, 0 on failure
  393. */
  394. int BReactor_AddFileDescriptor (BReactor *bsys, BFileDescriptor *bs) WARN_UNUSED;
  395. /**
  396. * Stops monitoring a file descriptor.
  397. *
  398. * @param bsys the object
  399. * @param bs {@link BFileDescriptor} object. Must be in active state,
  400. * associated with this reactor. The file descriptor object
  401. * enters not active state.
  402. */
  403. void BReactor_RemoveFileDescriptor (BReactor *bsys, BFileDescriptor *bs);
  404. /**
  405. * Sets monitored file descriptor events.
  406. *
  407. * @param bsys the object
  408. * @param bs {@link BFileDescriptor} object. Must be in active state,
  409. * associated with this reactor.
  410. * @param events events to watch for. Must not have any bits other than
  411. * BREACTOR_READ and BREACTOR_WRITE.
  412. * This overrides previosly monitored events.
  413. */
  414. void BReactor_SetFileDescriptorEvents (BReactor *bsys, BFileDescriptor *bs, int events);
  415. #endif
  416. typedef struct {
  417. BReactor *reactor;
  418. int limit;
  419. int count;
  420. LinkedList1Node active_limits_list_node;
  421. DebugObject d_obj;
  422. } BReactorLimit;
  423. /**
  424. * Initializes a limit object.
  425. * A limit object consists of a counter integer, which is initialized to
  426. * zero, is incremented by {@link BReactorLimit_Increment} up to \a limit,
  427. * and is reset to zero every time the event loop performs a wait.
  428. * If the event loop has processed all detected events, and before performing
  429. * a wait, it determines that timers have expired, the counter will not be reset.
  430. *
  431. * @param o the object
  432. * @param reactor reactor the object is tied to
  433. * @param limit maximum counter value. Must be >0.
  434. */
  435. void BReactorLimit_Init (BReactorLimit *o, BReactor *reactor, int limit);
  436. /**
  437. * Frees a limit object.
  438. *
  439. * @param o the object
  440. */
  441. void BReactorLimit_Free (BReactorLimit *o);
  442. /**
  443. * Attempts to increment the counter of a limit object.
  444. *
  445. * @param o the object
  446. * @return 1 if the counter was lesser than the limit and was incremented,
  447. * 0 if the counter was greater or equal to the limit and could not be
  448. * incremented
  449. */
  450. int BReactorLimit_Increment (BReactorLimit *o);
  451. /**
  452. * Sets the limit of a limit object.
  453. *
  454. * @param o the object
  455. * @param limit new limit. Must be >0.
  456. */
  457. void BReactorLimit_SetLimit (BReactorLimit *o, int limit);
  458. #ifdef BADVPN_USE_KEVENT
  459. typedef void (*BReactorKEvent_handler) (void *user, u_int fflags, intptr_t data);
  460. typedef struct {
  461. BReactor *reactor;
  462. BReactorKEvent_handler handler;
  463. void *user;
  464. uintptr_t ident;
  465. short filter;
  466. int kevent_tag;
  467. int **kevent_returned_ptr;
  468. DebugObject d_obj;
  469. } BReactorKEvent;
  470. int BReactorKEvent_Init (BReactorKEvent *o, BReactor *reactor, BReactorKEvent_handler handler, void *user, uintptr_t ident, short filter, u_int fflags, intptr_t data);
  471. void BReactorKEvent_Free (BReactorKEvent *o);
  472. #endif
  473. #endif