compat_libevent.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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. /** A string which, if it appears in a libevent log, should be ignored. */
  49. static const char *suppress_msg = NULL;
  50. /** Callback function passed to event_set_log() so we can intercept
  51. * log messages from libevent. */
  52. static void
  53. libevent_logging_callback(int severity, const char *msg)
  54. {
  55. char buf[1024];
  56. size_t n;
  57. if (suppress_msg && strstr(msg, suppress_msg))
  58. return;
  59. n = strlcpy(buf, msg, sizeof(buf));
  60. if (n && n < sizeof(buf) && buf[n-1] == '\n') {
  61. buf[n-1] = '\0';
  62. }
  63. switch (severity) {
  64. case _EVENT_LOG_DEBUG:
  65. log_debug(LD_NOCB|LD_NET, "Message from libevent: %s", buf);
  66. break;
  67. case _EVENT_LOG_MSG:
  68. log_info(LD_NOCB|LD_NET, "Message from libevent: %s", buf);
  69. break;
  70. case _EVENT_LOG_WARN:
  71. log_warn(LD_NOCB|LD_GENERAL, "Warning from libevent: %s", buf);
  72. break;
  73. case _EVENT_LOG_ERR:
  74. log_err(LD_NOCB|LD_GENERAL, "Error from libevent: %s", buf);
  75. break;
  76. default:
  77. log_warn(LD_NOCB|LD_GENERAL, "Message [%d] from libevent: %s",
  78. severity, buf);
  79. break;
  80. }
  81. }
  82. /** Set hook to intercept log messages from libevent. */
  83. void
  84. configure_libevent_logging(void)
  85. {
  86. event_set_log_callback(libevent_logging_callback);
  87. }
  88. /** Ignore any libevent log message that contains <b>msg</b>. */
  89. void
  90. suppress_libevent_log_msg(const char *msg)
  91. {
  92. suppress_msg = msg;
  93. }
  94. #ifndef HAVE_EVENT2_EVENT_H
  95. /** Work-alike replacement for event_new() on pre-Libevent-2.0 systems. */
  96. struct event *
  97. tor_event_new(struct event_base *base, int sock, short what,
  98. void (*cb)(int, short, void *), void *arg)
  99. {
  100. struct event *e = tor_malloc_zero(sizeof(struct event));
  101. event_set(e, sock, what, cb, arg);
  102. if (! base)
  103. base = tor_libevent_get_base();
  104. event_base_set(base, e);
  105. return e;
  106. }
  107. /** Work-alike replacement for evtimer_new() on pre-Libevent-2.0 systems. */
  108. struct event *
  109. tor_evtimer_new(struct event_base *base,
  110. void (*cb)(int, short, void *), void *arg)
  111. {
  112. return tor_event_new(base, -1, 0, cb, arg);
  113. }
  114. /** Work-alike replacement for evsignal_new() on pre-Libevent-2.0 systems. */
  115. struct event *
  116. tor_evsignal_new(struct event_base * base, int sig,
  117. void (*cb)(int, short, void *), void *arg)
  118. {
  119. return tor_event_new(base, sig, EV_SIGNAL|EV_PERSIST, cb, arg);
  120. }
  121. /** Work-alike replacement for event_free() on pre-Libevent-2.0 systems,
  122. * except tolerate tor_event_free(NULL). */
  123. void
  124. tor_event_free(struct event *ev)
  125. {
  126. if (ev == NULL)
  127. return;
  128. event_del(ev);
  129. tor_free(ev);
  130. }
  131. #else
  132. /* Wrapper for event_free() that tolerates tor_event_free(NULL) */
  133. void
  134. tor_event_free(struct event *ev)
  135. {
  136. if (ev == NULL)
  137. return;
  138. event_free(ev);
  139. }
  140. #endif
  141. /** Global event base for use by the main thread. */
  142. struct event_base *the_event_base = NULL;
  143. /* This is what passes for version detection on OSX. We set
  144. * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
  145. * 10.4.0 (aka 1040). */
  146. #ifdef __APPLE__
  147. #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
  148. #define MACOSX_KQUEUE_IS_BROKEN \
  149. (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
  150. #else
  151. #define MACOSX_KQUEUE_IS_BROKEN 0
  152. #endif
  153. #endif
  154. #ifdef USE_BUFFEREVENTS
  155. static int using_iocp_bufferevents = 0;
  156. static void tor_libevent_set_tick_timeout(int msec_per_tick);
  157. int
  158. tor_libevent_using_iocp_bufferevents(void)
  159. {
  160. return using_iocp_bufferevents;
  161. }
  162. #endif
  163. /** Initialize the Libevent library and set up the event base. */
  164. void
  165. tor_libevent_initialize(tor_libevent_cfg *torcfg)
  166. {
  167. tor_assert(the_event_base == NULL);
  168. /* some paths below don't use torcfg, so avoid unused variable warnings */
  169. (void)torcfg;
  170. #ifdef HAVE_EVENT2_EVENT_H
  171. {
  172. int attempts = 0;
  173. int using_threads;
  174. struct event_config *cfg;
  175. retry:
  176. ++attempts;
  177. using_threads = 0;
  178. cfg = event_config_new();
  179. tor_assert(cfg);
  180. #if defined(_WIN32) && defined(USE_BUFFEREVENTS)
  181. if (! torcfg->disable_iocp) {
  182. evthread_use_windows_threads();
  183. event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
  184. using_iocp_bufferevents = 1;
  185. using_threads = 1;
  186. } else {
  187. using_iocp_bufferevents = 0;
  188. }
  189. #elif defined(__COVERITY__)
  190. /* Avoid a 'dead code' warning below. */
  191. using_threads = ! torcfg->disable_iocp;
  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. /* 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. #ifdef USE_BUFFEREVENTS
  239. tor_libevent_set_tick_timeout(torcfg->msec_per_tick);
  240. #endif
  241. }
  242. /** Return the current Libevent event base that we're set up to use. */
  243. MOCK_IMPL(struct event_base *,
  244. tor_libevent_get_base, (void))
  245. {
  246. return the_event_base;
  247. }
  248. /** Return the name of the Libevent backend we're using. */
  249. const char *
  250. tor_libevent_get_method(void)
  251. {
  252. #ifdef HAVE_EVENT2_EVENT_H
  253. return event_base_get_method(the_event_base);
  254. #else
  255. return event_get_method();
  256. #endif
  257. }
  258. /** Return the le_version_t for the version of libevent specified in the
  259. * string <b>v</b>. If the version is very new or uses an unrecognized
  260. * version, format, return LE_OTHER. */
  261. static le_version_t
  262. tor_decode_libevent_version(const char *v)
  263. {
  264. unsigned major, minor, patchlevel;
  265. char c, e, extra;
  266. int fields;
  267. /* Try the new preferred "1.4.11-stable" format.
  268. * Also accept "1.4.14b-stable". */
  269. fields = tor_sscanf(v, "%u.%u.%u%c%c", &major, &minor, &patchlevel, &c, &e);
  270. if (fields == 3 ||
  271. ((fields == 4 || fields == 5 ) && (c == '-' || c == '_')) ||
  272. (fields == 5 && TOR_ISALPHA(c) && (e == '-' || e == '_'))) {
  273. return V(major,minor,patchlevel);
  274. }
  275. /* Try the old "1.3e" format. */
  276. fields = tor_sscanf(v, "%u.%u%c%c", &major, &minor, &c, &extra);
  277. if (fields == 3 && TOR_ISALPHA(c)) {
  278. return V_OLD(major, minor, c);
  279. } else if (fields == 2) {
  280. return V(major, minor, 0);
  281. }
  282. return LE_OTHER;
  283. }
  284. /** Return an integer representing the binary interface of a Libevent library.
  285. * Two different versions with different numbers are sure not to be binary
  286. * compatible. Two different versions with the same numbers have a decent
  287. * chance of binary compatibility.*/
  288. static int
  289. le_versions_compatibility(le_version_t v)
  290. {
  291. if (v == LE_OTHER)
  292. return 0;
  293. if (v < V_OLD(1,0,'c'))
  294. return 1;
  295. else if (v < V(1,4,0))
  296. return 2;
  297. else if (v < V(1,4,99))
  298. return 3;
  299. else if (v < V(2,0,1))
  300. return 4;
  301. else /* Everything 2.0 and later should be compatible. */
  302. return 5;
  303. }
  304. /** Return a string representation of the version of the currently running
  305. * version of Libevent. */
  306. const char *
  307. tor_libevent_get_version_str(void)
  308. {
  309. return event_get_version();
  310. }
  311. #if defined(LIBEVENT_VERSION)
  312. #define HEADER_VERSION LIBEVENT_VERSION
  313. #elif defined(_EVENT_VERSION)
  314. #define HEADER_VERSION _EVENT_VERSION
  315. #endif
  316. /** Return a string representation of the version of Libevent that was used
  317. * at compilation time. */
  318. const char *
  319. tor_libevent_get_header_version_str(void)
  320. {
  321. return HEADER_VERSION;
  322. }
  323. /** See whether the headers we were built against differ from the library we
  324. * linked against so much that we're likely to crash. If so, warn the
  325. * user. */
  326. void
  327. tor_check_libevent_header_compatibility(void)
  328. {
  329. (void) le_versions_compatibility;
  330. (void) tor_decode_libevent_version;
  331. /* In libevent versions before 2.0, it's hard to keep binary compatibility
  332. * between upgrades, and unpleasant to detect when the version we compiled
  333. * against is unlike the version we have linked against. Here's how. */
  334. #if defined(HEADER_VERSION)
  335. /* We have a header-file version and a function-call version. Easy. */
  336. if (strcmp(HEADER_VERSION, event_get_version())) {
  337. le_version_t v1, v2;
  338. int compat1 = -1, compat2 = -1;
  339. int verybad;
  340. v1 = tor_decode_libevent_version(HEADER_VERSION);
  341. v2 = tor_decode_libevent_version(event_get_version());
  342. compat1 = le_versions_compatibility(v1);
  343. compat2 = le_versions_compatibility(v2);
  344. verybad = compat1 != compat2;
  345. tor_log(verybad ? LOG_WARN : LOG_NOTICE,
  346. LD_GENERAL, "We were compiled with headers from version %s "
  347. "of Libevent, but we're using a Libevent library that says it's "
  348. "version %s.", HEADER_VERSION, event_get_version());
  349. if (verybad)
  350. log_warn(LD_GENERAL, "This will almost certainly make Tor crash.");
  351. else
  352. log_info(LD_GENERAL, "I think these versions are binary-compatible.");
  353. }
  354. #else
  355. /* event_get_version but no _EVENT_VERSION. We might be in 1.4.0-beta or
  356. earlier, where that's normal. To see whether we were compiled with an
  357. earlier version, let's see whether the struct event defines MIN_HEAP_IDX.
  358. */
  359. #ifdef HAVE_STRUCT_EVENT_MIN_HEAP_IDX
  360. /* The header files are 1.4.0-beta or later. If the version is not
  361. * 1.4.0-beta, we are incompatible. */
  362. {
  363. if (strcmp(event_get_version(), "1.4.0-beta")) {
  364. log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
  365. "Libevent 1.4.0-beta header files, whereas you have linked "
  366. "against Libevent %s. This will probably make Tor crash.",
  367. event_get_version());
  368. }
  369. }
  370. #else
  371. /* Our headers are 1.3e or earlier. If the library version is not 1.4.x or
  372. later, we're probably fine. */
  373. {
  374. const char *v = event_get_version();
  375. if ((v[0] == '1' && v[2] == '.' && v[3] > '3') || v[0] > '1') {
  376. log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
  377. "Libevent header file from 1.3e or earlier, whereas you have "
  378. "linked against Libevent %s. This will probably make Tor "
  379. "crash.", event_get_version());
  380. }
  381. }
  382. #endif
  383. /* Your libevent is ancient. */
  384. #endif
  385. }
  386. /*
  387. If possible, we're going to try to use Libevent's periodic timer support,
  388. since it does a pretty good job of making sure that periodic events get
  389. called exactly M seconds apart, rather than starting each one exactly M
  390. seconds after the time that the last one was run.
  391. */
  392. #ifdef HAVE_EVENT2_EVENT_H
  393. #define HAVE_PERIODIC
  394. #define PERIODIC_FLAGS EV_PERSIST
  395. #else
  396. #define PERIODIC_FLAGS 0
  397. #endif
  398. /** Represents a timer that's run every N microseconds by Libevent. */
  399. struct periodic_timer_t {
  400. /** Underlying event used to implement this periodic event. */
  401. struct event *ev;
  402. /** The callback we'll be invoking whenever the event triggers */
  403. void (*cb)(struct periodic_timer_t *, void *);
  404. /** User-supplied data for the callback */
  405. void *data;
  406. #ifndef HAVE_PERIODIC
  407. /** If Libevent doesn't know how to invoke events every N microseconds,
  408. * we'll need to remember the timeout interval here. */
  409. struct timeval tv;
  410. #endif
  411. };
  412. /** Libevent callback to implement a periodic event. */
  413. static void
  414. periodic_timer_cb(evutil_socket_t fd, short what, void *arg)
  415. {
  416. periodic_timer_t *timer = arg;
  417. (void) what;
  418. (void) fd;
  419. #ifndef HAVE_PERIODIC
  420. /** reschedule the event as needed. */
  421. event_add(timer->ev, &timer->tv);
  422. #endif
  423. timer->cb(timer, timer->data);
  424. }
  425. /** Create and schedule a new timer that will run every <b>tv</b> in
  426. * the event loop of <b>base</b>. When the timer fires, it will
  427. * run the timer in <b>cb</b> with the user-supplied data in <b>data</b>. */
  428. periodic_timer_t *
  429. periodic_timer_new(struct event_base *base,
  430. const struct timeval *tv,
  431. void (*cb)(periodic_timer_t *timer, void *data),
  432. void *data)
  433. {
  434. periodic_timer_t *timer;
  435. tor_assert(base);
  436. tor_assert(tv);
  437. tor_assert(cb);
  438. timer = tor_malloc_zero(sizeof(periodic_timer_t));
  439. if (!(timer->ev = tor_event_new(base, -1, PERIODIC_FLAGS,
  440. periodic_timer_cb, timer))) {
  441. tor_free(timer);
  442. return NULL;
  443. }
  444. timer->cb = cb;
  445. timer->data = data;
  446. #ifndef HAVE_PERIODIC
  447. memcpy(&timer->tv, tv, sizeof(struct timeval));
  448. #endif
  449. event_add(timer->ev, (struct timeval *)tv); /*drop const for old libevent*/
  450. return timer;
  451. }
  452. /** Stop and free a periodic timer */
  453. void
  454. periodic_timer_free(periodic_timer_t *timer)
  455. {
  456. if (!timer)
  457. return;
  458. tor_event_free(timer->ev);
  459. tor_free(timer);
  460. }
  461. #ifdef USE_BUFFEREVENTS
  462. static const struct timeval *one_tick = NULL;
  463. /**
  464. * Return a special timeout to be passed whenever libevent's O(1) timeout
  465. * implementation should be used. Only use this when the timer is supposed
  466. * to fire after msec_per_tick ticks have elapsed.
  467. */
  468. const struct timeval *
  469. tor_libevent_get_one_tick_timeout(void)
  470. {
  471. tor_assert(one_tick);
  472. return one_tick;
  473. }
  474. /** Initialize the common timeout that we'll use to refill the buckets every
  475. * time a tick elapses. */
  476. static void
  477. tor_libevent_set_tick_timeout(int msec_per_tick)
  478. {
  479. struct event_base *base = tor_libevent_get_base();
  480. struct timeval tv;
  481. tor_assert(! one_tick);
  482. tv.tv_sec = msec_per_tick / 1000;
  483. tv.tv_usec = (msec_per_tick % 1000) * 1000;
  484. one_tick = event_base_init_common_timeout(base, &tv);
  485. }
  486. static struct bufferevent *
  487. tor_get_root_bufferevent(struct bufferevent *bev)
  488. {
  489. struct bufferevent *u;
  490. while ((u = bufferevent_get_underlying(bev)) != NULL)
  491. bev = u;
  492. return bev;
  493. }
  494. int
  495. tor_set_bufferevent_rate_limit(struct bufferevent *bev,
  496. struct ev_token_bucket_cfg *cfg)
  497. {
  498. return bufferevent_set_rate_limit(tor_get_root_bufferevent(bev), cfg);
  499. }
  500. int
  501. tor_add_bufferevent_to_rate_limit_group(struct bufferevent *bev,
  502. struct bufferevent_rate_limit_group *g)
  503. {
  504. return bufferevent_add_to_rate_limit_group(tor_get_root_bufferevent(bev), g);
  505. }
  506. #endif
  507. int
  508. tor_init_libevent_rng(void)
  509. {
  510. int rv = 0;
  511. #ifdef HAVE_EVUTIL_SECURE_RNG_INIT
  512. char buf[256];
  513. if (evutil_secure_rng_init() < 0) {
  514. rv = -1;
  515. }
  516. /* Older libevent -- manually initialize the RNG */
  517. crypto_rand(buf, 32);
  518. evutil_secure_rng_add_bytes(buf, 32);
  519. evutil_secure_rng_get_bytes(buf, sizeof(buf));
  520. #endif
  521. return rv;
  522. }
  523. #if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= V(2,1,1) \
  524. && !defined(TOR_UNIT_TESTS)
  525. void
  526. tor_gettimeofday_cached(struct timeval *tv)
  527. {
  528. event_base_gettimeofday_cached(the_event_base, tv);
  529. }
  530. void
  531. tor_gettimeofday_cache_clear(void)
  532. {
  533. event_base_update_cache_time(the_event_base);
  534. }
  535. #else
  536. /** Cache the current hi-res time; the cache gets reset when libevent
  537. * calls us. */
  538. static struct timeval cached_time_hires = {0, 0};
  539. /** Return a fairly recent view of the current time. */
  540. void
  541. tor_gettimeofday_cached(struct timeval *tv)
  542. {
  543. if (cached_time_hires.tv_sec == 0) {
  544. tor_gettimeofday(&cached_time_hires);
  545. }
  546. *tv = cached_time_hires;
  547. }
  548. /** Reset the cached view of the current time, so that the next time we try
  549. * to learn it, we will get an up-to-date value. */
  550. void
  551. tor_gettimeofday_cache_clear(void)
  552. {
  553. cached_time_hires.tv_sec = 0;
  554. }
  555. #ifdef TOR_UNIT_TESTS
  556. /** For testing: force-update the cached time to a given value. */
  557. void
  558. tor_gettimeofday_cache_set(const struct timeval *tv)
  559. {
  560. tor_assert(tv);
  561. memcpy(&cached_time_hires, tv, sizeof(*tv));
  562. }
  563. #endif
  564. #endif
  565. /**
  566. * As tor_gettimeofday_cached, but can never move backwards in time.
  567. *
  568. * The returned value may diverge from wall-clock time, since wall-clock time
  569. * can trivially be adjusted backwards, and this can't. Don't mix wall-clock
  570. * time with these values in the same calculation.
  571. *
  572. * Depending on implementation, this function may or may not "smooth out" huge
  573. * jumps forward in wall-clock time. It may or may not keep its results
  574. * advancing forward (as opposed to stalling) if the wall-clock time goes
  575. * backwards. The current implementation does neither of of these.
  576. *
  577. * This function is not thread-safe; do not call it outside the main thread.
  578. *
  579. * In future versions of Tor, this may return a time does not have its
  580. * origin at the Unix epoch.
  581. */
  582. void
  583. tor_gettimeofday_cached_monotonic(struct timeval *tv)
  584. {
  585. struct timeval last_tv = { 0, 0 };
  586. tor_gettimeofday_cached(tv);
  587. if (timercmp(tv, &last_tv, OP_LT)) {
  588. memcpy(tv, &last_tv, sizeof(struct timeval));
  589. } else {
  590. memcpy(&last_tv, tv, sizeof(struct timeval));
  591. }
  592. }