BReactor_badvpn.h 17 KB

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