compat_libevent.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. /* Copyright (c) 2009-2014, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file compat_libevent.c
  5. * \brief Wrappers to handle porting between different versions of libevent.
  6. *
  7. * In an ideal world, we'd just use Libevent 2.0 from now on. But as of June
  8. * 2012, Libevent 1.4 is still all over, and some poor souls are stuck on
  9. * Libevent 1.3e. */
  10. #include "orconfig.h"
  11. #include "compat.h"
  12. #include "compat_libevent.h"
  13. #include "crypto.h"
  14. #include "util.h"
  15. #include "torlog.h"
  16. #ifdef HAVE_EVENT2_EVENT_H
  17. #include <event2/event.h>
  18. #include <event2/thread.h>
  19. #ifdef USE_BUFFEREVENTS
  20. #include <event2/bufferevent.h>
  21. #endif
  22. #else
  23. #include <event.h>
  24. #endif
  25. /** A number representing a version of Libevent.
  26. This is a 4-byte number, with the first three bytes representing the
  27. major, minor, and patchlevel respectively of the library. The fourth
  28. byte is unused.
  29. This is equivalent to the format of LIBEVENT_VERSION_NUMBER on Libevent
  30. 2.0.1 or later. For versions of Libevent before 1.4.0, which followed the
  31. format of "1.0, 1.0a, 1.0b", we define 1.0 to be equivalent to 1.0.0, 1.0a
  32. to be equivalent to 1.0.1, and so on.
  33. */
  34. typedef uint32_t le_version_t;
  35. /** @{ */
  36. /** Macros: returns the number of a libevent version as a le_version_t */
  37. #define V(major, minor, patch) \
  38. (((major) << 24) | ((minor) << 16) | ((patch) << 8))
  39. #define V_OLD(major, minor, patch) \
  40. V((major), (minor), (patch)-'a'+1)
  41. /** @} */
  42. /** Represetns a version of libevent so old we can't figure out what version
  43. * it is. */
  44. #define LE_OLD V(0,0,0)
  45. /** Represents a version of libevent so weird we can't figure out what version
  46. * it is. */
  47. #define LE_OTHER V(0,0,99)
  48. #if 0
  49. static le_version_t tor_get_libevent_version(const char **v_out);
  50. #endif
  51. #if defined(HAVE_EVENT_SET_LOG_CALLBACK) || defined(RUNNING_DOXYGEN)
  52. /** A string which, if it appears in a libevent log, should be ignored. */
  53. static const char *suppress_msg = NULL;
  54. /** Callback function passed to event_set_log() so we can intercept
  55. * log messages from libevent. */
  56. static void
  57. libevent_logging_callback(int severity, const char *msg)
  58. {
  59. char buf[1024];
  60. size_t n;
  61. if (suppress_msg && strstr(msg, suppress_msg))
  62. return;
  63. n = strlcpy(buf, msg, sizeof(buf));
  64. if (n && n < sizeof(buf) && buf[n-1] == '\n') {
  65. buf[n-1] = '\0';
  66. }
  67. switch (severity) {
  68. case _EVENT_LOG_DEBUG:
  69. log_debug(LD_NOCB|LD_NET, "Message from libevent: %s", buf);
  70. break;
  71. case _EVENT_LOG_MSG:
  72. log_info(LD_NOCB|LD_NET, "Message from libevent: %s", buf);
  73. break;
  74. case _EVENT_LOG_WARN:
  75. log_warn(LD_NOCB|LD_GENERAL, "Warning from libevent: %s", buf);
  76. break;
  77. case _EVENT_LOG_ERR:
  78. log_err(LD_NOCB|LD_GENERAL, "Error from libevent: %s", buf);
  79. break;
  80. default:
  81. log_warn(LD_NOCB|LD_GENERAL, "Message [%d] from libevent: %s",
  82. severity, buf);
  83. break;
  84. }
  85. }
  86. /** Set hook to intercept log messages from libevent. */
  87. void
  88. configure_libevent_logging(void)
  89. {
  90. event_set_log_callback(libevent_logging_callback);
  91. }
  92. /** Ignore any libevent log message that contains <b>msg</b>. */
  93. void
  94. suppress_libevent_log_msg(const char *msg)
  95. {
  96. suppress_msg = msg;
  97. }
  98. #else
  99. void
  100. configure_libevent_logging(void)
  101. {
  102. }
  103. void
  104. suppress_libevent_log_msg(const char *msg)
  105. {
  106. (void)msg;
  107. }
  108. #endif
  109. #ifndef HAVE_EVENT2_EVENT_H
  110. /** Work-alike replacement for event_new() on pre-Libevent-2.0 systems. */
  111. struct event *
  112. tor_event_new(struct event_base *base, int sock, short what,
  113. void (*cb)(int, short, void *), void *arg)
  114. {
  115. struct event *e = tor_malloc_zero(sizeof(struct event));
  116. event_set(e, sock, what, cb, arg);
  117. if (! base)
  118. base = tor_libevent_get_base();
  119. event_base_set(base, e);
  120. return e;
  121. }
  122. /** Work-alike replacement for evtimer_new() on pre-Libevent-2.0 systems. */
  123. struct event *
  124. tor_evtimer_new(struct event_base *base,
  125. void (*cb)(int, short, void *), void *arg)
  126. {
  127. return tor_event_new(base, -1, 0, cb, arg);
  128. }
  129. /** Work-alike replacement for evsignal_new() on pre-Libevent-2.0 systems. */
  130. struct event *
  131. tor_evsignal_new(struct event_base * base, int sig,
  132. void (*cb)(int, short, void *), void *arg)
  133. {
  134. return tor_event_new(base, sig, EV_SIGNAL|EV_PERSIST, cb, arg);
  135. }
  136. /** Work-alike replacement for event_free() on pre-Libevent-2.0 systems. */
  137. void
  138. tor_event_free(struct event *ev)
  139. {
  140. event_del(ev);
  141. tor_free(ev);
  142. }
  143. #endif
  144. /** Global event base for use by the main thread. */
  145. struct event_base *the_event_base = NULL;
  146. /* This is what passes for version detection on OSX. We set
  147. * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
  148. * 10.4.0 (aka 1040). */
  149. #ifdef __APPLE__
  150. #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
  151. #define MACOSX_KQUEUE_IS_BROKEN \
  152. (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
  153. #else
  154. #define MACOSX_KQUEUE_IS_BROKEN 0
  155. #endif
  156. #endif
  157. #ifdef USE_BUFFEREVENTS
  158. static int using_iocp_bufferevents = 0;
  159. static void tor_libevent_set_tick_timeout(int msec_per_tick);
  160. int
  161. tor_libevent_using_iocp_bufferevents(void)
  162. {
  163. return using_iocp_bufferevents;
  164. }
  165. #endif
  166. /** Initialize the Libevent library and set up the event base. */
  167. void
  168. tor_libevent_initialize(tor_libevent_cfg *torcfg)
  169. {
  170. tor_assert(the_event_base == NULL);
  171. /* some paths below don't use torcfg, so avoid unused variable warnings */
  172. (void)torcfg;
  173. #ifdef HAVE_EVENT2_EVENT_H
  174. {
  175. int attempts = 0;
  176. int using_threads;
  177. struct event_config *cfg;
  178. retry:
  179. ++attempts;
  180. using_threads = 0;
  181. cfg = event_config_new();
  182. tor_assert(cfg);
  183. #if defined(_WIN32) && defined(USE_BUFFEREVENTS)
  184. if (! torcfg->disable_iocp) {
  185. evthread_use_windows_threads();
  186. event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
  187. using_iocp_bufferevents = 1;
  188. using_threads = 1;
  189. } else {
  190. using_iocp_bufferevents = 0;
  191. }
  192. #elif defined(__COVERITY__)
  193. /* Avoid a 'dead code' warning below. */
  194. using_threads = ! torcfg->disable_iocp;
  195. #endif
  196. if (!using_threads) {
  197. /* Telling Libevent not to try to turn locking on can avoid a needless
  198. * socketpair() attempt. */
  199. event_config_set_flag(cfg, EVENT_BASE_FLAG_NOLOCK);
  200. }
  201. #if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= V(2,0,7)
  202. if (torcfg->num_cpus > 0)
  203. event_config_set_num_cpus_hint(cfg, torcfg->num_cpus);
  204. #endif
  205. #if LIBEVENT_VERSION_NUMBER >= V(2,0,9)
  206. /* We can enable changelist support with epoll, since we don't give
  207. * Libevent any dup'd fds. This lets us avoid some syscalls. */
  208. event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);
  209. #endif
  210. the_event_base = event_base_new_with_config(cfg);
  211. event_config_free(cfg);
  212. if (using_threads && the_event_base == NULL && attempts < 2) {
  213. /* This could be a socketpair() failure, which can happen sometimes on
  214. * windows boxes with obnoxious firewall rules. Downgrade and try
  215. * again. */
  216. #if defined(_WIN32) && defined(USE_BUFFEREVENTS)
  217. if (torcfg->disable_iocp == 0) {
  218. log_warn(LD_GENERAL, "Unable to initialize Libevent. Trying again "
  219. "with IOCP disabled.");
  220. } else
  221. #endif
  222. {
  223. log_warn(LD_GENERAL, "Unable to initialize Libevent. Trying again.");
  224. }
  225. torcfg->disable_iocp = 1;
  226. goto retry;
  227. }
  228. }
  229. #else
  230. the_event_base = event_init();
  231. #endif
  232. if (!the_event_base) {
  233. log_err(LD_GENERAL, "Unable to initialize Libevent: cannot continue.");
  234. exit(1);
  235. }
  236. #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  237. /* Making this a NOTICE for now so we can link bugs to a libevent versions
  238. * or methods better. */
  239. log_info(LD_GENERAL,
  240. "Initialized libevent version %s using method %s. Good.",
  241. event_get_version(), tor_libevent_get_method());
  242. #else
  243. log_notice(LD_GENERAL,
  244. "Initialized old libevent (version 1.0b or earlier).");
  245. log_warn(LD_GENERAL,
  246. "You have a *VERY* old version of libevent. It is likely to be buggy; "
  247. "please build Tor with a more recent version.");
  248. #endif
  249. #ifdef USE_BUFFEREVENTS
  250. tor_libevent_set_tick_timeout(torcfg->msec_per_tick);
  251. #endif
  252. }
  253. /** Return the current Libevent event base that we're set up to use. */
  254. struct event_base *
  255. tor_libevent_get_base(void)
  256. {
  257. return the_event_base;
  258. }
  259. #ifndef HAVE_EVENT_BASE_LOOPEXIT
  260. /** Replacement for event_base_loopexit on some very old versions of Libevent
  261. * that we are not yet brave enough to deprecate. */
  262. int
  263. tor_event_base_loopexit(struct event_base *base, struct timeval *tv)
  264. {
  265. tor_assert(base == the_event_base);
  266. return event_loopexit(tv);
  267. }
  268. #endif
  269. /** Return the name of the Libevent backend we're using. */
  270. const char *
  271. tor_libevent_get_method(void)
  272. {
  273. #ifdef HAVE_EVENT2_EVENT_H
  274. return event_base_get_method(the_event_base);
  275. #elif defined(HAVE_EVENT_GET_METHOD)
  276. return event_get_method();
  277. #else
  278. return "<unknown>";
  279. #endif
  280. }
  281. /** Return the le_version_t for the version of libevent specified in the
  282. * string <b>v</b>. If the version is very new or uses an unrecognized
  283. * version, format, return LE_OTHER. */
  284. static le_version_t
  285. tor_decode_libevent_version(const char *v)
  286. {
  287. unsigned major, minor, patchlevel;
  288. char c, e, extra;
  289. int fields;
  290. /* Try the new preferred "1.4.11-stable" format.
  291. * Also accept "1.4.14b-stable". */
  292. fields = tor_sscanf(v, "%u.%u.%u%c%c", &major, &minor, &patchlevel, &c, &e);
  293. if (fields == 3 ||
  294. ((fields == 4 || fields == 5 ) && (c == '-' || c == '_')) ||
  295. (fields == 5 && TOR_ISALPHA(c) && (e == '-' || e == '_'))) {
  296. return V(major,minor,patchlevel);
  297. }
  298. /* Try the old "1.3e" format. */
  299. fields = tor_sscanf(v, "%u.%u%c%c", &major, &minor, &c, &extra);
  300. if (fields == 3 && TOR_ISALPHA(c)) {
  301. return V_OLD(major, minor, c);
  302. } else if (fields == 2) {
  303. return V(major, minor, 0);
  304. }
  305. return LE_OTHER;
  306. }
  307. /** Return an integer representing the binary interface of a Libevent library.
  308. * Two different versions with different numbers are sure not to be binary
  309. * compatible. Two different versions with the same numbers have a decent
  310. * chance of binary compatibility.*/
  311. static int
  312. le_versions_compatibility(le_version_t v)
  313. {
  314. if (v == LE_OTHER)
  315. return 0;
  316. if (v < V_OLD(1,0,'c'))
  317. return 1;
  318. else if (v < V(1,4,0))
  319. return 2;
  320. else if (v < V(1,4,99))
  321. return 3;
  322. else if (v < V(2,0,1))
  323. return 4;
  324. else /* Everything 2.0 and later should be compatible. */
  325. return 5;
  326. }
  327. #if 0
  328. /** Return the version number of the currently running version of Libevent.
  329. * See le_version_t for info on the format.
  330. */
  331. static le_version_t
  332. tor_get_libevent_version(const char **v_out)
  333. {
  334. const char *v;
  335. le_version_t r;
  336. #if defined(HAVE_EVENT_GET_VERSION_NUMBER)
  337. v = event_get_version();
  338. r = event_get_version_number();
  339. #elif defined (HAVE_EVENT_GET_VERSION)
  340. v = event_get_version();
  341. r = tor_decode_libevent_version(v);
  342. #else
  343. v = "pre-1.0c";
  344. r = LE_OLD;
  345. #endif
  346. if (v_out)
  347. *v_out = v;
  348. return r;
  349. }
  350. #endif
  351. /** Return a string representation of the version of the currently running
  352. * version of Libevent. */
  353. const char *
  354. tor_libevent_get_version_str(void)
  355. {
  356. #ifdef HAVE_EVENT_GET_VERSION
  357. return event_get_version();
  358. #else
  359. return "pre-1.0c";
  360. #endif
  361. }
  362. /**
  363. * Compare the current Libevent method and version to a list of versions
  364. * which are known not to work. Warn the user as appropriate.
  365. */
  366. void
  367. tor_check_libevent_version(const char *m, int server,
  368. const char **badness_out)
  369. {
  370. (void) m;
  371. (void) server;
  372. *badness_out = NULL;
  373. }
  374. #if defined(LIBEVENT_VERSION)
  375. #define HEADER_VERSION LIBEVENT_VERSION
  376. #elif defined(_EVENT_VERSION)
  377. #define HEADER_VERSION _EVENT_VERSION
  378. #endif
  379. /** Return a string representation of the version of Libevent that was used
  380. * at compilation time. */
  381. const char *
  382. tor_libevent_get_header_version_str(void)
  383. {
  384. return HEADER_VERSION;
  385. }
  386. /** See whether the headers we were built against differ from the library we
  387. * linked against so much that we're likely to crash. If so, warn the
  388. * user. */
  389. void
  390. tor_check_libevent_header_compatibility(void)
  391. {
  392. (void) le_versions_compatibility;
  393. (void) tor_decode_libevent_version;
  394. /* In libevent versions before 2.0, it's hard to keep binary compatibility
  395. * between upgrades, and unpleasant to detect when the version we compiled
  396. * against is unlike the version we have linked against. Here's how. */
  397. #if defined(HEADER_VERSION) && defined(HAVE_EVENT_GET_VERSION)
  398. /* We have a header-file version and a function-call version. Easy. */
  399. if (strcmp(HEADER_VERSION, event_get_version())) {
  400. le_version_t v1, v2;
  401. int compat1 = -1, compat2 = -1;
  402. int verybad;
  403. v1 = tor_decode_libevent_version(HEADER_VERSION);
  404. v2 = tor_decode_libevent_version(event_get_version());
  405. compat1 = le_versions_compatibility(v1);
  406. compat2 = le_versions_compatibility(v2);
  407. verybad = compat1 != compat2;
  408. tor_log(verybad ? LOG_WARN : LOG_NOTICE,
  409. LD_GENERAL, "We were compiled with headers from version %s "
  410. "of Libevent, but we're using a Libevent library that says it's "
  411. "version %s.", HEADER_VERSION, event_get_version());
  412. if (verybad)
  413. log_warn(LD_GENERAL, "This will almost certainly make Tor crash.");
  414. else
  415. log_info(LD_GENERAL, "I think these versions are binary-compatible.");
  416. }
  417. #elif defined(HAVE_EVENT_GET_VERSION)
  418. /* event_get_version but no _EVENT_VERSION. We might be in 1.4.0-beta or
  419. earlier, where that's normal. To see whether we were compiled with an
  420. earlier version, let's see whether the struct event defines MIN_HEAP_IDX.
  421. */
  422. #ifdef HAVE_STRUCT_EVENT_MIN_HEAP_IDX
  423. /* The header files are 1.4.0-beta or later. If the version is not
  424. * 1.4.0-beta, we are incompatible. */
  425. {
  426. if (strcmp(event_get_version(), "1.4.0-beta")) {
  427. log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
  428. "Libevent 1.4.0-beta header files, whereas you have linked "
  429. "against Libevent %s. This will probably make Tor crash.",
  430. event_get_version());
  431. }
  432. }
  433. #else
  434. /* Our headers are 1.3e or earlier. If the library version is not 1.4.x or
  435. later, we're probably fine. */
  436. {
  437. const char *v = event_get_version();
  438. if ((v[0] == '1' && v[2] == '.' && v[3] > '3') || v[0] > '1') {
  439. log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
  440. "Libevent header file from 1.3e or earlier, whereas you have "
  441. "linked against Libevent %s. This will probably make Tor "
  442. "crash.", event_get_version());
  443. }
  444. }
  445. #endif
  446. #elif defined(HEADER_VERSION)
  447. #warn "_EVENT_VERSION is defined but not get_event_version(): Libevent is odd."
  448. #else
  449. /* Your libevent is ancient. */
  450. #endif
  451. }
  452. /*
  453. If possible, we're going to try to use Libevent's periodic timer support,
  454. since it does a pretty good job of making sure that periodic events get
  455. called exactly M seconds apart, rather than starting each one exactly M
  456. seconds after the time that the last one was run.
  457. */
  458. #ifdef HAVE_EVENT2_EVENT_H
  459. #define HAVE_PERIODIC
  460. #define PERIODIC_FLAGS EV_PERSIST
  461. #else
  462. #define PERIODIC_FLAGS 0
  463. #endif
  464. /** Represents a timer that's run every N microseconds by Libevent. */
  465. struct periodic_timer_t {
  466. /** Underlying event used to implement this periodic event. */
  467. struct event *ev;
  468. /** The callback we'll be invoking whenever the event triggers */
  469. void (*cb)(struct periodic_timer_t *, void *);
  470. /** User-supplied data for the callback */
  471. void *data;
  472. #ifndef HAVE_PERIODIC
  473. /** If Libevent doesn't know how to invoke events every N microseconds,
  474. * we'll need to remember the timeout interval here. */
  475. struct timeval tv;
  476. #endif
  477. };
  478. /** Libevent callback to implement a periodic event. */
  479. static void
  480. periodic_timer_cb(evutil_socket_t fd, short what, void *arg)
  481. {
  482. periodic_timer_t *timer = arg;
  483. (void) what;
  484. (void) fd;
  485. #ifndef HAVE_PERIODIC
  486. /** reschedule the event as needed. */
  487. event_add(timer->ev, &timer->tv);
  488. #endif
  489. timer->cb(timer, timer->data);
  490. }
  491. /** Create and schedule a new timer that will run every <b>tv</b> in
  492. * the event loop of <b>base</b>. When the timer fires, it will
  493. * run the timer in <b>cb</b> with the user-supplied data in <b>data</b>. */
  494. periodic_timer_t *
  495. periodic_timer_new(struct event_base *base,
  496. const struct timeval *tv,
  497. void (*cb)(periodic_timer_t *timer, void *data),
  498. void *data)
  499. {
  500. periodic_timer_t *timer;
  501. tor_assert(base);
  502. tor_assert(tv);
  503. tor_assert(cb);
  504. timer = tor_malloc_zero(sizeof(periodic_timer_t));
  505. if (!(timer->ev = tor_event_new(base, -1, PERIODIC_FLAGS,
  506. periodic_timer_cb, timer))) {
  507. tor_free(timer);
  508. return NULL;
  509. }
  510. timer->cb = cb;
  511. timer->data = data;
  512. #ifndef HAVE_PERIODIC
  513. memcpy(&timer->tv, tv, sizeof(struct timeval));
  514. #endif
  515. event_add(timer->ev, (struct timeval *)tv); /*drop const for old libevent*/
  516. return timer;
  517. }
  518. /** Stop and free a periodic timer */
  519. void
  520. periodic_timer_free(periodic_timer_t *timer)
  521. {
  522. if (!timer)
  523. return;
  524. tor_event_free(timer->ev);
  525. tor_free(timer);
  526. }
  527. #ifdef USE_BUFFEREVENTS
  528. static const struct timeval *one_tick = NULL;
  529. /**
  530. * Return a special timeout to be passed whenever libevent's O(1) timeout
  531. * implementation should be used. Only use this when the timer is supposed
  532. * to fire after msec_per_tick ticks have elapsed.
  533. */
  534. const struct timeval *
  535. tor_libevent_get_one_tick_timeout(void)
  536. {
  537. tor_assert(one_tick);
  538. return one_tick;
  539. }
  540. /** Initialize the common timeout that we'll use to refill the buckets every
  541. * time a tick elapses. */
  542. static void
  543. tor_libevent_set_tick_timeout(int msec_per_tick)
  544. {
  545. struct event_base *base = tor_libevent_get_base();
  546. struct timeval tv;
  547. tor_assert(! one_tick);
  548. tv.tv_sec = msec_per_tick / 1000;
  549. tv.tv_usec = (msec_per_tick % 1000) * 1000;
  550. one_tick = event_base_init_common_timeout(base, &tv);
  551. }
  552. static struct bufferevent *
  553. tor_get_root_bufferevent(struct bufferevent *bev)
  554. {
  555. struct bufferevent *u;
  556. while ((u = bufferevent_get_underlying(bev)) != NULL)
  557. bev = u;
  558. return bev;
  559. }
  560. int
  561. tor_set_bufferevent_rate_limit(struct bufferevent *bev,
  562. struct ev_token_bucket_cfg *cfg)
  563. {
  564. return bufferevent_set_rate_limit(tor_get_root_bufferevent(bev), cfg);
  565. }
  566. int
  567. tor_add_bufferevent_to_rate_limit_group(struct bufferevent *bev,
  568. struct bufferevent_rate_limit_group *g)
  569. {
  570. return bufferevent_add_to_rate_limit_group(tor_get_root_bufferevent(bev), g);
  571. }
  572. #endif
  573. int
  574. tor_init_libevent_rng(void)
  575. {
  576. int rv = 0;
  577. #ifdef HAVE_EVUTIL_SECURE_RNG_INIT
  578. char buf[256];
  579. if (evutil_secure_rng_init() < 0) {
  580. rv = -1;
  581. }
  582. /* Older libevent -- manually initialize the RNG */
  583. crypto_rand(buf, 32);
  584. evutil_secure_rng_add_bytes(buf, 32);
  585. evutil_secure_rng_get_bytes(buf, sizeof(buf));
  586. #endif
  587. return rv;
  588. }
  589. #if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= V(2,1,1) \
  590. && !defined(TOR_UNIT_TESTS)
  591. void
  592. tor_gettimeofday_cached(struct timeval *tv)
  593. {
  594. event_base_gettimeofday_cached(the_event_base, tv);
  595. }
  596. void
  597. tor_gettimeofday_cache_clear(void)
  598. {
  599. event_base_update_cache_time(the_event_base);
  600. }
  601. #else
  602. /** Cache the current hi-res time; the cache gets reset when libevent
  603. * calls us. */
  604. static struct timeval cached_time_hires = {0, 0};
  605. /** Return a fairly recent view of the current time. */
  606. void
  607. tor_gettimeofday_cached(struct timeval *tv)
  608. {
  609. if (cached_time_hires.tv_sec == 0) {
  610. tor_gettimeofday(&cached_time_hires);
  611. }
  612. *tv = cached_time_hires;
  613. }
  614. /** Reset the cached view of the current time, so that the next time we try
  615. * to learn it, we will get an up-to-date value. */
  616. void
  617. tor_gettimeofday_cache_clear(void)
  618. {
  619. cached_time_hires.tv_sec = 0;
  620. }
  621. #ifdef TOR_UNIT_TESTS
  622. /** For testing: force-update the cached time to a given value. */
  623. void
  624. tor_gettimeofday_cache_set(const struct timeval *tv)
  625. {
  626. tor_assert(tv);
  627. memcpy(&cached_time_hires, tv, sizeof(*tv));
  628. }
  629. #endif
  630. #endif
  631. /**
  632. * As tor_gettimeofday_cached, but can never move backwards in time.
  633. *
  634. * The returned value may diverge from wall-clock time, since wall-clock time
  635. * can trivially be adjusted backwards, and this can't. Don't mix wall-clock
  636. * time with these values in the same calculation.
  637. *
  638. * Depending on implementation, this function may or may not "smooth out" huge
  639. * jumps forward in wall-clock time. It may or may not keep its results
  640. * advancing forward (as opposed to stalling) if the wall-clock time goes
  641. * backwards. The current implementation does neither of of these.
  642. *
  643. * This function is not thread-safe; do not call it outside the main thread.
  644. *
  645. * In future versions of Tor, this may return a time does not have its
  646. * origin at the Unix epoch.
  647. */
  648. void
  649. tor_gettimeofday_cached_monotonic(struct timeval *tv)
  650. {
  651. struct timeval last_tv = { 0, 0 };
  652. tor_gettimeofday_cached(tv);
  653. if (timercmp(tv, &last_tv, <)) {
  654. memcpy(tv, &last_tv, sizeof(struct timeval));
  655. } else {
  656. memcpy(&last_tv, tv, sizeof(struct timeval));
  657. }
  658. }