compat_libevent.c 20 KB

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