compat_libevent.c 18 KB

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