circuitstats.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2017, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitstats.c
  8. *
  9. * \brief Maintains and analyzes statistics about circuit built times, so we
  10. * can tell how long we may need to wait for a fast circuit to be constructed.
  11. *
  12. * By keeping these statistics, a client learns when it should time out a slow
  13. * circuit for being too slow, and when it should keep a circuit open in order
  14. * to wait for it to complete.
  15. *
  16. * The information here is kept in a circuit_built_times_t structure, which is
  17. * currently a singleton, but doesn't need to be. It's updated by calls to
  18. * circuit_build_times_count_timeout() from circuituse.c,
  19. * circuit_build_times_count_close() from circuituse.c, and
  20. * circuit_build_times_add_time() from circuitbuild.c, and inspected by other
  21. * calls into this module, mostly from circuitlist.c. Observations are
  22. * persisted to disk via the or_state_t-related calls.
  23. */
  24. #define CIRCUITSTATS_PRIVATE
  25. #include "or.h"
  26. #include "circuitbuild.h"
  27. #include "circuitstats.h"
  28. #include "config.h"
  29. #include "confparse.h"
  30. #include "control.h"
  31. #include "main.h"
  32. #include "networkstatus.h"
  33. #include "rendclient.h"
  34. #include "rendservice.h"
  35. #include "statefile.h"
  36. #include "circuitlist.h"
  37. #include "circuituse.h"
  38. #undef log
  39. #include <math.h>
  40. static void cbt_control_event_buildtimeout_set(
  41. const circuit_build_times_t *cbt,
  42. buildtimeout_set_event_t type);
  43. #define CBT_BIN_TO_MS(bin) ((bin)*CBT_BIN_WIDTH + (CBT_BIN_WIDTH/2))
  44. /** Global list of circuit build times */
  45. // XXXX: Add this as a member for entry_guard_t instead of global?
  46. // Then we could do per-guard statistics, as guards are likely to
  47. // vary in their own latency. The downside of this is that guards
  48. // can change frequently, so we'd be building a lot more circuits
  49. // most likely.
  50. static circuit_build_times_t circ_times;
  51. #ifdef TOR_UNIT_TESTS
  52. /** If set, we're running the unit tests: we should avoid clobbering
  53. * our state file or accessing get_options() or get_or_state() */
  54. static int unit_tests = 0;
  55. #else
  56. #define unit_tests 0
  57. #endif /* defined(TOR_UNIT_TESTS) */
  58. /** Return a pointer to the data structure describing our current circuit
  59. * build time history and computations. */
  60. const circuit_build_times_t *
  61. get_circuit_build_times(void)
  62. {
  63. return &circ_times;
  64. }
  65. /** As get_circuit_build_times, but return a mutable pointer. */
  66. circuit_build_times_t *
  67. get_circuit_build_times_mutable(void)
  68. {
  69. return &circ_times;
  70. }
  71. /** Return the time to wait before actually closing an under-construction, in
  72. * milliseconds. */
  73. double
  74. get_circuit_build_close_time_ms(void)
  75. {
  76. return circ_times.close_ms;
  77. }
  78. /** Return the time to wait before giving up on an under-construction circuit,
  79. * in milliseconds. */
  80. double
  81. get_circuit_build_timeout_ms(void)
  82. {
  83. return circ_times.timeout_ms;
  84. }
  85. /**
  86. * This function decides if CBT learning should be disabled. It returns
  87. * true if one or more of the following conditions are met:
  88. *
  89. * 1. If the cbtdisabled consensus parameter is set.
  90. * 2. If the torrc option LearnCircuitBuildTimeout is false.
  91. * 3. If we are a directory authority
  92. * 4. If we fail to write circuit build time history to our state file.
  93. * 5. If we are compiled or configured in Tor2web mode
  94. * 6. If we are configured in Single Onion mode
  95. */
  96. int
  97. circuit_build_times_disabled(const or_options_t *options)
  98. {
  99. return circuit_build_times_disabled_(options, 0);
  100. }
  101. /** As circuit_build_times_disabled, but take options as an argument. */
  102. int
  103. circuit_build_times_disabled_(const or_options_t *options,
  104. int ignore_consensus)
  105. {
  106. if (unit_tests) {
  107. return 0;
  108. } else {
  109. int consensus_disabled =
  110. ignore_consensus ? 0 : networkstatus_get_param(NULL, "cbtdisabled",
  111. 0, 0, 1);
  112. int config_disabled = !options->LearnCircuitBuildTimeout;
  113. int dirauth_disabled = options->AuthoritativeDir;
  114. int state_disabled = did_last_state_file_write_fail() ? 1 : 0;
  115. /* LearnCircuitBuildTimeout and Tor2web/Single Onion Services are
  116. * incompatible in two ways:
  117. *
  118. * - LearnCircuitBuildTimeout results in a low CBT, which
  119. * Single Onion use of one-hop intro and rendezvous circuits lowers
  120. * much further, producing *far* too many timeouts.
  121. *
  122. * - The adaptive CBT code does not update its timeout estimate
  123. * using build times for single-hop circuits.
  124. *
  125. * If we fix both of these issues someday, we should test
  126. * these modes with LearnCircuitBuildTimeout on again. */
  127. int tor2web_disabled = rend_client_allow_non_anonymous_connection(options);
  128. int single_onion_disabled = rend_service_allow_non_anonymous_connection(
  129. options);
  130. if (consensus_disabled || config_disabled || dirauth_disabled ||
  131. state_disabled || tor2web_disabled || single_onion_disabled) {
  132. #if 0
  133. log_debug(LD_CIRC,
  134. "CircuitBuildTime learning is disabled. "
  135. "Consensus=%d, Config=%d, AuthDir=%d, StateFile=%d",
  136. consensus_disabled, config_disabled, dirauth_disabled,
  137. state_disabled);
  138. #endif /* 0 */
  139. return 1;
  140. } else {
  141. #if 0
  142. log_debug(LD_CIRC,
  143. "CircuitBuildTime learning is not disabled. "
  144. "Consensus=%d, Config=%d, AuthDir=%d, StateFile=%d",
  145. consensus_disabled, config_disabled, dirauth_disabled,
  146. state_disabled);
  147. #endif /* 0 */
  148. return 0;
  149. }
  150. }
  151. }
  152. /**
  153. * Retrieve and bounds-check the cbtmaxtimeouts consensus paramter.
  154. *
  155. * Effect: When this many timeouts happen in the last 'cbtrecentcount'
  156. * circuit attempts, the client should discard all of its history and
  157. * begin learning a fresh timeout value.
  158. */
  159. static int32_t
  160. circuit_build_times_max_timeouts(void)
  161. {
  162. int32_t cbt_maxtimeouts;
  163. cbt_maxtimeouts = networkstatus_get_param(NULL, "cbtmaxtimeouts",
  164. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT,
  165. CBT_MIN_MAX_RECENT_TIMEOUT_COUNT,
  166. CBT_MAX_MAX_RECENT_TIMEOUT_COUNT);
  167. if (!(get_options()->LearnCircuitBuildTimeout)) {
  168. log_debug(LD_BUG,
  169. "circuit_build_times_max_timeouts() called, cbtmaxtimeouts is"
  170. " %d",
  171. cbt_maxtimeouts);
  172. }
  173. return cbt_maxtimeouts;
  174. }
  175. /**
  176. * Retrieve and bounds-check the cbtnummodes consensus paramter.
  177. *
  178. * Effect: This value governs how many modes to use in the weighted
  179. * average calculation of Pareto parameter Xm. A value of 3 introduces
  180. * some bias (2-5% of CDF) under ideal conditions, but allows for better
  181. * performance in the event that a client chooses guard nodes of radically
  182. * different performance characteristics.
  183. */
  184. static int32_t
  185. circuit_build_times_default_num_xm_modes(void)
  186. {
  187. int32_t num = networkstatus_get_param(NULL, "cbtnummodes",
  188. CBT_DEFAULT_NUM_XM_MODES,
  189. CBT_MIN_NUM_XM_MODES,
  190. CBT_MAX_NUM_XM_MODES);
  191. if (!(get_options()->LearnCircuitBuildTimeout)) {
  192. log_debug(LD_BUG,
  193. "circuit_build_times_default_num_xm_modes() called, cbtnummodes"
  194. " is %d",
  195. num);
  196. }
  197. return num;
  198. }
  199. /**
  200. * Retrieve and bounds-check the cbtmincircs consensus paramter.
  201. *
  202. * Effect: This is the minimum number of circuits to build before
  203. * computing a timeout.
  204. */
  205. static int32_t
  206. circuit_build_times_min_circs_to_observe(void)
  207. {
  208. int32_t num = networkstatus_get_param(NULL, "cbtmincircs",
  209. CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE,
  210. CBT_MIN_MIN_CIRCUITS_TO_OBSERVE,
  211. CBT_MAX_MIN_CIRCUITS_TO_OBSERVE);
  212. if (!(get_options()->LearnCircuitBuildTimeout)) {
  213. log_debug(LD_BUG,
  214. "circuit_build_times_min_circs_to_observe() called, cbtmincircs"
  215. " is %d",
  216. num);
  217. }
  218. return num;
  219. }
  220. /** Return true iff <b>cbt</b> has recorded enough build times that we
  221. * want to start acting on the timeout it implies. */
  222. int
  223. circuit_build_times_enough_to_compute(const circuit_build_times_t *cbt)
  224. {
  225. return cbt->total_build_times >= circuit_build_times_min_circs_to_observe();
  226. }
  227. /**
  228. * Retrieve and bounds-check the cbtquantile consensus paramter.
  229. *
  230. * Effect: This is the position on the quantile curve to use to set the
  231. * timeout value. It is a percent (10-99).
  232. */
  233. double
  234. circuit_build_times_quantile_cutoff(void)
  235. {
  236. int32_t num = networkstatus_get_param(NULL, "cbtquantile",
  237. CBT_DEFAULT_QUANTILE_CUTOFF,
  238. CBT_MIN_QUANTILE_CUTOFF,
  239. CBT_MAX_QUANTILE_CUTOFF);
  240. if (!(get_options()->LearnCircuitBuildTimeout)) {
  241. log_debug(LD_BUG,
  242. "circuit_build_times_quantile_cutoff() called, cbtquantile"
  243. " is %d",
  244. num);
  245. }
  246. return num/100.0;
  247. }
  248. /**
  249. * Retrieve and bounds-check the cbtclosequantile consensus paramter.
  250. *
  251. * Effect: This is the position on the quantile curve to use to set the
  252. * timeout value to use to actually close circuits. It is a percent
  253. * (0-99).
  254. */
  255. static double
  256. circuit_build_times_close_quantile(void)
  257. {
  258. int32_t param;
  259. /* Cast is safe - circuit_build_times_quantile_cutoff() is capped */
  260. int32_t min = (int)tor_lround(100*circuit_build_times_quantile_cutoff());
  261. param = networkstatus_get_param(NULL, "cbtclosequantile",
  262. CBT_DEFAULT_CLOSE_QUANTILE,
  263. CBT_MIN_CLOSE_QUANTILE,
  264. CBT_MAX_CLOSE_QUANTILE);
  265. if (!(get_options()->LearnCircuitBuildTimeout)) {
  266. log_debug(LD_BUG,
  267. "circuit_build_times_close_quantile() called, cbtclosequantile"
  268. " is %d", param);
  269. }
  270. if (param < min) {
  271. log_warn(LD_DIR, "Consensus parameter cbtclosequantile is "
  272. "too small, raising to %d", min);
  273. param = min;
  274. }
  275. return param / 100.0;
  276. }
  277. /**
  278. * Retrieve and bounds-check the cbttestfreq consensus paramter.
  279. *
  280. * Effect: Describes how often in seconds to build a test circuit to
  281. * gather timeout values. Only applies if less than 'cbtmincircs'
  282. * have been recorded.
  283. */
  284. static int32_t
  285. circuit_build_times_test_frequency(void)
  286. {
  287. int32_t num = networkstatus_get_param(NULL, "cbttestfreq",
  288. CBT_DEFAULT_TEST_FREQUENCY,
  289. CBT_MIN_TEST_FREQUENCY,
  290. CBT_MAX_TEST_FREQUENCY);
  291. if (!(get_options()->LearnCircuitBuildTimeout)) {
  292. log_debug(LD_BUG,
  293. "circuit_build_times_test_frequency() called, cbttestfreq is %d",
  294. num);
  295. }
  296. return num;
  297. }
  298. /**
  299. * Retrieve and bounds-check the cbtmintimeout consensus parameter.
  300. *
  301. * Effect: This is the minimum allowed timeout value in milliseconds.
  302. * The minimum is to prevent rounding to 0 (we only check once
  303. * per second).
  304. */
  305. static int32_t
  306. circuit_build_times_min_timeout(void)
  307. {
  308. int32_t num = networkstatus_get_param(NULL, "cbtmintimeout",
  309. CBT_DEFAULT_TIMEOUT_MIN_VALUE,
  310. CBT_MIN_TIMEOUT_MIN_VALUE,
  311. CBT_MAX_TIMEOUT_MIN_VALUE);
  312. if (!(get_options()->LearnCircuitBuildTimeout)) {
  313. log_debug(LD_BUG,
  314. "circuit_build_times_min_timeout() called, cbtmintimeout is %d",
  315. num);
  316. }
  317. return num;
  318. }
  319. /**
  320. * Retrieve and bounds-check the cbtinitialtimeout consensus paramter.
  321. *
  322. * Effect: This is the timeout value to use before computing a timeout,
  323. * in milliseconds.
  324. */
  325. int32_t
  326. circuit_build_times_initial_timeout(void)
  327. {
  328. int32_t min = circuit_build_times_min_timeout();
  329. int32_t param = networkstatus_get_param(NULL, "cbtinitialtimeout",
  330. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE,
  331. CBT_MIN_TIMEOUT_INITIAL_VALUE,
  332. CBT_MAX_TIMEOUT_INITIAL_VALUE);
  333. if (!(get_options()->LearnCircuitBuildTimeout)) {
  334. log_debug(LD_BUG,
  335. "circuit_build_times_initial_timeout() called, "
  336. "cbtinitialtimeout is %d",
  337. param);
  338. }
  339. if (param < min) {
  340. log_warn(LD_DIR, "Consensus parameter cbtinitialtimeout is too small, "
  341. "raising to %d", min);
  342. param = min;
  343. }
  344. return param;
  345. }
  346. /**
  347. * Retrieve and bounds-check the cbtrecentcount consensus paramter.
  348. *
  349. * Effect: This is the number of circuit build times to keep track of
  350. * for deciding if we hit cbtmaxtimeouts and need to reset our state
  351. * and learn a new timeout.
  352. */
  353. static int32_t
  354. circuit_build_times_recent_circuit_count(networkstatus_t *ns)
  355. {
  356. int32_t num;
  357. num = networkstatus_get_param(ns, "cbtrecentcount",
  358. CBT_DEFAULT_RECENT_CIRCUITS,
  359. CBT_MIN_RECENT_CIRCUITS,
  360. CBT_MAX_RECENT_CIRCUITS);
  361. if (!(get_options()->LearnCircuitBuildTimeout)) {
  362. log_debug(LD_BUG,
  363. "circuit_build_times_recent_circuit_count() called, "
  364. "cbtrecentcount is %d",
  365. num);
  366. }
  367. return num;
  368. }
  369. /**
  370. * This function is called when we get a consensus update.
  371. *
  372. * It checks to see if we have changed any consensus parameters
  373. * that require reallocation or discard of previous stats.
  374. */
  375. void
  376. circuit_build_times_new_consensus_params(circuit_build_times_t *cbt,
  377. networkstatus_t *ns)
  378. {
  379. int32_t num;
  380. /*
  381. * First check if we're doing adaptive timeouts at all; nothing to
  382. * update if we aren't.
  383. */
  384. if (!circuit_build_times_disabled(get_options())) {
  385. num = circuit_build_times_recent_circuit_count(ns);
  386. if (num > 0) {
  387. if (num != cbt->liveness.num_recent_circs) {
  388. int8_t *recent_circs;
  389. log_notice(LD_CIRC, "The Tor Directory Consensus has changed how many "
  390. "circuits we must track to detect network failures from %d "
  391. "to %d.", cbt->liveness.num_recent_circs, num);
  392. tor_assert(cbt->liveness.timeouts_after_firsthop ||
  393. cbt->liveness.num_recent_circs == 0);
  394. /*
  395. * Technically this is a circular array that we are reallocating
  396. * and memcopying. However, since it only consists of either 1s
  397. * or 0s, and is only used in a statistical test to determine when
  398. * we should discard our history after a sufficient number of 1's
  399. * have been reached, it is fine if order is not preserved or
  400. * elements are lost.
  401. *
  402. * cbtrecentcount should only be changing in cases of severe network
  403. * distress anyway, so memory correctness here is paramount over
  404. * doing acrobatics to preserve the array.
  405. */
  406. recent_circs = tor_calloc(num, sizeof(int8_t));
  407. if (cbt->liveness.timeouts_after_firsthop &&
  408. cbt->liveness.num_recent_circs > 0) {
  409. memcpy(recent_circs, cbt->liveness.timeouts_after_firsthop,
  410. sizeof(int8_t)*MIN(num, cbt->liveness.num_recent_circs));
  411. }
  412. // Adjust the index if it needs it.
  413. if (num < cbt->liveness.num_recent_circs) {
  414. cbt->liveness.after_firsthop_idx = MIN(num-1,
  415. cbt->liveness.after_firsthop_idx);
  416. }
  417. tor_free(cbt->liveness.timeouts_after_firsthop);
  418. cbt->liveness.timeouts_after_firsthop = recent_circs;
  419. cbt->liveness.num_recent_circs = num;
  420. }
  421. /* else no change, nothing to do */
  422. } else { /* num == 0 */
  423. /*
  424. * Weird. This probably shouldn't happen, so log a warning, but try
  425. * to do something sensible anyway.
  426. */
  427. log_warn(LD_CIRC,
  428. "The cbtrecentcircs consensus parameter came back zero! "
  429. "This disables adaptive timeouts since we can't keep track of "
  430. "any recent circuits.");
  431. circuit_build_times_free_timeouts(cbt);
  432. }
  433. } else {
  434. /*
  435. * Adaptive timeouts are disabled; this might be because of the
  436. * LearnCircuitBuildTimes config parameter, and hence permanent, or
  437. * the cbtdisabled consensus parameter, so it may be a new condition.
  438. * Treat it like getting num == 0 above and free the circuit history
  439. * if we have any.
  440. */
  441. circuit_build_times_free_timeouts(cbt);
  442. }
  443. }
  444. /**
  445. * Return the initial default or configured timeout in milliseconds
  446. */
  447. static double
  448. circuit_build_times_get_initial_timeout(void)
  449. {
  450. double timeout;
  451. const or_options_t *options = get_options();
  452. /*
  453. * Check if we have LearnCircuitBuildTimeout, and if we don't,
  454. * always use CircuitBuildTimeout, no questions asked.
  455. */
  456. if (!unit_tests && options->CircuitBuildTimeout) {
  457. timeout = options->CircuitBuildTimeout*1000;
  458. if (!circuit_build_times_disabled(options) &&
  459. timeout < circuit_build_times_min_timeout()) {
  460. log_warn(LD_CIRC, "Config CircuitBuildTimeout too low. Setting to %ds",
  461. circuit_build_times_min_timeout()/1000);
  462. timeout = circuit_build_times_min_timeout();
  463. }
  464. } else {
  465. timeout = circuit_build_times_initial_timeout();
  466. }
  467. return timeout;
  468. }
  469. /**
  470. * Reset the build time state.
  471. *
  472. * Leave estimated parameters, timeout and network liveness intact
  473. * for future use.
  474. */
  475. STATIC void
  476. circuit_build_times_reset(circuit_build_times_t *cbt)
  477. {
  478. memset(cbt->circuit_build_times, 0, sizeof(cbt->circuit_build_times));
  479. cbt->total_build_times = 0;
  480. cbt->build_times_idx = 0;
  481. cbt->have_computed_timeout = 0;
  482. }
  483. /**
  484. * Initialize the buildtimes structure for first use.
  485. *
  486. * Sets the initial timeout values based on either the config setting,
  487. * the consensus param, or the default (CBT_DEFAULT_TIMEOUT_INITIAL_VALUE).
  488. */
  489. void
  490. circuit_build_times_init(circuit_build_times_t *cbt)
  491. {
  492. memset(cbt, 0, sizeof(*cbt));
  493. /*
  494. * Check if we really are using adaptive timeouts, and don't keep
  495. * track of this stuff if not.
  496. */
  497. if (!circuit_build_times_disabled(get_options())) {
  498. cbt->liveness.num_recent_circs =
  499. circuit_build_times_recent_circuit_count(NULL);
  500. cbt->liveness.timeouts_after_firsthop =
  501. tor_calloc(cbt->liveness.num_recent_circs, sizeof(int8_t));
  502. } else {
  503. cbt->liveness.num_recent_circs = 0;
  504. cbt->liveness.timeouts_after_firsthop = NULL;
  505. }
  506. cbt->close_ms = cbt->timeout_ms = circuit_build_times_get_initial_timeout();
  507. cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  508. }
  509. /**
  510. * Free the saved timeouts, if the cbtdisabled consensus parameter got turned
  511. * on or something.
  512. */
  513. void
  514. circuit_build_times_free_timeouts(circuit_build_times_t *cbt)
  515. {
  516. if (!cbt) return;
  517. if (cbt->liveness.timeouts_after_firsthop) {
  518. tor_free(cbt->liveness.timeouts_after_firsthop);
  519. }
  520. cbt->liveness.num_recent_circs = 0;
  521. }
  522. #if 0
  523. /**
  524. * Rewind our build time history by n positions.
  525. */
  526. static void
  527. circuit_build_times_rewind_history(circuit_build_times_t *cbt, int n)
  528. {
  529. int i = 0;
  530. cbt->build_times_idx -= n;
  531. cbt->build_times_idx %= CBT_NCIRCUITS_TO_OBSERVE;
  532. for (i = 0; i < n; i++) {
  533. cbt->circuit_build_times[(i+cbt->build_times_idx)
  534. %CBT_NCIRCUITS_TO_OBSERVE]=0;
  535. }
  536. if (cbt->total_build_times > n) {
  537. cbt->total_build_times -= n;
  538. } else {
  539. cbt->total_build_times = 0;
  540. }
  541. log_info(LD_CIRC,
  542. "Rewound history by %d places. Current index: %d. "
  543. "Total: %d", n, cbt->build_times_idx, cbt->total_build_times);
  544. }
  545. #endif /* 0 */
  546. /**
  547. * Mark this circuit as timed out, but change its purpose
  548. * so that it continues to build, allowing us to measure
  549. * its full build time.
  550. */
  551. void
  552. circuit_build_times_mark_circ_as_measurement_only(origin_circuit_t *circ)
  553. {
  554. control_event_circuit_status(circ,
  555. CIRC_EVENT_FAILED,
  556. END_CIRC_REASON_TIMEOUT);
  557. circuit_change_purpose(TO_CIRCUIT(circ),
  558. CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT);
  559. /* Record this event to check for too many timeouts
  560. * in a row. This function does not record a time value yet
  561. * (we do that later); it only counts the fact that we did
  562. * have a timeout. We also want to avoid double-counting
  563. * already "relaxed" circuits, which are counted in
  564. * circuit_expire_building(). */
  565. if (!circ->relaxed_timeout) {
  566. int first_hop_succeeded = circ->cpath &&
  567. circ->cpath->state == CPATH_STATE_OPEN;
  568. circuit_build_times_count_timeout(
  569. get_circuit_build_times_mutable(),
  570. first_hop_succeeded);
  571. }
  572. }
  573. /**
  574. * Perform the build time work that needs to be done when a circuit
  575. * completes a hop.
  576. *
  577. * This function decides if we should record a circuit's build time
  578. * in our histogram data and other statistics, and if so, records it.
  579. * It also will mark circuits that have already timed out as
  580. * measurement-only circuits, so they can continue to build but
  581. * not get used.
  582. *
  583. * For this, we want to consider circuits that will eventually make
  584. * it to the third hop. For circuits longer than 3 hops, we want to
  585. * record their build time when they reach the third hop, but let
  586. * them continue (and not count them later). For circuits that are
  587. * exactly 3 hops, this will count them when they are completed. We
  588. * do this so that CBT is always gathering statistics on circuits
  589. * of the same length, regardless of their type.
  590. */
  591. void
  592. circuit_build_times_handle_completed_hop(origin_circuit_t *circ)
  593. {
  594. struct timeval end;
  595. long timediff;
  596. /* If circuit build times are disabled, let circuit_expire_building()
  597. * handle it.. */
  598. if (circuit_build_times_disabled(get_options())) {
  599. return;
  600. }
  601. /* Is this a circuit for which the timeout applies in a straight-forward
  602. * way? If so, handle it below. If not, just return (and let
  603. * circuit_expire_building() eventually take care of it).
  604. */
  605. if (!circuit_timeout_want_to_count_circ(circ)) {
  606. return;
  607. }
  608. tor_gettimeofday(&end);
  609. timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
  610. /* Check if we would have timed out already. If so, change the
  611. * purpose here. But don't do any timeout handling here if there
  612. * are no circuits opened yet. Save it for circuit_expire_building()
  613. * (to allow it to handle timeout "relaxing" over there). */
  614. if (timediff > get_circuit_build_timeout_ms() &&
  615. circuit_any_opened_circuits_cached()) {
  616. /* Circuits are allowed to last longer for measurement.
  617. * Switch their purpose and wait. */
  618. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  619. log_info(LD_CIRC,
  620. "Deciding to timeout circuit "U64_FORMAT"\n",
  621. U64_PRINTF_ARG(circ->global_identifier));
  622. circuit_build_times_mark_circ_as_measurement_only(circ);
  623. }
  624. }
  625. /* If the circuit is built to exactly the DEFAULT_ROUTE_LEN,
  626. * add it to our buildtimes. */
  627. if (circuit_get_cpath_opened_len(circ) == DEFAULT_ROUTE_LEN) {
  628. /* If the circuit build time is much greater than we would have cut
  629. * it off at, we probably had a suspend event along this codepath,
  630. * and we should discard the value.
  631. */
  632. if (timediff < 0 ||
  633. timediff > 2*get_circuit_build_close_time_ms()+1000) {
  634. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  635. "Assuming clock jump. Purpose %d (%s)", timediff,
  636. circ->base_.purpose,
  637. circuit_purpose_to_string(circ->base_.purpose));
  638. } else {
  639. /* Only count circuit times if the network is live */
  640. if (circuit_build_times_network_check_live(
  641. get_circuit_build_times())) {
  642. circuit_build_times_add_time(get_circuit_build_times_mutable(),
  643. (build_time_t)timediff);
  644. circuit_build_times_set_timeout(get_circuit_build_times_mutable());
  645. }
  646. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  647. circuit_build_times_network_circ_success(
  648. get_circuit_build_times_mutable());
  649. }
  650. }
  651. }
  652. }
  653. /**
  654. * Add a new build time value <b>time</b> to the set of build times. Time
  655. * units are milliseconds.
  656. *
  657. * circuit_build_times <b>cbt</b> is a circular array, so loop around when
  658. * array is full.
  659. */
  660. int
  661. circuit_build_times_add_time(circuit_build_times_t *cbt, build_time_t btime)
  662. {
  663. if (btime <= 0 || btime > CBT_BUILD_TIME_MAX) {
  664. log_warn(LD_BUG, "Circuit build time is too large (%u)."
  665. "This is probably a bug.", btime);
  666. tor_fragile_assert();
  667. return -1;
  668. }
  669. log_debug(LD_CIRC, "Adding circuit build time %u", btime);
  670. cbt->circuit_build_times[cbt->build_times_idx] = btime;
  671. cbt->build_times_idx = (cbt->build_times_idx + 1) % CBT_NCIRCUITS_TO_OBSERVE;
  672. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  673. cbt->total_build_times++;
  674. if ((cbt->total_build_times % CBT_SAVE_STATE_EVERY) == 0) {
  675. /* Save state every n circuit builds */
  676. if (!unit_tests && !get_options()->AvoidDiskWrites)
  677. or_state_mark_dirty(get_or_state(), 0);
  678. }
  679. return 0;
  680. }
  681. /**
  682. * Return maximum circuit build time
  683. */
  684. static build_time_t
  685. circuit_build_times_max(const circuit_build_times_t *cbt)
  686. {
  687. int i = 0;
  688. build_time_t max_build_time = 0;
  689. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  690. if (cbt->circuit_build_times[i] > max_build_time
  691. && cbt->circuit_build_times[i] != CBT_BUILD_ABANDONED)
  692. max_build_time = cbt->circuit_build_times[i];
  693. }
  694. return max_build_time;
  695. }
  696. #if 0
  697. /** Return minimum circuit build time */
  698. build_time_t
  699. circuit_build_times_min(circuit_build_times_t *cbt)
  700. {
  701. int i = 0;
  702. build_time_t min_build_time = CBT_BUILD_TIME_MAX;
  703. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  704. if (cbt->circuit_build_times[i] && /* 0 <-> uninitialized */
  705. cbt->circuit_build_times[i] < min_build_time)
  706. min_build_time = cbt->circuit_build_times[i];
  707. }
  708. if (min_build_time == CBT_BUILD_TIME_MAX) {
  709. log_warn(LD_CIRC, "No build times less than CBT_BUILD_TIME_MAX!");
  710. }
  711. return min_build_time;
  712. }
  713. #endif /* 0 */
  714. /**
  715. * Calculate and return a histogram for the set of build times.
  716. *
  717. * Returns an allocated array of histrogram bins representing
  718. * the frequency of index*CBT_BIN_WIDTH millisecond
  719. * build times. Also outputs the number of bins in nbins.
  720. *
  721. * The return value must be freed by the caller.
  722. */
  723. static uint32_t *
  724. circuit_build_times_create_histogram(const circuit_build_times_t *cbt,
  725. build_time_t *nbins)
  726. {
  727. uint32_t *histogram;
  728. build_time_t max_build_time = circuit_build_times_max(cbt);
  729. int i, c;
  730. *nbins = 1 + (max_build_time / CBT_BIN_WIDTH);
  731. histogram = tor_calloc(*nbins, sizeof(build_time_t));
  732. // calculate histogram
  733. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  734. if (cbt->circuit_build_times[i] == 0
  735. || cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  736. continue; /* 0 <-> uninitialized */
  737. c = (cbt->circuit_build_times[i] / CBT_BIN_WIDTH);
  738. histogram[c]++;
  739. }
  740. return histogram;
  741. }
  742. /**
  743. * Return the Pareto start-of-curve parameter Xm.
  744. *
  745. * Because we are not a true Pareto curve, we compute this as the
  746. * weighted average of the N most frequent build time bins. N is either
  747. * 1 if we don't have enough circuit build time data collected, or
  748. * determined by the consensus parameter cbtnummodes (default 3).
  749. */
  750. static build_time_t
  751. circuit_build_times_get_xm(circuit_build_times_t *cbt)
  752. {
  753. build_time_t i, nbins;
  754. build_time_t *nth_max_bin;
  755. int32_t bin_counts=0;
  756. build_time_t ret = 0;
  757. uint32_t *histogram = circuit_build_times_create_histogram(cbt, &nbins);
  758. int n=0;
  759. int num_modes = circuit_build_times_default_num_xm_modes();
  760. tor_assert(nbins > 0);
  761. tor_assert(num_modes > 0);
  762. // Only use one mode if < 1000 buildtimes. Not enough data
  763. // for multiple.
  764. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  765. num_modes = 1;
  766. nth_max_bin = tor_calloc(num_modes, sizeof(build_time_t));
  767. /* Determine the N most common build times */
  768. for (i = 0; i < nbins; i++) {
  769. if (histogram[i] >= histogram[nth_max_bin[0]]) {
  770. nth_max_bin[0] = i;
  771. }
  772. for (n = 1; n < num_modes; n++) {
  773. if (histogram[i] >= histogram[nth_max_bin[n]] &&
  774. (!histogram[nth_max_bin[n-1]]
  775. || histogram[i] < histogram[nth_max_bin[n-1]])) {
  776. nth_max_bin[n] = i;
  777. }
  778. }
  779. }
  780. for (n = 0; n < num_modes; n++) {
  781. bin_counts += histogram[nth_max_bin[n]];
  782. ret += CBT_BIN_TO_MS(nth_max_bin[n])*histogram[nth_max_bin[n]];
  783. log_info(LD_CIRC, "Xm mode #%d: %u %u", n, CBT_BIN_TO_MS(nth_max_bin[n]),
  784. histogram[nth_max_bin[n]]);
  785. }
  786. /* The following assert is safe, because we don't get called when we
  787. * haven't observed at least CBT_MIN_MIN_CIRCUITS_TO_OBSERVE circuits. */
  788. tor_assert(bin_counts > 0);
  789. ret /= bin_counts;
  790. tor_free(histogram);
  791. tor_free(nth_max_bin);
  792. return ret;
  793. }
  794. /**
  795. * Output a histogram of current circuit build times to
  796. * the or_state_t state structure.
  797. */
  798. void
  799. circuit_build_times_update_state(const circuit_build_times_t *cbt,
  800. or_state_t *state)
  801. {
  802. uint32_t *histogram;
  803. build_time_t i = 0;
  804. build_time_t nbins = 0;
  805. config_line_t **next, *line;
  806. histogram = circuit_build_times_create_histogram(cbt, &nbins);
  807. // write to state
  808. config_free_lines(state->BuildtimeHistogram);
  809. next = &state->BuildtimeHistogram;
  810. *next = NULL;
  811. state->TotalBuildTimes = cbt->total_build_times;
  812. state->CircuitBuildAbandonedCount = 0;
  813. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  814. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  815. state->CircuitBuildAbandonedCount++;
  816. }
  817. for (i = 0; i < nbins; i++) {
  818. // compress the histogram by skipping the blanks
  819. if (histogram[i] == 0) continue;
  820. *next = line = tor_malloc_zero(sizeof(config_line_t));
  821. line->key = tor_strdup("CircuitBuildTimeBin");
  822. tor_asprintf(&line->value, "%d %d",
  823. CBT_BIN_TO_MS(i), histogram[i]);
  824. next = &(line->next);
  825. }
  826. if (!unit_tests) {
  827. if (!get_options()->AvoidDiskWrites)
  828. or_state_mark_dirty(get_or_state(), 0);
  829. }
  830. tor_free(histogram);
  831. }
  832. /**
  833. * Shuffle the build times array.
  834. *
  835. * Adapted from http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  836. */
  837. static void
  838. circuit_build_times_shuffle_and_store_array(circuit_build_times_t *cbt,
  839. build_time_t *raw_times,
  840. uint32_t num_times)
  841. {
  842. uint32_t n = num_times;
  843. if (num_times > CBT_NCIRCUITS_TO_OBSERVE) {
  844. log_notice(LD_CIRC, "The number of circuit times that this Tor version "
  845. "uses to calculate build times is less than the number stored "
  846. "in your state file. Decreasing the circuit time history from "
  847. "%lu to %d.", (unsigned long)num_times,
  848. CBT_NCIRCUITS_TO_OBSERVE);
  849. }
  850. if (n > INT_MAX-1) {
  851. log_warn(LD_CIRC, "For some insane reasons, you had %lu circuit build "
  852. "observations in your state file. That's far too many; probably "
  853. "there's a bug here.", (unsigned long)n);
  854. n = INT_MAX-1;
  855. }
  856. /* This code can only be run on a compact array */
  857. while (n-- > 1) {
  858. int k = crypto_rand_int(n + 1); /* 0 <= k <= n. */
  859. build_time_t tmp = raw_times[k];
  860. raw_times[k] = raw_times[n];
  861. raw_times[n] = tmp;
  862. }
  863. /* Since the times are now shuffled, take a random CBT_NCIRCUITS_TO_OBSERVE
  864. * subset (ie the first CBT_NCIRCUITS_TO_OBSERVE values) */
  865. for (n = 0; n < MIN(num_times, CBT_NCIRCUITS_TO_OBSERVE); n++) {
  866. circuit_build_times_add_time(cbt, raw_times[n]);
  867. }
  868. }
  869. /**
  870. * Filter old synthetic timeouts that were created before the
  871. * new right-censored Pareto calculation was deployed.
  872. *
  873. * Once all clients before 0.2.1.13-alpha are gone, this code
  874. * will be unused.
  875. */
  876. static int
  877. circuit_build_times_filter_timeouts(circuit_build_times_t *cbt)
  878. {
  879. int num_filtered=0, i=0;
  880. double timeout_rate = 0;
  881. build_time_t max_timeout = 0;
  882. timeout_rate = circuit_build_times_timeout_rate(cbt);
  883. max_timeout = (build_time_t)cbt->close_ms;
  884. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  885. if (cbt->circuit_build_times[i] > max_timeout) {
  886. build_time_t replaced = cbt->circuit_build_times[i];
  887. num_filtered++;
  888. cbt->circuit_build_times[i] = CBT_BUILD_ABANDONED;
  889. log_debug(LD_CIRC, "Replaced timeout %d with %d", replaced,
  890. cbt->circuit_build_times[i]);
  891. }
  892. }
  893. log_info(LD_CIRC,
  894. "We had %d timeouts out of %d build times, "
  895. "and filtered %d above the max of %u",
  896. (int)(cbt->total_build_times*timeout_rate),
  897. cbt->total_build_times, num_filtered, max_timeout);
  898. return num_filtered;
  899. }
  900. /**
  901. * Load histogram from <b>state</b>, shuffling the resulting array
  902. * after we do so. Use this result to estimate parameters and
  903. * calculate the timeout.
  904. *
  905. * Return -1 on error.
  906. */
  907. int
  908. circuit_build_times_parse_state(circuit_build_times_t *cbt,
  909. or_state_t *state)
  910. {
  911. int tot_values = 0;
  912. uint32_t loaded_cnt = 0, N = 0;
  913. config_line_t *line;
  914. int i;
  915. build_time_t *loaded_times;
  916. int err = 0;
  917. circuit_build_times_init(cbt);
  918. if (circuit_build_times_disabled(get_options())) {
  919. return 0;
  920. }
  921. /* build_time_t 0 means uninitialized */
  922. loaded_times = tor_calloc(state->TotalBuildTimes, sizeof(build_time_t));
  923. for (line = state->BuildtimeHistogram; line; line = line->next) {
  924. smartlist_t *args = smartlist_new();
  925. smartlist_split_string(args, line->value, " ",
  926. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  927. if (smartlist_len(args) < 2) {
  928. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  929. "Too few arguments to CircuitBuildTime");
  930. err = 1;
  931. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  932. smartlist_free(args);
  933. break;
  934. } else {
  935. const char *ms_str = smartlist_get(args,0);
  936. const char *count_str = smartlist_get(args,1);
  937. uint32_t count, k;
  938. build_time_t ms;
  939. int ok;
  940. ms = (build_time_t)tor_parse_ulong(ms_str, 10, 0,
  941. CBT_BUILD_TIME_MAX, &ok, NULL);
  942. if (!ok) {
  943. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  944. "Unparsable bin number");
  945. err = 1;
  946. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  947. smartlist_free(args);
  948. break;
  949. }
  950. count = (uint32_t)tor_parse_ulong(count_str, 10, 0,
  951. UINT32_MAX, &ok, NULL);
  952. if (!ok) {
  953. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  954. "Unparsable bin count");
  955. err = 1;
  956. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  957. smartlist_free(args);
  958. break;
  959. }
  960. if (loaded_cnt+count+ (unsigned)state->CircuitBuildAbandonedCount
  961. > (unsigned) state->TotalBuildTimes) {
  962. log_warn(LD_CIRC,
  963. "Too many build times in state file. "
  964. "Stopping short before %d",
  965. loaded_cnt+count);
  966. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  967. smartlist_free(args);
  968. break;
  969. }
  970. for (k = 0; k < count; k++) {
  971. loaded_times[loaded_cnt++] = ms;
  972. }
  973. N++;
  974. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  975. smartlist_free(args);
  976. }
  977. }
  978. log_info(LD_CIRC,
  979. "Adding %d timeouts.", state->CircuitBuildAbandonedCount);
  980. for (i=0; i < state->CircuitBuildAbandonedCount; i++) {
  981. loaded_times[loaded_cnt++] = CBT_BUILD_ABANDONED;
  982. }
  983. if (loaded_cnt != (unsigned)state->TotalBuildTimes) {
  984. log_warn(LD_CIRC,
  985. "Corrupt state file? Build times count mismatch. "
  986. "Read %d times, but file says %d", loaded_cnt,
  987. state->TotalBuildTimes);
  988. err = 1;
  989. circuit_build_times_reset(cbt);
  990. goto done;
  991. }
  992. circuit_build_times_shuffle_and_store_array(cbt, loaded_times, loaded_cnt);
  993. /* Verify that we didn't overwrite any indexes */
  994. for (i=0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  995. if (!cbt->circuit_build_times[i])
  996. break;
  997. tot_values++;
  998. }
  999. log_info(LD_CIRC,
  1000. "Loaded %d/%d values from %d lines in circuit time histogram",
  1001. tot_values, cbt->total_build_times, N);
  1002. if (cbt->total_build_times != tot_values
  1003. || cbt->total_build_times > CBT_NCIRCUITS_TO_OBSERVE) {
  1004. log_warn(LD_CIRC,
  1005. "Corrupt state file? Shuffled build times mismatch. "
  1006. "Read %d times, but file says %d", tot_values,
  1007. state->TotalBuildTimes);
  1008. err = 1;
  1009. circuit_build_times_reset(cbt);
  1010. goto done;
  1011. }
  1012. circuit_build_times_set_timeout(cbt);
  1013. if (!state->CircuitBuildAbandonedCount && cbt->total_build_times) {
  1014. circuit_build_times_filter_timeouts(cbt);
  1015. }
  1016. done:
  1017. tor_free(loaded_times);
  1018. return err ? -1 : 0;
  1019. }
  1020. /**
  1021. * Estimates the Xm and Alpha parameters using
  1022. * http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
  1023. *
  1024. * The notable difference is that we use mode instead of min to estimate Xm.
  1025. * This is because our distribution is frechet-like. We claim this is
  1026. * an acceptable approximation because we are only concerned with the
  1027. * accuracy of the CDF of the tail.
  1028. */
  1029. STATIC int
  1030. circuit_build_times_update_alpha(circuit_build_times_t *cbt)
  1031. {
  1032. build_time_t *x=cbt->circuit_build_times;
  1033. double a = 0;
  1034. int n=0,i=0,abandoned_count=0;
  1035. build_time_t max_time=0;
  1036. /* http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation */
  1037. /* We sort of cheat here and make our samples slightly more pareto-like
  1038. * and less frechet-like. */
  1039. cbt->Xm = circuit_build_times_get_xm(cbt);
  1040. tor_assert(cbt->Xm > 0);
  1041. for (i=0; i< CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1042. if (!x[i]) {
  1043. continue;
  1044. }
  1045. if (x[i] < cbt->Xm) {
  1046. a += tor_mathlog(cbt->Xm);
  1047. } else if (x[i] == CBT_BUILD_ABANDONED) {
  1048. abandoned_count++;
  1049. } else {
  1050. a += tor_mathlog(x[i]);
  1051. if (x[i] > max_time)
  1052. max_time = x[i];
  1053. }
  1054. n++;
  1055. }
  1056. /*
  1057. * We are erring and asserting here because this can only happen
  1058. * in codepaths other than startup. The startup state parsing code
  1059. * performs this same check, and resets state if it hits it. If we
  1060. * hit it at runtime, something serious has gone wrong.
  1061. */
  1062. if (n!=cbt->total_build_times) {
  1063. log_err(LD_CIRC, "Discrepancy in build times count: %d vs %d", n,
  1064. cbt->total_build_times);
  1065. }
  1066. tor_assert(n==cbt->total_build_times);
  1067. if (max_time <= 0) {
  1068. /* This can happen if Xm is actually the *maximum* value in the set.
  1069. * It can also happen if we've abandoned every single circuit somehow.
  1070. * In either case, tell the caller not to compute a new build timeout. */
  1071. log_warn(LD_BUG,
  1072. "Could not determine largest build time (%d). "
  1073. "Xm is %dms and we've abandoned %d out of %d circuits.", max_time,
  1074. cbt->Xm, abandoned_count, n);
  1075. return 0;
  1076. }
  1077. a += abandoned_count*tor_mathlog(max_time);
  1078. a -= n*tor_mathlog(cbt->Xm);
  1079. // Estimator comes from Eq #4 in:
  1080. // "Bayesian estimation based on trimmed samples from Pareto populations"
  1081. // by Arturo J. Fernández. We are right-censored only.
  1082. a = (n-abandoned_count)/a;
  1083. cbt->alpha = a;
  1084. return 1;
  1085. }
  1086. /**
  1087. * This is the Pareto Quantile Function. It calculates the point x
  1088. * in the distribution such that F(x) = quantile (ie quantile*100%
  1089. * of the mass of the density function is below x on the curve).
  1090. *
  1091. * We use it to calculate the timeout and also to generate synthetic
  1092. * values of time for circuits that timeout before completion.
  1093. *
  1094. * See http://en.wikipedia.org/wiki/Quantile_function,
  1095. * http://en.wikipedia.org/wiki/Inverse_transform_sampling and
  1096. * http://en.wikipedia.org/wiki/Pareto_distribution#Generating_a_
  1097. * random_sample_from_Pareto_distribution
  1098. * That's right. I'll cite wikipedia all day long.
  1099. *
  1100. * Return value is in milliseconds, clamped to INT32_MAX.
  1101. */
  1102. STATIC double
  1103. circuit_build_times_calculate_timeout(circuit_build_times_t *cbt,
  1104. double quantile)
  1105. {
  1106. double ret;
  1107. tor_assert(quantile >= 0);
  1108. tor_assert(1.0-quantile > 0);
  1109. tor_assert(cbt->Xm > 0);
  1110. /* If either alpha or p are 0, we would divide by zero, yielding an
  1111. * infinite (double) result; which would be clamped to INT32_MAX.
  1112. * Instead, initialise ret to INT32_MAX, and skip over these
  1113. * potentially illegal/trapping divides by zero.
  1114. */
  1115. ret = INT32_MAX;
  1116. if (cbt->alpha > 0) {
  1117. double p;
  1118. p = pow(1.0-quantile,1.0/cbt->alpha);
  1119. if (p > 0) {
  1120. ret = cbt->Xm/p;
  1121. }
  1122. }
  1123. if (ret > INT32_MAX) {
  1124. ret = INT32_MAX;
  1125. }
  1126. tor_assert(ret > 0);
  1127. return ret;
  1128. }
  1129. #ifdef TOR_UNIT_TESTS
  1130. /** Pareto CDF */
  1131. double
  1132. circuit_build_times_cdf(circuit_build_times_t *cbt, double x)
  1133. {
  1134. double ret;
  1135. tor_assert(cbt->Xm > 0);
  1136. ret = 1.0-pow(cbt->Xm/x,cbt->alpha);
  1137. tor_assert(0 <= ret && ret <= 1.0);
  1138. return ret;
  1139. }
  1140. #endif /* defined(TOR_UNIT_TESTS) */
  1141. #ifdef TOR_UNIT_TESTS
  1142. /**
  1143. * Generate a synthetic time using our distribution parameters.
  1144. *
  1145. * The return value will be within the [q_lo, q_hi) quantile points
  1146. * on the CDF.
  1147. */
  1148. build_time_t
  1149. circuit_build_times_generate_sample(circuit_build_times_t *cbt,
  1150. double q_lo, double q_hi)
  1151. {
  1152. double randval = crypto_rand_double();
  1153. build_time_t ret;
  1154. double u;
  1155. /* Generate between [q_lo, q_hi) */
  1156. /*XXXX This is what nextafter is supposed to be for; we should use it on the
  1157. * platforms that support it. */
  1158. q_hi -= 1.0/(INT32_MAX);
  1159. tor_assert(q_lo >= 0);
  1160. tor_assert(q_hi < 1);
  1161. tor_assert(q_lo < q_hi);
  1162. u = q_lo + (q_hi-q_lo)*randval;
  1163. tor_assert(0 <= u && u < 1.0);
  1164. /* circuit_build_times_calculate_timeout returns <= INT32_MAX */
  1165. ret = (build_time_t)
  1166. tor_lround(circuit_build_times_calculate_timeout(cbt, u));
  1167. tor_assert(ret > 0);
  1168. return ret;
  1169. }
  1170. #endif /* defined(TOR_UNIT_TESTS) */
  1171. #ifdef TOR_UNIT_TESTS
  1172. /**
  1173. * Estimate an initial alpha parameter by solving the quantile
  1174. * function with a quantile point and a specific timeout value.
  1175. */
  1176. void
  1177. circuit_build_times_initial_alpha(circuit_build_times_t *cbt,
  1178. double quantile, double timeout_ms)
  1179. {
  1180. // Q(u) = Xm/((1-u)^(1/a))
  1181. // Q(0.8) = Xm/((1-0.8))^(1/a)) = CircBuildTimeout
  1182. // CircBuildTimeout = Xm/((1-0.8))^(1/a))
  1183. // CircBuildTimeout = Xm*((1-0.8))^(-1/a))
  1184. // ln(CircBuildTimeout) = ln(Xm)+ln(((1-0.8)))*(-1/a)
  1185. // -ln(1-0.8)/(ln(CircBuildTimeout)-ln(Xm))=a
  1186. tor_assert(quantile >= 0);
  1187. tor_assert(cbt->Xm > 0);
  1188. cbt->alpha = tor_mathlog(1.0-quantile)/
  1189. (tor_mathlog(cbt->Xm)-tor_mathlog(timeout_ms));
  1190. tor_assert(cbt->alpha > 0);
  1191. }
  1192. #endif /* defined(TOR_UNIT_TESTS) */
  1193. /**
  1194. * Returns true if we need circuits to be built
  1195. */
  1196. int
  1197. circuit_build_times_needs_circuits(const circuit_build_times_t *cbt)
  1198. {
  1199. /* Return true if < MIN_CIRCUITS_TO_OBSERVE */
  1200. return !circuit_build_times_enough_to_compute(cbt);
  1201. }
  1202. /**
  1203. * Returns true if we should build a timeout test circuit
  1204. * right now.
  1205. */
  1206. int
  1207. circuit_build_times_needs_circuits_now(const circuit_build_times_t *cbt)
  1208. {
  1209. return circuit_build_times_needs_circuits(cbt) &&
  1210. approx_time()-cbt->last_circ_at > circuit_build_times_test_frequency();
  1211. }
  1212. /**
  1213. * How long should we be unreachable before we think we need to check if
  1214. * our published IP address has changed.
  1215. */
  1216. #define CIRCUIT_TIMEOUT_BEFORE_RECHECK_IP (60*3)
  1217. /**
  1218. * Called to indicate that the network showed some signs of liveness,
  1219. * i.e. we received a cell.
  1220. *
  1221. * This is used by circuit_build_times_network_check_live() to decide
  1222. * if we should record the circuit build timeout or not.
  1223. *
  1224. * This function is called every time we receive a cell. Avoid
  1225. * syscalls, events, and other high-intensity work.
  1226. */
  1227. void
  1228. circuit_build_times_network_is_live(circuit_build_times_t *cbt)
  1229. {
  1230. time_t now = approx_time();
  1231. if (cbt->liveness.nonlive_timeouts > 0) {
  1232. time_t time_since_live = now - cbt->liveness.network_last_live;
  1233. log_notice(LD_CIRC,
  1234. "Tor now sees network activity. Restoring circuit build "
  1235. "timeout recording. Network was down for %d seconds "
  1236. "during %d circuit attempts.",
  1237. (int)time_since_live,
  1238. cbt->liveness.nonlive_timeouts);
  1239. if (time_since_live > CIRCUIT_TIMEOUT_BEFORE_RECHECK_IP)
  1240. reschedule_descriptor_update_check();
  1241. }
  1242. cbt->liveness.network_last_live = now;
  1243. cbt->liveness.nonlive_timeouts = 0;
  1244. /* Tell control.c */
  1245. control_event_network_liveness_update(1);
  1246. }
  1247. /**
  1248. * Called to indicate that we "completed" a circuit. Because this circuit
  1249. * succeeded, it doesn't count as a timeout-after-the-first-hop.
  1250. *
  1251. * (For the purposes of the cbt code, we consider a circuit "completed" if
  1252. * it has 3 hops, regardless of its final hop count. We do this because
  1253. * we're trying to answer the question, "how long should a circuit take to
  1254. * reach the 3-hop count".)
  1255. *
  1256. * This is used by circuit_build_times_network_check_changed() to determine
  1257. * if we had too many recent timeouts and need to reset our learned timeout
  1258. * to something higher.
  1259. */
  1260. void
  1261. circuit_build_times_network_circ_success(circuit_build_times_t *cbt)
  1262. {
  1263. /* Check for NULLness because we might not be using adaptive timeouts */
  1264. if (cbt->liveness.timeouts_after_firsthop &&
  1265. cbt->liveness.num_recent_circs > 0) {
  1266. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1267. = 0;
  1268. cbt->liveness.after_firsthop_idx++;
  1269. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1270. }
  1271. }
  1272. /**
  1273. * A circuit just timed out. If it failed after the first hop, record it
  1274. * in our history for later deciding if the network speed has changed.
  1275. *
  1276. * This is used by circuit_build_times_network_check_changed() to determine
  1277. * if we had too many recent timeouts and need to reset our learned timeout
  1278. * to something higher.
  1279. */
  1280. static void
  1281. circuit_build_times_network_timeout(circuit_build_times_t *cbt,
  1282. int did_onehop)
  1283. {
  1284. /* Check for NULLness because we might not be using adaptive timeouts */
  1285. if (cbt->liveness.timeouts_after_firsthop &&
  1286. cbt->liveness.num_recent_circs > 0) {
  1287. if (did_onehop) {
  1288. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1289. = 1;
  1290. cbt->liveness.after_firsthop_idx++;
  1291. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1292. }
  1293. }
  1294. }
  1295. /**
  1296. * A circuit was just forcibly closed. If there has been no recent network
  1297. * activity at all, but this circuit was launched back when we thought the
  1298. * network was live, increment the number of "nonlive" circuit timeouts.
  1299. *
  1300. * This is used by circuit_build_times_network_check_live() to decide
  1301. * if we should record the circuit build timeout or not.
  1302. */
  1303. static void
  1304. circuit_build_times_network_close(circuit_build_times_t *cbt,
  1305. int did_onehop, time_t start_time)
  1306. {
  1307. time_t now = time(NULL);
  1308. /*
  1309. * Check if this is a timeout that was for a circuit that spent its
  1310. * entire existence during a time where we have had no network activity.
  1311. */
  1312. if (cbt->liveness.network_last_live < start_time) {
  1313. if (did_onehop) {
  1314. char last_live_buf[ISO_TIME_LEN+1];
  1315. char start_time_buf[ISO_TIME_LEN+1];
  1316. char now_buf[ISO_TIME_LEN+1];
  1317. format_local_iso_time(last_live_buf, cbt->liveness.network_last_live);
  1318. format_local_iso_time(start_time_buf, start_time);
  1319. format_local_iso_time(now_buf, now);
  1320. log_notice(LD_CIRC,
  1321. "A circuit somehow completed a hop while the network was "
  1322. "not live. The network was last live at %s, but the circuit "
  1323. "launched at %s. It's now %s. This could mean your clock "
  1324. "changed.", last_live_buf, start_time_buf, now_buf);
  1325. }
  1326. cbt->liveness.nonlive_timeouts++;
  1327. if (cbt->liveness.nonlive_timeouts == 1) {
  1328. log_notice(LD_CIRC,
  1329. "Tor has not observed any network activity for the past %d "
  1330. "seconds. Disabling circuit build timeout recording.",
  1331. (int)(now - cbt->liveness.network_last_live));
  1332. /* Tell control.c */
  1333. control_event_network_liveness_update(0);
  1334. } else {
  1335. log_info(LD_CIRC,
  1336. "Got non-live timeout. Current count is: %d",
  1337. cbt->liveness.nonlive_timeouts);
  1338. }
  1339. }
  1340. }
  1341. /**
  1342. * When the network is not live, we do not record circuit build times.
  1343. *
  1344. * The network is considered not live if there has been at least one
  1345. * circuit build that began and ended (had its close_ms measurement
  1346. * period expire) since we last received a cell.
  1347. *
  1348. * Also has the side effect of rewinding the circuit time history
  1349. * in the case of recent liveness changes.
  1350. */
  1351. int
  1352. circuit_build_times_network_check_live(const circuit_build_times_t *cbt)
  1353. {
  1354. if (cbt->liveness.nonlive_timeouts > 0) {
  1355. return 0;
  1356. }
  1357. return 1;
  1358. }
  1359. /**
  1360. * Returns true if we have seen more than MAX_RECENT_TIMEOUT_COUNT of
  1361. * the past RECENT_CIRCUITS time out after the first hop. Used to detect
  1362. * if the network connection has changed significantly, and if so,
  1363. * resets our circuit build timeout to the default.
  1364. *
  1365. * Also resets the entire timeout history in this case and causes us
  1366. * to restart the process of building test circuits and estimating a
  1367. * new timeout.
  1368. */
  1369. STATIC int
  1370. circuit_build_times_network_check_changed(circuit_build_times_t *cbt)
  1371. {
  1372. int total_build_times = cbt->total_build_times;
  1373. int timeout_count=0;
  1374. int i;
  1375. if (cbt->liveness.timeouts_after_firsthop &&
  1376. cbt->liveness.num_recent_circs > 0) {
  1377. /* how many of our recent circuits made it to the first hop but then
  1378. * timed out? */
  1379. for (i = 0; i < cbt->liveness.num_recent_circs; i++) {
  1380. timeout_count += cbt->liveness.timeouts_after_firsthop[i];
  1381. }
  1382. }
  1383. /* If 80% of our recent circuits are timing out after the first hop,
  1384. * we need to re-estimate a new initial alpha and timeout. */
  1385. if (timeout_count < circuit_build_times_max_timeouts()) {
  1386. return 0;
  1387. }
  1388. circuit_build_times_reset(cbt);
  1389. if (cbt->liveness.timeouts_after_firsthop &&
  1390. cbt->liveness.num_recent_circs > 0) {
  1391. memset(cbt->liveness.timeouts_after_firsthop, 0,
  1392. sizeof(*cbt->liveness.timeouts_after_firsthop)*
  1393. cbt->liveness.num_recent_circs);
  1394. }
  1395. cbt->liveness.after_firsthop_idx = 0;
  1396. #define MAX_TIMEOUT ((int32_t) (INT32_MAX/2))
  1397. /* Check to see if this has happened before. If so, double the timeout
  1398. * to give clients on abysmally bad network connections a shot at access */
  1399. if (cbt->timeout_ms >= circuit_build_times_get_initial_timeout()) {
  1400. if (cbt->timeout_ms > MAX_TIMEOUT || cbt->close_ms > MAX_TIMEOUT) {
  1401. log_warn(LD_CIRC, "Insanely large circuit build timeout value. "
  1402. "(timeout = %fmsec, close = %fmsec)",
  1403. cbt->timeout_ms, cbt->close_ms);
  1404. } else {
  1405. cbt->timeout_ms *= 2;
  1406. cbt->close_ms *= 2;
  1407. }
  1408. } else {
  1409. cbt->close_ms = cbt->timeout_ms
  1410. = circuit_build_times_get_initial_timeout();
  1411. }
  1412. #undef MAX_TIMEOUT
  1413. cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  1414. log_notice(LD_CIRC,
  1415. "Your network connection speed appears to have changed. Resetting "
  1416. "timeout to %lds after %d timeouts and %d buildtimes.",
  1417. tor_lround(cbt->timeout_ms/1000), timeout_count,
  1418. total_build_times);
  1419. return 1;
  1420. }
  1421. /**
  1422. * Count the number of timeouts in a set of cbt data.
  1423. */
  1424. double
  1425. circuit_build_times_timeout_rate(const circuit_build_times_t *cbt)
  1426. {
  1427. int i=0,timeouts=0;
  1428. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1429. if (cbt->circuit_build_times[i] >= cbt->timeout_ms) {
  1430. timeouts++;
  1431. }
  1432. }
  1433. if (!cbt->total_build_times)
  1434. return 0;
  1435. return ((double)timeouts)/cbt->total_build_times;
  1436. }
  1437. /**
  1438. * Count the number of closed circuits in a set of cbt data.
  1439. */
  1440. double
  1441. circuit_build_times_close_rate(const circuit_build_times_t *cbt)
  1442. {
  1443. int i=0,closed=0;
  1444. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1445. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED) {
  1446. closed++;
  1447. }
  1448. }
  1449. if (!cbt->total_build_times)
  1450. return 0;
  1451. return ((double)closed)/cbt->total_build_times;
  1452. }
  1453. /**
  1454. * Store a timeout as a synthetic value.
  1455. *
  1456. * Returns true if the store was successful and we should possibly
  1457. * update our timeout estimate.
  1458. */
  1459. int
  1460. circuit_build_times_count_close(circuit_build_times_t *cbt,
  1461. int did_onehop,
  1462. time_t start_time)
  1463. {
  1464. if (circuit_build_times_disabled(get_options())) {
  1465. cbt->close_ms = cbt->timeout_ms
  1466. = circuit_build_times_get_initial_timeout();
  1467. return 0;
  1468. }
  1469. /* Record this force-close to help determine if the network is dead */
  1470. circuit_build_times_network_close(cbt, did_onehop, start_time);
  1471. /* Only count timeouts if network is live.. */
  1472. if (!circuit_build_times_network_check_live(cbt)) {
  1473. return 0;
  1474. }
  1475. circuit_build_times_add_time(cbt, CBT_BUILD_ABANDONED);
  1476. return 1;
  1477. }
  1478. /**
  1479. * Update timeout counts to determine if we need to expire
  1480. * our build time history due to excessive timeouts.
  1481. *
  1482. * We do not record any actual time values at this stage;
  1483. * we are only interested in recording the fact that a timeout
  1484. * happened. We record the time values via
  1485. * circuit_build_times_count_close() and circuit_build_times_add_time().
  1486. */
  1487. void
  1488. circuit_build_times_count_timeout(circuit_build_times_t *cbt,
  1489. int did_onehop)
  1490. {
  1491. if (circuit_build_times_disabled(get_options())) {
  1492. cbt->close_ms = cbt->timeout_ms
  1493. = circuit_build_times_get_initial_timeout();
  1494. return;
  1495. }
  1496. /* Register the fact that a timeout just occurred. */
  1497. circuit_build_times_network_timeout(cbt, did_onehop);
  1498. /* If there are a ton of timeouts, we should reset
  1499. * the circuit build timeout. */
  1500. circuit_build_times_network_check_changed(cbt);
  1501. }
  1502. /**
  1503. * Estimate a new timeout based on history and set our timeout
  1504. * variable accordingly.
  1505. */
  1506. static int
  1507. circuit_build_times_set_timeout_worker(circuit_build_times_t *cbt)
  1508. {
  1509. build_time_t max_time;
  1510. if (!circuit_build_times_enough_to_compute(cbt))
  1511. return 0;
  1512. if (!circuit_build_times_update_alpha(cbt))
  1513. return 0;
  1514. cbt->timeout_ms = circuit_build_times_calculate_timeout(cbt,
  1515. circuit_build_times_quantile_cutoff());
  1516. cbt->close_ms = circuit_build_times_calculate_timeout(cbt,
  1517. circuit_build_times_close_quantile());
  1518. max_time = circuit_build_times_max(cbt);
  1519. if (cbt->timeout_ms > max_time) {
  1520. log_info(LD_CIRC,
  1521. "Circuit build timeout of %dms is beyond the maximum build "
  1522. "time we have ever observed. Capping it to %dms.",
  1523. (int)cbt->timeout_ms, max_time);
  1524. cbt->timeout_ms = max_time;
  1525. }
  1526. if (max_time < INT32_MAX/2 && cbt->close_ms > 2*max_time) {
  1527. log_info(LD_CIRC,
  1528. "Circuit build measurement period of %dms is more than twice "
  1529. "the maximum build time we have ever observed. Capping it to "
  1530. "%dms.", (int)cbt->close_ms, 2*max_time);
  1531. cbt->close_ms = 2*max_time;
  1532. }
  1533. /* Sometimes really fast guard nodes give us such a steep curve
  1534. * that this ends up being not that much greater than timeout_ms.
  1535. * Make it be at least 1 min to handle this case. */
  1536. cbt->close_ms = MAX(cbt->close_ms, circuit_build_times_initial_timeout());
  1537. cbt->have_computed_timeout = 1;
  1538. return 1;
  1539. }
  1540. /**
  1541. * Exposed function to compute a new timeout. Dispatches events and
  1542. * also filters out extremely high timeout values.
  1543. */
  1544. void
  1545. circuit_build_times_set_timeout(circuit_build_times_t *cbt)
  1546. {
  1547. long prev_timeout = tor_lround(cbt->timeout_ms/1000);
  1548. double timeout_rate;
  1549. /*
  1550. * Just return if we aren't using adaptive timeouts
  1551. */
  1552. if (circuit_build_times_disabled(get_options()))
  1553. return;
  1554. if (!circuit_build_times_set_timeout_worker(cbt))
  1555. return;
  1556. if (cbt->timeout_ms < circuit_build_times_min_timeout()) {
  1557. log_info(LD_CIRC, "Set buildtimeout to low value %fms. Setting to %dms",
  1558. cbt->timeout_ms, circuit_build_times_min_timeout());
  1559. cbt->timeout_ms = circuit_build_times_min_timeout();
  1560. if (cbt->close_ms < cbt->timeout_ms) {
  1561. /* This shouldn't happen because of MAX() in timeout_worker above,
  1562. * but doing it just in case */
  1563. cbt->close_ms = circuit_build_times_initial_timeout();
  1564. }
  1565. }
  1566. cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_COMPUTED);
  1567. timeout_rate = circuit_build_times_timeout_rate(cbt);
  1568. if (prev_timeout > tor_lround(cbt->timeout_ms/1000)) {
  1569. log_info(LD_CIRC,
  1570. "Based on %d circuit times, it looks like we don't need to "
  1571. "wait so long for circuits to finish. We will now assume a "
  1572. "circuit is too slow to use after waiting %ld seconds.",
  1573. cbt->total_build_times,
  1574. tor_lround(cbt->timeout_ms/1000));
  1575. log_info(LD_CIRC,
  1576. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1577. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1578. timeout_rate);
  1579. } else if (prev_timeout < tor_lround(cbt->timeout_ms/1000)) {
  1580. log_info(LD_CIRC,
  1581. "Based on %d circuit times, it looks like we need to wait "
  1582. "longer for circuits to finish. We will now assume a "
  1583. "circuit is too slow to use after waiting %ld seconds.",
  1584. cbt->total_build_times,
  1585. tor_lround(cbt->timeout_ms/1000));
  1586. log_info(LD_CIRC,
  1587. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1588. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1589. timeout_rate);
  1590. } else {
  1591. log_info(LD_CIRC,
  1592. "Set circuit build timeout to %lds (%fms, %fms, Xm: %d, a: %f,"
  1593. " r: %f) based on %d circuit times",
  1594. tor_lround(cbt->timeout_ms/1000),
  1595. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha, timeout_rate,
  1596. cbt->total_build_times);
  1597. }
  1598. }
  1599. #ifdef TOR_UNIT_TESTS
  1600. /** Make a note that we're running unit tests (rather than running Tor
  1601. * itself), so we avoid clobbering our state file. */
  1602. void
  1603. circuitbuild_running_unit_tests(void)
  1604. {
  1605. unit_tests = 1;
  1606. }
  1607. #endif /* defined(TOR_UNIT_TESTS) */
  1608. void
  1609. circuit_build_times_update_last_circ(circuit_build_times_t *cbt)
  1610. {
  1611. cbt->last_circ_at = approx_time();
  1612. }
  1613. static void
  1614. cbt_control_event_buildtimeout_set(const circuit_build_times_t *cbt,
  1615. buildtimeout_set_event_t type)
  1616. {
  1617. char *args = NULL;
  1618. double qnt;
  1619. switch (type) {
  1620. case BUILDTIMEOUT_SET_EVENT_RESET:
  1621. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  1622. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  1623. qnt = 1.0;
  1624. break;
  1625. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  1626. case BUILDTIMEOUT_SET_EVENT_RESUME:
  1627. default:
  1628. qnt = circuit_build_times_quantile_cutoff();
  1629. break;
  1630. }
  1631. tor_asprintf(&args, "TOTAL_TIMES=%lu "
  1632. "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
  1633. "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f",
  1634. (unsigned long)cbt->total_build_times,
  1635. (unsigned long)cbt->timeout_ms,
  1636. (unsigned long)cbt->Xm, cbt->alpha, qnt,
  1637. circuit_build_times_timeout_rate(cbt),
  1638. (unsigned long)cbt->close_ms,
  1639. circuit_build_times_close_rate(cbt));
  1640. control_event_buildtimeout_set(type, args);
  1641. tor_free(args);
  1642. }