compat_libevent.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /* Copyright (c) 2009-2016, 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 "compat.h"
  9. #define COMPAT_LIBEVENT_PRIVATE
  10. #include "compat_libevent.h"
  11. #include "crypto.h"
  12. #include "util.h"
  13. #include "torlog.h"
  14. #include <event2/event.h>
  15. #include <event2/thread.h>
  16. #ifdef USE_BUFFEREVENTS
  17. #include <event2/bufferevent.h>
  18. #endif
  19. /** A string which, if it appears in a libevent log, should be ignored. */
  20. static const char *suppress_msg = NULL;
  21. /** Callback function passed to event_set_log() so we can intercept
  22. * log messages from libevent. */
  23. STATIC void
  24. libevent_logging_callback(int severity, const char *msg)
  25. {
  26. char buf[1024];
  27. size_t n;
  28. if (suppress_msg && strstr(msg, suppress_msg))
  29. return;
  30. n = strlcpy(buf, msg, sizeof(buf));
  31. if (n && n < sizeof(buf) && buf[n-1] == '\n') {
  32. buf[n-1] = '\0';
  33. }
  34. switch (severity) {
  35. case _EVENT_LOG_DEBUG:
  36. log_debug(LD_NOCB|LD_NET, "Message from libevent: %s", buf);
  37. break;
  38. case _EVENT_LOG_MSG:
  39. log_info(LD_NOCB|LD_NET, "Message from libevent: %s", buf);
  40. break;
  41. case _EVENT_LOG_WARN:
  42. log_warn(LD_NOCB|LD_GENERAL, "Warning from libevent: %s", buf);
  43. break;
  44. case _EVENT_LOG_ERR:
  45. log_err(LD_NOCB|LD_GENERAL, "Error from libevent: %s", buf);
  46. break;
  47. default:
  48. log_warn(LD_NOCB|LD_GENERAL, "Message [%d] from libevent: %s",
  49. severity, buf);
  50. break;
  51. }
  52. }
  53. /** Set hook to intercept log messages from libevent. */
  54. void
  55. configure_libevent_logging(void)
  56. {
  57. event_set_log_callback(libevent_logging_callback);
  58. }
  59. /** Ignore any libevent log message that contains <b>msg</b>. */
  60. void
  61. suppress_libevent_log_msg(const char *msg)
  62. {
  63. suppress_msg = msg;
  64. }
  65. /* Wrapper for event_free() that tolerates tor_event_free(NULL) */
  66. void
  67. tor_event_free(struct event *ev)
  68. {
  69. if (ev == NULL)
  70. return;
  71. event_free(ev);
  72. }
  73. /** Global event base for use by the main thread. */
  74. static struct event_base *the_event_base = NULL;
  75. /* This is what passes for version detection on OSX. We set
  76. * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
  77. * 10.4.0 (aka 1040). */
  78. #ifdef __APPLE__
  79. #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
  80. #define MACOSX_KQUEUE_IS_BROKEN \
  81. (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
  82. #else
  83. #define MACOSX_KQUEUE_IS_BROKEN 0
  84. #endif
  85. #endif
  86. #ifdef USE_BUFFEREVENTS
  87. static int using_iocp_bufferevents = 0;
  88. static void tor_libevent_set_tick_timeout(int msec_per_tick);
  89. int
  90. tor_libevent_using_iocp_bufferevents(void)
  91. {
  92. return using_iocp_bufferevents;
  93. }
  94. #endif
  95. /** Initialize the Libevent library and set up the event base. */
  96. void
  97. tor_libevent_initialize(tor_libevent_cfg *torcfg)
  98. {
  99. tor_assert(the_event_base == NULL);
  100. /* some paths below don't use torcfg, so avoid unused variable warnings */
  101. (void)torcfg;
  102. {
  103. int attempts = 0;
  104. int using_threads;
  105. struct event_config *cfg;
  106. retry:
  107. ++attempts;
  108. using_threads = 0;
  109. cfg = event_config_new();
  110. tor_assert(cfg);
  111. #if defined(_WIN32) && defined(USE_BUFFEREVENTS)
  112. if (! torcfg->disable_iocp) {
  113. evthread_use_windows_threads();
  114. event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
  115. using_iocp_bufferevents = 1;
  116. using_threads = 1;
  117. } else {
  118. using_iocp_bufferevents = 0;
  119. }
  120. #elif defined(__COVERITY__)
  121. /* Avoid a 'dead code' warning below. */
  122. using_threads = ! torcfg->disable_iocp;
  123. #endif
  124. if (!using_threads) {
  125. /* Telling Libevent not to try to turn locking on can avoid a needless
  126. * socketpair() attempt. */
  127. event_config_set_flag(cfg, EVENT_BASE_FLAG_NOLOCK);
  128. }
  129. if (torcfg->num_cpus > 0)
  130. event_config_set_num_cpus_hint(cfg, torcfg->num_cpus);
  131. /* We can enable changelist support with epoll, since we don't give
  132. * Libevent any dup'd fds. This lets us avoid some syscalls. */
  133. event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);
  134. the_event_base = event_base_new_with_config(cfg);
  135. event_config_free(cfg);
  136. if (using_threads && the_event_base == NULL && attempts < 2) {
  137. /* This could be a socketpair() failure, which can happen sometimes on
  138. * windows boxes with obnoxious firewall rules. Downgrade and try
  139. * again. */
  140. #if defined(_WIN32) && defined(USE_BUFFEREVENTS)
  141. if (torcfg->disable_iocp == 0) {
  142. log_warn(LD_GENERAL, "Unable to initialize Libevent. Trying again "
  143. "with IOCP disabled.");
  144. } else
  145. #endif
  146. {
  147. log_warn(LD_GENERAL, "Unable to initialize Libevent. Trying again.");
  148. }
  149. torcfg->disable_iocp = 1;
  150. goto retry;
  151. }
  152. }
  153. if (!the_event_base) {
  154. /* LCOV_EXCL_START */
  155. log_err(LD_GENERAL, "Unable to initialize Libevent: cannot continue.");
  156. exit(1);
  157. /* LCOV_EXCL_STOP */
  158. }
  159. log_info(LD_GENERAL,
  160. "Initialized libevent version %s using method %s. Good.",
  161. event_get_version(), tor_libevent_get_method());
  162. #ifdef USE_BUFFEREVENTS
  163. tor_libevent_set_tick_timeout(torcfg->msec_per_tick);
  164. #endif
  165. }
  166. /** Return the current Libevent event base that we're set up to use. */
  167. MOCK_IMPL(struct event_base *,
  168. tor_libevent_get_base, (void))
  169. {
  170. tor_assert(the_event_base != NULL);
  171. return the_event_base;
  172. }
  173. /** Return the name of the Libevent backend we're using. */
  174. const char *
  175. tor_libevent_get_method(void)
  176. {
  177. return event_base_get_method(the_event_base);
  178. }
  179. /** Return a string representation of the version of the currently running
  180. * version of Libevent. */
  181. const char *
  182. tor_libevent_get_version_str(void)
  183. {
  184. return event_get_version();
  185. }
  186. /** Return a string representation of the version of Libevent that was used
  187. * at compilation time. */
  188. const char *
  189. tor_libevent_get_header_version_str(void)
  190. {
  191. return LIBEVENT_VERSION;
  192. }
  193. /** Represents a timer that's run every N microseconds by Libevent. */
  194. struct periodic_timer_t {
  195. /** Underlying event used to implement this periodic event. */
  196. struct event *ev;
  197. /** The callback we'll be invoking whenever the event triggers */
  198. void (*cb)(struct periodic_timer_t *, void *);
  199. /** User-supplied data for the callback */
  200. void *data;
  201. };
  202. /** Libevent callback to implement a periodic event. */
  203. static void
  204. periodic_timer_cb(evutil_socket_t fd, short what, void *arg)
  205. {
  206. periodic_timer_t *timer = arg;
  207. (void) what;
  208. (void) fd;
  209. timer->cb(timer, timer->data);
  210. }
  211. /** Create and schedule a new timer that will run every <b>tv</b> in
  212. * the event loop of <b>base</b>. When the timer fires, it will
  213. * run the timer in <b>cb</b> with the user-supplied data in <b>data</b>. */
  214. periodic_timer_t *
  215. periodic_timer_new(struct event_base *base,
  216. const struct timeval *tv,
  217. void (*cb)(periodic_timer_t *timer, void *data),
  218. void *data)
  219. {
  220. periodic_timer_t *timer;
  221. tor_assert(base);
  222. tor_assert(tv);
  223. tor_assert(cb);
  224. timer = tor_malloc_zero(sizeof(periodic_timer_t));
  225. if (!(timer->ev = tor_event_new(base, -1, EV_PERSIST,
  226. periodic_timer_cb, timer))) {
  227. tor_free(timer);
  228. return NULL;
  229. }
  230. timer->cb = cb;
  231. timer->data = data;
  232. event_add(timer->ev, (struct timeval *)tv); /*drop const for old libevent*/
  233. return timer;
  234. }
  235. /** Stop and free a periodic timer */
  236. void
  237. periodic_timer_free(periodic_timer_t *timer)
  238. {
  239. if (!timer)
  240. return;
  241. tor_event_free(timer->ev);
  242. tor_free(timer);
  243. }
  244. #ifdef USE_BUFFEREVENTS
  245. static const struct timeval *one_tick = NULL;
  246. /**
  247. * Return a special timeout to be passed whenever libevent's O(1) timeout
  248. * implementation should be used. Only use this when the timer is supposed
  249. * to fire after msec_per_tick ticks have elapsed.
  250. */
  251. const struct timeval *
  252. tor_libevent_get_one_tick_timeout(void)
  253. {
  254. tor_assert(one_tick);
  255. return one_tick;
  256. }
  257. /** Initialize the common timeout that we'll use to refill the buckets every
  258. * time a tick elapses. */
  259. static void
  260. tor_libevent_set_tick_timeout(int msec_per_tick)
  261. {
  262. struct event_base *base = tor_libevent_get_base();
  263. struct timeval tv;
  264. tor_assert(! one_tick);
  265. tv.tv_sec = msec_per_tick / 1000;
  266. tv.tv_usec = (msec_per_tick % 1000) * 1000;
  267. one_tick = event_base_init_common_timeout(base, &tv);
  268. }
  269. static struct bufferevent *
  270. tor_get_root_bufferevent(struct bufferevent *bev)
  271. {
  272. struct bufferevent *u;
  273. while ((u = bufferevent_get_underlying(bev)) != NULL)
  274. bev = u;
  275. return bev;
  276. }
  277. int
  278. tor_set_bufferevent_rate_limit(struct bufferevent *bev,
  279. struct ev_token_bucket_cfg *cfg)
  280. {
  281. return bufferevent_set_rate_limit(tor_get_root_bufferevent(bev), cfg);
  282. }
  283. int
  284. tor_add_bufferevent_to_rate_limit_group(struct bufferevent *bev,
  285. struct bufferevent_rate_limit_group *g)
  286. {
  287. return bufferevent_add_to_rate_limit_group(tor_get_root_bufferevent(bev), g);
  288. }
  289. #endif
  290. int
  291. tor_init_libevent_rng(void)
  292. {
  293. int rv = 0;
  294. char buf[256];
  295. if (evutil_secure_rng_init() < 0) {
  296. rv = -1;
  297. }
  298. crypto_rand(buf, 32);
  299. evutil_secure_rng_add_bytes(buf, 32);
  300. evutil_secure_rng_get_bytes(buf, sizeof(buf));
  301. return rv;
  302. }
  303. #if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= V(2,1,1) \
  304. && !defined(TOR_UNIT_TESTS)
  305. void
  306. tor_gettimeofday_cached(struct timeval *tv)
  307. {
  308. event_base_gettimeofday_cached(the_event_base, tv);
  309. }
  310. void
  311. tor_gettimeofday_cache_clear(void)
  312. {
  313. event_base_update_cache_time(the_event_base);
  314. }
  315. #else
  316. /** Cache the current hi-res time; the cache gets reset when libevent
  317. * calls us. */
  318. static struct timeval cached_time_hires = {0, 0};
  319. /** Return a fairly recent view of the current time. */
  320. void
  321. tor_gettimeofday_cached(struct timeval *tv)
  322. {
  323. if (cached_time_hires.tv_sec == 0) {
  324. tor_gettimeofday(&cached_time_hires);
  325. }
  326. *tv = cached_time_hires;
  327. }
  328. /** Reset the cached view of the current time, so that the next time we try
  329. * to learn it, we will get an up-to-date value. */
  330. void
  331. tor_gettimeofday_cache_clear(void)
  332. {
  333. cached_time_hires.tv_sec = 0;
  334. }
  335. #ifdef TOR_UNIT_TESTS
  336. /** For testing: force-update the cached time to a given value. */
  337. void
  338. tor_gettimeofday_cache_set(const struct timeval *tv)
  339. {
  340. tor_assert(tv);
  341. memcpy(&cached_time_hires, tv, sizeof(*tv));
  342. }
  343. #endif
  344. #endif
  345. /**
  346. * As tor_gettimeofday_cached, but can never move backwards in time.
  347. *
  348. * The returned value may diverge from wall-clock time, since wall-clock time
  349. * can trivially be adjusted backwards, and this can't. Don't mix wall-clock
  350. * time with these values in the same calculation.
  351. *
  352. * Depending on implementation, this function may or may not "smooth out" huge
  353. * jumps forward in wall-clock time. It may or may not keep its results
  354. * advancing forward (as opposed to stalling) if the wall-clock time goes
  355. * backwards. The current implementation does neither of of these.
  356. *
  357. * This function is not thread-safe; do not call it outside the main thread.
  358. *
  359. * In future versions of Tor, this may return a time does not have its
  360. * origin at the Unix epoch.
  361. */
  362. void
  363. tor_gettimeofday_cached_monotonic(struct timeval *tv)
  364. {
  365. struct timeval last_tv = { 0, 0 };
  366. tor_gettimeofday_cached(tv);
  367. if (timercmp(tv, &last_tv, OP_LT)) {
  368. memcpy(tv, &last_tv, sizeof(struct timeval));
  369. } else {
  370. memcpy(&last_tv, tv, sizeof(struct timeval));
  371. }
  372. }