compat_libevent.c 21 KB

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