compat_libevent.c 20 KB

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