BReactor_badvpn.h 18 KB

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