compat_libevent.c 20 KB

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