compat_libevent.c 15 KB

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