BReactor_badvpn.h 15 KB

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