compat_libevent.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /* Copyright (c) 2009-2019, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file compat_libevent.c
  5. * \brief Wrappers and utility functions for Libevent.
  6. */
  7. #include "orconfig.h"
  8. #define COMPAT_LIBEVENT_PRIVATE
  9. #include "lib/evloop/compat_libevent.h"
  10. #include "lib/crypt_ops/crypto_rand.h"
  11. #include "lib/log/log.h"
  12. #include "lib/log/util_bug.h"
  13. #include "lib/string/compat_string.h"
  14. #include <event2/event.h>
  15. #include <event2/thread.h>
  16. #include <string.h>
  17. /** A string which, if it appears in a libevent log, should be ignored. */
  18. static const char *suppress_msg = NULL;
  19. /** Callback function passed to event_set_log() so we can intercept
  20. * log messages from libevent. */
  21. STATIC void
  22. libevent_logging_callback(int severity, const char *msg)
  23. {
  24. char buf[1024];
  25. size_t n;
  26. if (suppress_msg && strstr(msg, suppress_msg))
  27. return;
  28. n = strlcpy(buf, msg, sizeof(buf));
  29. if (n && n < sizeof(buf) && buf[n-1] == '\n') {
  30. buf[n-1] = '\0';
  31. }
  32. switch (severity) {
  33. case _EVENT_LOG_DEBUG:
  34. log_debug(LD_NOCB|LD_NET, "Message from libevent: %s", buf);
  35. break;
  36. case _EVENT_LOG_MSG:
  37. log_info(LD_NOCB|LD_NET, "Message from libevent: %s", buf);
  38. break;
  39. case _EVENT_LOG_WARN:
  40. log_warn(LD_NOCB|LD_GENERAL, "Warning from libevent: %s", buf);
  41. break;
  42. case _EVENT_LOG_ERR:
  43. log_err(LD_NOCB|LD_GENERAL, "Error from libevent: %s", buf);
  44. break;
  45. default:
  46. log_warn(LD_NOCB|LD_GENERAL, "Message [%d] from libevent: %s",
  47. severity, buf);
  48. break;
  49. }
  50. }
  51. /** Set hook to intercept log messages from libevent. */
  52. void
  53. configure_libevent_logging(void)
  54. {
  55. event_set_log_callback(libevent_logging_callback);
  56. }
  57. /** Ignore any libevent log message that contains <b>msg</b>. */
  58. void
  59. suppress_libevent_log_msg(const char *msg)
  60. {
  61. suppress_msg = msg;
  62. }
  63. /* Wrapper for event_free() that tolerates tor_event_free(NULL) */
  64. void
  65. tor_event_free_(struct event *ev)
  66. {
  67. if (ev == NULL)
  68. return;
  69. event_free(ev);
  70. }
  71. /** Global event base for use by the main thread. */
  72. static struct event_base *the_event_base = NULL;
  73. /**
  74. * @defgroup postloop post-loop event helpers
  75. *
  76. * If we're not careful, Libevent can susceptible to infinite event chains:
  77. * one event can activate another, whose callback activates another, whose
  78. * callback activates another, ad infinitum. While this is happening,
  79. * Libevent won't be checking timeouts, socket-based events, signals, and so
  80. * on.
  81. *
  82. * We solve this problem by marking some events as "post-loop". A post-loop
  83. * event behaves like any ordinary event, but any events that _it_ activates
  84. * cannot run until Libevent has checked for other events at least once.
  85. *
  86. * @{ */
  87. /**
  88. * An event that stops Libevent from running any more events on the current
  89. * iteration of its loop, until it has re-checked for socket events, signal
  90. * events, timeouts, etc.
  91. */
  92. static struct event *rescan_mainloop_ev = NULL;
  93. /**
  94. * Callback to implement rescan_mainloop_ev: it simply exits the mainloop,
  95. * and relies on Tor to re-enter the mainloop since no error has occurred.
  96. */
  97. static void
  98. rescan_mainloop_cb(evutil_socket_t fd, short events, void *arg)
  99. {
  100. (void)fd;
  101. (void)events;
  102. struct event_base *the_base = arg;
  103. event_base_loopbreak(the_base);
  104. }
  105. /** @} */
  106. /* This is what passes for version detection on OSX. We set
  107. * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
  108. * 10.4.0 (aka 1040). */
  109. #ifdef __APPLE__
  110. #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
  111. #define MACOSX_KQUEUE_IS_BROKEN \
  112. (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
  113. #else
  114. #define MACOSX_KQUEUE_IS_BROKEN 0
  115. #endif /* defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) */
  116. #endif /* defined(__APPLE__) */
  117. /** Initialize the Libevent library and set up the event base. */
  118. void
  119. tor_libevent_initialize(tor_libevent_cfg *torcfg)
  120. {
  121. tor_assert(the_event_base == NULL);
  122. /* some paths below don't use torcfg, so avoid unused variable warnings */
  123. (void)torcfg;
  124. {
  125. int attempts = 0;
  126. struct event_config *cfg;
  127. ++attempts;
  128. cfg = event_config_new();
  129. tor_assert(cfg);
  130. /* Telling Libevent not to try to turn locking on can avoid a needless
  131. * socketpair() attempt. */
  132. event_config_set_flag(cfg, EVENT_BASE_FLAG_NOLOCK);
  133. if (torcfg->num_cpus > 0)
  134. event_config_set_num_cpus_hint(cfg, torcfg->num_cpus);
  135. /* We can enable changelist support with epoll, since we don't give
  136. * Libevent any dup'd fds. This lets us avoid some syscalls. */
  137. event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);
  138. the_event_base = event_base_new_with_config(cfg);
  139. event_config_free(cfg);
  140. }
  141. if (!the_event_base) {
  142. /* LCOV_EXCL_START */
  143. log_err(LD_GENERAL, "Unable to initialize Libevent: cannot continue.");
  144. exit(1); // exit ok: libevent is broken.
  145. /* LCOV_EXCL_STOP */
  146. }
  147. rescan_mainloop_ev = event_new(the_event_base, -1, 0,
  148. rescan_mainloop_cb, the_event_base);
  149. if (!rescan_mainloop_ev) {
  150. /* LCOV_EXCL_START */
  151. log_err(LD_GENERAL, "Unable to create rescan event: cannot continue.");
  152. exit(1); // exit ok: libevent is broken.
  153. /* LCOV_EXCL_STOP */
  154. }
  155. log_info(LD_GENERAL,
  156. "Initialized libevent version %s using method %s. Good.",
  157. event_get_version(), tor_libevent_get_method());
  158. }
  159. /**
  160. * Return true iff the libevent module has been successfully initialized,
  161. * and not subsequently shut down.
  162. **/
  163. bool
  164. tor_libevent_is_initialized(void)
  165. {
  166. return the_event_base != NULL;
  167. }
  168. /** Return the current Libevent event base that we're set up to use. */
  169. MOCK_IMPL(struct event_base *,
  170. tor_libevent_get_base, (void))
  171. {
  172. tor_assert(the_event_base != NULL);
  173. return the_event_base;
  174. }
  175. /** Return the name of the Libevent backend we're using. */
  176. const char *
  177. tor_libevent_get_method(void)
  178. {
  179. return event_base_get_method(the_event_base);
  180. }
  181. /** Return a string representation of the version of the currently running
  182. * version of Libevent. */
  183. const char *
  184. tor_libevent_get_version_str(void)
  185. {
  186. return event_get_version();
  187. }
  188. /** Return a string representation of the version of Libevent that was used
  189. * at compilation time. */
  190. const char *
  191. tor_libevent_get_header_version_str(void)
  192. {
  193. return LIBEVENT_VERSION;
  194. }
  195. /** Represents a timer that's run every N microseconds by Libevent. */
  196. struct periodic_timer_t {
  197. /** Underlying event used to implement this periodic event. */
  198. struct event *ev;
  199. /** The callback we'll be invoking whenever the event triggers */
  200. void (*cb)(struct periodic_timer_t *, void *);
  201. /** User-supplied data for the callback */
  202. void *data;
  203. };
  204. /** Libevent callback to implement a periodic event. */
  205. static void
  206. periodic_timer_cb(evutil_socket_t fd, short what, void *arg)
  207. {
  208. periodic_timer_t *timer = arg;
  209. (void) what;
  210. (void) fd;
  211. timer->cb(timer, timer->data);
  212. }
  213. /** Create and schedule a new timer that will run every <b>tv</b> in
  214. * the event loop of <b>base</b>. When the timer fires, it will
  215. * run the timer in <b>cb</b> with the user-supplied data in <b>data</b>. */
  216. periodic_timer_t *
  217. periodic_timer_new(struct event_base *base,
  218. const struct timeval *tv,
  219. void (*cb)(periodic_timer_t *timer, void *data),
  220. void *data)
  221. {
  222. periodic_timer_t *timer;
  223. tor_assert(base);
  224. tor_assert(tv);
  225. tor_assert(cb);
  226. timer = tor_malloc_zero(sizeof(periodic_timer_t));
  227. if (!(timer->ev = tor_event_new(base, -1, EV_PERSIST,
  228. periodic_timer_cb, timer))) {
  229. tor_free(timer);
  230. return NULL;
  231. }
  232. timer->cb = cb;
  233. timer->data = data;
  234. periodic_timer_launch(timer, tv);
  235. return timer;
  236. }
  237. /**
  238. * Launch the timer <b>timer</b> to run at <b>tv</b> from now, and every
  239. * <b>tv</b> thereafter.
  240. *
  241. * If the timer is already enabled, this function does nothing.
  242. */
  243. void
  244. periodic_timer_launch(periodic_timer_t *timer, const struct timeval *tv)
  245. {
  246. tor_assert(timer);
  247. if (event_pending(timer->ev, EV_TIMEOUT, NULL))
  248. return;
  249. event_add(timer->ev, tv);
  250. }
  251. /**
  252. * Disable the provided <b>timer</b>, but do not free it.
  253. *
  254. * You can reenable the same timer later with periodic_timer_launch.
  255. *
  256. * If the timer is already disabled, this function does nothing.
  257. */
  258. void
  259. periodic_timer_disable(periodic_timer_t *timer)
  260. {
  261. tor_assert(timer);
  262. (void) event_del(timer->ev);
  263. }
  264. /** Stop and free a periodic timer */
  265. void
  266. periodic_timer_free_(periodic_timer_t *timer)
  267. {
  268. if (!timer)
  269. return;
  270. tor_event_free(timer->ev);
  271. tor_free(timer);
  272. }
  273. /**
  274. * Type used to represent events that run directly from the main loop,
  275. * either because they are activated from elsewhere in the code, or
  276. * because they have a simple timeout.
  277. *
  278. * We use this type to avoid exposing Libevent's API throughout the rest
  279. * of the codebase.
  280. *
  281. * This type can't be used for all events: it doesn't handle events that
  282. * are triggered by signals or by sockets.
  283. */
  284. struct mainloop_event_t {
  285. struct event *ev;
  286. void (*cb)(mainloop_event_t *, void *);
  287. void *userdata;
  288. };
  289. /**
  290. * Internal: Implements mainloop event using a libevent event.
  291. */
  292. static void
  293. mainloop_event_cb(evutil_socket_t fd, short what, void *arg)
  294. {
  295. (void)fd;
  296. (void)what;
  297. mainloop_event_t *mev = arg;
  298. mev->cb(mev, mev->userdata);
  299. }
  300. /**
  301. * As mainloop_event_cb, but implements a post-loop event.
  302. */
  303. static void
  304. mainloop_event_postloop_cb(evutil_socket_t fd, short what, void *arg)
  305. {
  306. (void)fd;
  307. (void)what;
  308. /* Note that if rescan_mainloop_ev is already activated,
  309. * event_active() will do nothing: only the first post-loop event that
  310. * happens each time through the event loop will cause it to be
  311. * activated.
  312. *
  313. * Because event_active() puts events on a FIFO queue, every event
  314. * that is made active _after_ rescan_mainloop_ev will get its
  315. * callback run after rescan_mainloop_cb is called -- that is, on the
  316. * next iteration of the loop.
  317. */
  318. event_active(rescan_mainloop_ev, EV_READ, 1);
  319. mainloop_event_t *mev = arg;
  320. mev->cb(mev, mev->userdata);
  321. }
  322. /**
  323. * Helper for mainloop_event_new() and mainloop_event_postloop_new().
  324. */
  325. static mainloop_event_t *
  326. mainloop_event_new_impl(int postloop,
  327. void (*cb)(mainloop_event_t *, void *),
  328. void *userdata)
  329. {
  330. tor_assert(cb);
  331. struct event_base *base = tor_libevent_get_base();
  332. mainloop_event_t *mev = tor_malloc_zero(sizeof(mainloop_event_t));
  333. mev->ev = tor_event_new(base, -1, 0,
  334. postloop ? mainloop_event_postloop_cb : mainloop_event_cb,
  335. mev);
  336. tor_assert(mev->ev);
  337. mev->cb = cb;
  338. mev->userdata = userdata;
  339. return mev;
  340. }
  341. /**
  342. * Create and return a new mainloop_event_t to run the function <b>cb</b>.
  343. *
  344. * When run, the callback function will be passed the mainloop_event_t
  345. * and <b>userdata</b> as its arguments. The <b>userdata</b> pointer
  346. * must remain valid for as long as the mainloop_event_t event exists:
  347. * it is your responsibility to free it.
  348. *
  349. * The event is not scheduled by default: Use mainloop_event_activate()
  350. * or mainloop_event_schedule() to make it run.
  351. */
  352. mainloop_event_t *
  353. mainloop_event_new(void (*cb)(mainloop_event_t *, void *),
  354. void *userdata)
  355. {
  356. return mainloop_event_new_impl(0, cb, userdata);
  357. }
  358. /**
  359. * As mainloop_event_new(), but create a post-loop event.
  360. *
  361. * A post-loop event behaves like any ordinary event, but any events
  362. * that _it_ activates cannot run until Libevent has checked for other
  363. * events at least once.
  364. */
  365. mainloop_event_t *
  366. mainloop_event_postloop_new(void (*cb)(mainloop_event_t *, void *),
  367. void *userdata)
  368. {
  369. return mainloop_event_new_impl(1, cb, userdata);
  370. }
  371. /**
  372. * Schedule <b>event</b> to run in the main loop, immediately. If it is
  373. * not scheduled, it will run anyway. If it is already scheduled to run
  374. * later, it will run now instead. This function will have no effect if
  375. * the event is already scheduled to run.
  376. *
  377. * This function may only be called from the main thread.
  378. */
  379. void
  380. mainloop_event_activate(mainloop_event_t *event)
  381. {
  382. tor_assert(event);
  383. event_active(event->ev, EV_READ, 1);
  384. }
  385. /** Schedule <b>event</b> to run in the main loop, after a delay of <b>tv</b>.
  386. *
  387. * If the event is scheduled for a different time, cancel it and run
  388. * after this delay instead. If the event is currently pending to run
  389. * <em>now</b>, has no effect.
  390. *
  391. * Do not call this function with <b>tv</b> == NULL -- use
  392. * mainloop_event_activate() instead.
  393. *
  394. * This function may only be called from the main thread.
  395. */
  396. int
  397. mainloop_event_schedule(mainloop_event_t *event, const struct timeval *tv)
  398. {
  399. tor_assert(event);
  400. if (BUG(tv == NULL)) {
  401. // LCOV_EXCL_START
  402. mainloop_event_activate(event);
  403. return 0;
  404. // LCOV_EXCL_STOP
  405. }
  406. return event_add(event->ev, tv);
  407. }
  408. /** Cancel <b>event</b> if it is currently active or pending. (Do nothing if
  409. * the event is not currently active or pending.) */
  410. void
  411. mainloop_event_cancel(mainloop_event_t *event)
  412. {
  413. if (!event)
  414. return;
  415. (void) event_del(event->ev);
  416. }
  417. /** Cancel <b>event</b> and release all storage associated with it. */
  418. void
  419. mainloop_event_free_(mainloop_event_t *event)
  420. {
  421. if (!event)
  422. return;
  423. tor_event_free(event->ev);
  424. memset(event, 0xb8, sizeof(*event));
  425. tor_free(event);
  426. }
  427. int
  428. tor_init_libevent_rng(void)
  429. {
  430. int rv = 0;
  431. char buf[256];
  432. if (evutil_secure_rng_init() < 0) {
  433. rv = -1;
  434. }
  435. crypto_rand(buf, 32);
  436. #ifdef HAVE_EVUTIL_SECURE_RNG_ADD_BYTES
  437. evutil_secure_rng_add_bytes(buf, 32);
  438. #endif
  439. evutil_secure_rng_get_bytes(buf, sizeof(buf));
  440. return rv;
  441. }
  442. /**
  443. * Un-initialize libevent in preparation for an exit
  444. */
  445. void
  446. tor_libevent_free_all(void)
  447. {
  448. tor_event_free(rescan_mainloop_ev);
  449. if (the_event_base)
  450. event_base_free(the_event_base);
  451. the_event_base = NULL;
  452. }
  453. /**
  454. * Run the event loop for the provided event_base, handling events until
  455. * something stops it. If <b>once</b> is set, then just poll-and-run
  456. * once, then exit. Return 0 on success, -1 if an error occurred, or 1
  457. * if we exited because no events were pending or active.
  458. *
  459. * This isn't reentrant or multithreaded.
  460. */
  461. int
  462. tor_libevent_run_event_loop(struct event_base *base, int once)
  463. {
  464. const int flags = once ? EVLOOP_ONCE : 0;
  465. return event_base_loop(base, flags);
  466. }
  467. /** Tell the event loop to exit after <b>delay</b>. If <b>delay</b> is NULL,
  468. * instead exit after we're done running the currently active events. */
  469. void
  470. tor_libevent_exit_loop_after_delay(struct event_base *base,
  471. const struct timeval *delay)
  472. {
  473. event_base_loopexit(base, delay);
  474. }
  475. /** Tell the event loop to exit after running whichever callback is currently
  476. * active. */
  477. void
  478. tor_libevent_exit_loop_after_callback(struct event_base *base)
  479. {
  480. event_base_loopbreak(base);
  481. }
  482. #if defined(TOR_UNIT_TESTS)
  483. /** For testing: called post-fork to make libevent reinitialize
  484. * kernel structures. */
  485. void
  486. tor_libevent_postfork(void)
  487. {
  488. int r = event_reinit(tor_libevent_get_base());
  489. tor_assert(r == 0);
  490. }
  491. #endif /* defined(TOR_UNIT_TESTS) */