circuitstats.c 61 KB

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