compat_libevent.c 21 KB

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