circuitstats.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939
  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. /* bin_counts can become zero if all of our last CBT_NCIRCUITS_TO_OBSERVE
  799. * circuits were abandoned before they completed. This shouldn't happen,
  800. * though. We should have reset/re-learned a lower timeout first. */
  801. if (bin_counts == 0) {
  802. ret = 0;
  803. log_warn(LD_CIRC,
  804. "No valid circuit build time data out of %d times, %u modes, "
  805. "have_timeout=%d, %lfms", cbt->total_build_times, num_modes,
  806. cbt->have_computed_timeout, cbt->timeout_ms);
  807. goto done;
  808. }
  809. tor_assert(bin_counts > 0);
  810. ret /= bin_counts;
  811. done:
  812. tor_free(histogram);
  813. tor_free(nth_max_bin);
  814. return ret;
  815. }
  816. /**
  817. * Output a histogram of current circuit build times to
  818. * the or_state_t state structure.
  819. */
  820. void
  821. circuit_build_times_update_state(const circuit_build_times_t *cbt,
  822. or_state_t *state)
  823. {
  824. uint32_t *histogram;
  825. build_time_t i = 0;
  826. build_time_t nbins = 0;
  827. config_line_t **next, *line;
  828. histogram = circuit_build_times_create_histogram(cbt, &nbins);
  829. // write to state
  830. config_free_lines(state->BuildtimeHistogram);
  831. next = &state->BuildtimeHistogram;
  832. *next = NULL;
  833. state->TotalBuildTimes = cbt->total_build_times;
  834. state->CircuitBuildAbandonedCount = 0;
  835. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  836. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  837. state->CircuitBuildAbandonedCount++;
  838. }
  839. for (i = 0; i < nbins; i++) {
  840. // compress the histogram by skipping the blanks
  841. if (histogram[i] == 0) continue;
  842. *next = line = tor_malloc_zero(sizeof(config_line_t));
  843. line->key = tor_strdup("CircuitBuildTimeBin");
  844. tor_asprintf(&line->value, "%d %d",
  845. CBT_BIN_TO_MS(i), histogram[i]);
  846. next = &(line->next);
  847. }
  848. if (!unit_tests) {
  849. if (!get_options()->AvoidDiskWrites)
  850. or_state_mark_dirty(get_or_state(), 0);
  851. }
  852. tor_free(histogram);
  853. }
  854. /**
  855. * Shuffle the build times array.
  856. *
  857. * Adapted from http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  858. */
  859. static void
  860. circuit_build_times_shuffle_and_store_array(circuit_build_times_t *cbt,
  861. build_time_t *raw_times,
  862. uint32_t num_times)
  863. {
  864. uint32_t n = num_times;
  865. if (num_times > CBT_NCIRCUITS_TO_OBSERVE) {
  866. log_notice(LD_CIRC, "The number of circuit times that this Tor version "
  867. "uses to calculate build times is less than the number stored "
  868. "in your state file. Decreasing the circuit time history from "
  869. "%lu to %d.", (unsigned long)num_times,
  870. CBT_NCIRCUITS_TO_OBSERVE);
  871. }
  872. if (n > INT_MAX-1) {
  873. log_warn(LD_CIRC, "For some insane reasons, you had %lu circuit build "
  874. "observations in your state file. That's far too many; probably "
  875. "there's a bug here.", (unsigned long)n);
  876. n = INT_MAX-1;
  877. }
  878. /* This code can only be run on a compact array */
  879. while (n-- > 1) {
  880. int k = crypto_rand_int(n + 1); /* 0 <= k <= n. */
  881. build_time_t tmp = raw_times[k];
  882. raw_times[k] = raw_times[n];
  883. raw_times[n] = tmp;
  884. }
  885. /* Since the times are now shuffled, take a random CBT_NCIRCUITS_TO_OBSERVE
  886. * subset (ie the first CBT_NCIRCUITS_TO_OBSERVE values) */
  887. for (n = 0; n < MIN(num_times, CBT_NCIRCUITS_TO_OBSERVE); n++) {
  888. circuit_build_times_add_time(cbt, raw_times[n]);
  889. }
  890. }
  891. /**
  892. * Filter old synthetic timeouts that were created before the
  893. * new right-censored Pareto calculation was deployed.
  894. *
  895. * Once all clients before 0.2.1.13-alpha are gone, this code
  896. * will be unused.
  897. */
  898. static int
  899. circuit_build_times_filter_timeouts(circuit_build_times_t *cbt)
  900. {
  901. int num_filtered=0, i=0;
  902. double timeout_rate = 0;
  903. build_time_t max_timeout = 0;
  904. timeout_rate = circuit_build_times_timeout_rate(cbt);
  905. max_timeout = (build_time_t)cbt->close_ms;
  906. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  907. if (cbt->circuit_build_times[i] > max_timeout) {
  908. build_time_t replaced = cbt->circuit_build_times[i];
  909. num_filtered++;
  910. cbt->circuit_build_times[i] = CBT_BUILD_ABANDONED;
  911. log_debug(LD_CIRC, "Replaced timeout %d with %d", replaced,
  912. cbt->circuit_build_times[i]);
  913. }
  914. }
  915. log_info(LD_CIRC,
  916. "We had %d timeouts out of %d build times, "
  917. "and filtered %d above the max of %u",
  918. (int)(cbt->total_build_times*timeout_rate),
  919. cbt->total_build_times, num_filtered, max_timeout);
  920. return num_filtered;
  921. }
  922. /**
  923. * Load histogram from <b>state</b>, shuffling the resulting array
  924. * after we do so. Use this result to estimate parameters and
  925. * calculate the timeout.
  926. *
  927. * Return -1 on error.
  928. */
  929. int
  930. circuit_build_times_parse_state(circuit_build_times_t *cbt,
  931. or_state_t *state)
  932. {
  933. int tot_values = 0;
  934. uint32_t loaded_cnt = 0, N = 0;
  935. config_line_t *line;
  936. int i;
  937. build_time_t *loaded_times;
  938. int err = 0;
  939. circuit_build_times_init(cbt);
  940. if (circuit_build_times_disabled(get_options())) {
  941. return 0;
  942. }
  943. /* build_time_t 0 means uninitialized */
  944. loaded_times = tor_calloc(state->TotalBuildTimes, sizeof(build_time_t));
  945. for (line = state->BuildtimeHistogram; line; line = line->next) {
  946. smartlist_t *args = smartlist_new();
  947. smartlist_split_string(args, line->value, " ",
  948. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  949. if (smartlist_len(args) < 2) {
  950. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  951. "Too few arguments to CircuitBuildTime");
  952. err = 1;
  953. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  954. smartlist_free(args);
  955. break;
  956. } else {
  957. const char *ms_str = smartlist_get(args,0);
  958. const char *count_str = smartlist_get(args,1);
  959. uint32_t count, k;
  960. build_time_t ms;
  961. int ok;
  962. ms = (build_time_t)tor_parse_ulong(ms_str, 10, 0,
  963. CBT_BUILD_TIME_MAX, &ok, NULL);
  964. if (!ok) {
  965. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  966. "Unparsable bin number");
  967. err = 1;
  968. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  969. smartlist_free(args);
  970. break;
  971. }
  972. count = (uint32_t)tor_parse_ulong(count_str, 10, 0,
  973. UINT32_MAX, &ok, NULL);
  974. if (!ok) {
  975. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  976. "Unparsable bin count");
  977. err = 1;
  978. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  979. smartlist_free(args);
  980. break;
  981. }
  982. if (loaded_cnt+count+ (unsigned)state->CircuitBuildAbandonedCount
  983. > (unsigned) state->TotalBuildTimes) {
  984. log_warn(LD_CIRC,
  985. "Too many build times in state file. "
  986. "Stopping short before %d",
  987. loaded_cnt+count);
  988. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  989. smartlist_free(args);
  990. break;
  991. }
  992. for (k = 0; k < count; k++) {
  993. loaded_times[loaded_cnt++] = ms;
  994. }
  995. N++;
  996. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  997. smartlist_free(args);
  998. }
  999. }
  1000. log_info(LD_CIRC,
  1001. "Adding %d timeouts.", state->CircuitBuildAbandonedCount);
  1002. for (i=0; i < state->CircuitBuildAbandonedCount; i++) {
  1003. loaded_times[loaded_cnt++] = CBT_BUILD_ABANDONED;
  1004. }
  1005. if (loaded_cnt != (unsigned)state->TotalBuildTimes) {
  1006. log_warn(LD_CIRC,
  1007. "Corrupt state file? Build times count mismatch. "
  1008. "Read %d times, but file says %d", loaded_cnt,
  1009. state->TotalBuildTimes);
  1010. err = 1;
  1011. circuit_build_times_reset(cbt);
  1012. goto done;
  1013. }
  1014. circuit_build_times_shuffle_and_store_array(cbt, loaded_times, loaded_cnt);
  1015. /* Verify that we didn't overwrite any indexes */
  1016. for (i=0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1017. if (!cbt->circuit_build_times[i])
  1018. break;
  1019. tot_values++;
  1020. }
  1021. log_info(LD_CIRC,
  1022. "Loaded %d/%d values from %d lines in circuit time histogram",
  1023. tot_values, cbt->total_build_times, N);
  1024. if (cbt->total_build_times != tot_values
  1025. || cbt->total_build_times > CBT_NCIRCUITS_TO_OBSERVE) {
  1026. log_warn(LD_CIRC,
  1027. "Corrupt state file? Shuffled build times mismatch. "
  1028. "Read %d times, but file says %d", tot_values,
  1029. state->TotalBuildTimes);
  1030. err = 1;
  1031. circuit_build_times_reset(cbt);
  1032. goto done;
  1033. }
  1034. circuit_build_times_set_timeout(cbt);
  1035. if (!state->CircuitBuildAbandonedCount && cbt->total_build_times) {
  1036. circuit_build_times_filter_timeouts(cbt);
  1037. }
  1038. done:
  1039. tor_free(loaded_times);
  1040. return err ? -1 : 0;
  1041. }
  1042. /**
  1043. * Estimates the Xm and Alpha parameters using
  1044. * http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
  1045. *
  1046. * The notable difference is that we use mode instead of min to estimate Xm.
  1047. * This is because our distribution is frechet-like. We claim this is
  1048. * an acceptable approximation because we are only concerned with the
  1049. * accuracy of the CDF of the tail.
  1050. */
  1051. STATIC int
  1052. circuit_build_times_update_alpha(circuit_build_times_t *cbt)
  1053. {
  1054. build_time_t *x=cbt->circuit_build_times;
  1055. double a = 0;
  1056. int n=0,i=0,abandoned_count=0;
  1057. build_time_t max_time=0;
  1058. /* http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation */
  1059. /* We sort of cheat here and make our samples slightly more pareto-like
  1060. * and less frechet-like. */
  1061. cbt->Xm = circuit_build_times_get_xm(cbt);
  1062. /* If Xm came back 0, then too many circuits were abandoned. */
  1063. if (cbt->Xm == 0)
  1064. return 0;
  1065. tor_assert(cbt->Xm > 0);
  1066. for (i=0; i< CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1067. if (!x[i]) {
  1068. continue;
  1069. }
  1070. if (x[i] < cbt->Xm) {
  1071. a += tor_mathlog(cbt->Xm);
  1072. } else if (x[i] == CBT_BUILD_ABANDONED) {
  1073. abandoned_count++;
  1074. } else {
  1075. a += tor_mathlog(x[i]);
  1076. if (x[i] > max_time)
  1077. max_time = x[i];
  1078. }
  1079. n++;
  1080. }
  1081. /*
  1082. * We are erring and asserting here because this can only happen
  1083. * in codepaths other than startup. The startup state parsing code
  1084. * performs this same check, and resets state if it hits it. If we
  1085. * hit it at runtime, something serious has gone wrong.
  1086. */
  1087. if (n!=cbt->total_build_times) {
  1088. log_err(LD_CIRC, "Discrepancy in build times count: %d vs %d", n,
  1089. cbt->total_build_times);
  1090. }
  1091. tor_assert(n==cbt->total_build_times);
  1092. if (max_time <= 0) {
  1093. /* This can happen if Xm is actually the *maximum* value in the set.
  1094. * It can also happen if we've abandoned every single circuit somehow.
  1095. * In either case, tell the caller not to compute a new build timeout. */
  1096. log_warn(LD_BUG,
  1097. "Could not determine largest build time (%d). "
  1098. "Xm is %dms and we've abandoned %d out of %d circuits.", max_time,
  1099. cbt->Xm, abandoned_count, n);
  1100. return 0;
  1101. }
  1102. a += abandoned_count*tor_mathlog(max_time);
  1103. a -= n*tor_mathlog(cbt->Xm);
  1104. // Estimator comes from Eq #4 in:
  1105. // "Bayesian estimation based on trimmed samples from Pareto populations"
  1106. // by Arturo J. Fernández. We are right-censored only.
  1107. a = (n-abandoned_count)/a;
  1108. cbt->alpha = a;
  1109. return 1;
  1110. }
  1111. /**
  1112. * This is the Pareto Quantile Function. It calculates the point x
  1113. * in the distribution such that F(x) = quantile (ie quantile*100%
  1114. * of the mass of the density function is below x on the curve).
  1115. *
  1116. * We use it to calculate the timeout and also to generate synthetic
  1117. * values of time for circuits that timeout before completion.
  1118. *
  1119. * See http://en.wikipedia.org/wiki/Quantile_function,
  1120. * http://en.wikipedia.org/wiki/Inverse_transform_sampling and
  1121. * http://en.wikipedia.org/wiki/Pareto_distribution#Generating_a_
  1122. * random_sample_from_Pareto_distribution
  1123. * That's right. I'll cite wikipedia all day long.
  1124. *
  1125. * Return value is in milliseconds, clamped to INT32_MAX.
  1126. */
  1127. STATIC double
  1128. circuit_build_times_calculate_timeout(circuit_build_times_t *cbt,
  1129. double quantile)
  1130. {
  1131. double ret;
  1132. tor_assert(quantile >= 0);
  1133. tor_assert(1.0-quantile > 0);
  1134. tor_assert(cbt->Xm > 0);
  1135. /* If either alpha or p are 0, we would divide by zero, yielding an
  1136. * infinite (double) result; which would be clamped to INT32_MAX.
  1137. * Instead, initialise ret to INT32_MAX, and skip over these
  1138. * potentially illegal/trapping divides by zero.
  1139. */
  1140. ret = INT32_MAX;
  1141. if (cbt->alpha > 0) {
  1142. double p;
  1143. p = pow(1.0-quantile,1.0/cbt->alpha);
  1144. if (p > 0) {
  1145. ret = cbt->Xm/p;
  1146. }
  1147. }
  1148. if (ret > INT32_MAX) {
  1149. ret = INT32_MAX;
  1150. }
  1151. tor_assert(ret > 0);
  1152. return ret;
  1153. }
  1154. #ifdef TOR_UNIT_TESTS
  1155. /** Pareto CDF */
  1156. double
  1157. circuit_build_times_cdf(circuit_build_times_t *cbt, double x)
  1158. {
  1159. double ret;
  1160. tor_assert(cbt->Xm > 0);
  1161. ret = 1.0-pow(cbt->Xm/x,cbt->alpha);
  1162. tor_assert(0 <= ret && ret <= 1.0);
  1163. return ret;
  1164. }
  1165. #endif /* defined(TOR_UNIT_TESTS) */
  1166. #ifdef TOR_UNIT_TESTS
  1167. /**
  1168. * Generate a synthetic time using our distribution parameters.
  1169. *
  1170. * The return value will be within the [q_lo, q_hi) quantile points
  1171. * on the CDF.
  1172. */
  1173. build_time_t
  1174. circuit_build_times_generate_sample(circuit_build_times_t *cbt,
  1175. double q_lo, double q_hi)
  1176. {
  1177. double randval = crypto_rand_double();
  1178. build_time_t ret;
  1179. double u;
  1180. /* Generate between [q_lo, q_hi) */
  1181. /*XXXX This is what nextafter is supposed to be for; we should use it on the
  1182. * platforms that support it. */
  1183. q_hi -= 1.0/(INT32_MAX);
  1184. tor_assert(q_lo >= 0);
  1185. tor_assert(q_hi < 1);
  1186. tor_assert(q_lo < q_hi);
  1187. u = q_lo + (q_hi-q_lo)*randval;
  1188. tor_assert(0 <= u && u < 1.0);
  1189. /* circuit_build_times_calculate_timeout returns <= INT32_MAX */
  1190. ret = (build_time_t)
  1191. tor_lround(circuit_build_times_calculate_timeout(cbt, u));
  1192. tor_assert(ret > 0);
  1193. return ret;
  1194. }
  1195. #endif /* defined(TOR_UNIT_TESTS) */
  1196. #ifdef TOR_UNIT_TESTS
  1197. /**
  1198. * Estimate an initial alpha parameter by solving the quantile
  1199. * function with a quantile point and a specific timeout value.
  1200. */
  1201. void
  1202. circuit_build_times_initial_alpha(circuit_build_times_t *cbt,
  1203. double quantile, double timeout_ms)
  1204. {
  1205. // Q(u) = Xm/((1-u)^(1/a))
  1206. // Q(0.8) = Xm/((1-0.8))^(1/a)) = CircBuildTimeout
  1207. // CircBuildTimeout = Xm/((1-0.8))^(1/a))
  1208. // CircBuildTimeout = Xm*((1-0.8))^(-1/a))
  1209. // ln(CircBuildTimeout) = ln(Xm)+ln(((1-0.8)))*(-1/a)
  1210. // -ln(1-0.8)/(ln(CircBuildTimeout)-ln(Xm))=a
  1211. tor_assert(quantile >= 0);
  1212. tor_assert(cbt->Xm > 0);
  1213. cbt->alpha = tor_mathlog(1.0-quantile)/
  1214. (tor_mathlog(cbt->Xm)-tor_mathlog(timeout_ms));
  1215. tor_assert(cbt->alpha > 0);
  1216. }
  1217. #endif /* defined(TOR_UNIT_TESTS) */
  1218. /**
  1219. * Returns true if we need circuits to be built
  1220. */
  1221. int
  1222. circuit_build_times_needs_circuits(const circuit_build_times_t *cbt)
  1223. {
  1224. /* Return true if < MIN_CIRCUITS_TO_OBSERVE */
  1225. return !circuit_build_times_enough_to_compute(cbt);
  1226. }
  1227. /**
  1228. * Returns true if we should build a timeout test circuit
  1229. * right now.
  1230. */
  1231. int
  1232. circuit_build_times_needs_circuits_now(const circuit_build_times_t *cbt)
  1233. {
  1234. return circuit_build_times_needs_circuits(cbt) &&
  1235. approx_time()-cbt->last_circ_at > circuit_build_times_test_frequency();
  1236. }
  1237. /**
  1238. * How long should we be unreachable before we think we need to check if
  1239. * our published IP address has changed.
  1240. */
  1241. #define CIRCUIT_TIMEOUT_BEFORE_RECHECK_IP (60*3)
  1242. /**
  1243. * Called to indicate that the network showed some signs of liveness,
  1244. * i.e. we received a cell.
  1245. *
  1246. * This is used by circuit_build_times_network_check_live() to decide
  1247. * if we should record the circuit build timeout or not.
  1248. *
  1249. * This function is called every time we receive a cell. Avoid
  1250. * syscalls, events, and other high-intensity work.
  1251. */
  1252. void
  1253. circuit_build_times_network_is_live(circuit_build_times_t *cbt)
  1254. {
  1255. time_t now = approx_time();
  1256. if (cbt->liveness.nonlive_timeouts > 0) {
  1257. time_t time_since_live = now - cbt->liveness.network_last_live;
  1258. log_notice(LD_CIRC,
  1259. "Tor now sees network activity. Restoring circuit build "
  1260. "timeout recording. Network was down for %d seconds "
  1261. "during %d circuit attempts.",
  1262. (int)time_since_live,
  1263. cbt->liveness.nonlive_timeouts);
  1264. if (time_since_live > CIRCUIT_TIMEOUT_BEFORE_RECHECK_IP)
  1265. reschedule_descriptor_update_check();
  1266. }
  1267. cbt->liveness.network_last_live = now;
  1268. cbt->liveness.nonlive_timeouts = 0;
  1269. /* Tell control.c */
  1270. control_event_network_liveness_update(1);
  1271. }
  1272. /**
  1273. * Non-destructively scale all of our circuit success, timeout, and close
  1274. * counts down by a factor of two. Scaling in this way preserves the
  1275. * ratios between succeeded vs timed out vs closed circuits, so that
  1276. * our statistics don't change when we scale.
  1277. *
  1278. * This is used only in the rare event that we build more than
  1279. * INT32_MAX circuits. Since the num_circ_* variables are
  1280. * uint32_t, we won't even be close to overflowing them.
  1281. */
  1282. void
  1283. circuit_build_times_scale_circ_counts(circuit_build_times_t *cbt)
  1284. {
  1285. cbt->num_circ_succeeded /= 2;
  1286. cbt->num_circ_timeouts /= 2;
  1287. cbt->num_circ_closed /= 2;
  1288. }
  1289. /**
  1290. * Called to indicate that we "completed" a circuit. Because this circuit
  1291. * succeeded, it doesn't count as a timeout-after-the-first-hop.
  1292. *
  1293. * (For the purposes of the cbt code, we consider a circuit "completed" if
  1294. * it has 3 hops, regardless of its final hop count. We do this because
  1295. * we're trying to answer the question, "how long should a circuit take to
  1296. * reach the 3-hop count".)
  1297. *
  1298. * This is used by circuit_build_times_network_check_changed() to determine
  1299. * if we had too many recent timeouts and need to reset our learned timeout
  1300. * to something higher.
  1301. */
  1302. void
  1303. circuit_build_times_network_circ_success(circuit_build_times_t *cbt)
  1304. {
  1305. // Count circuit success
  1306. cbt->num_circ_succeeded++;
  1307. // If we're going to wrap int32, scale everything
  1308. if (cbt->num_circ_succeeded >= INT32_MAX) {
  1309. circuit_build_times_scale_circ_counts(cbt);
  1310. }
  1311. /* Check for NULLness because we might not be using adaptive timeouts */
  1312. if (cbt->liveness.timeouts_after_firsthop &&
  1313. cbt->liveness.num_recent_circs > 0) {
  1314. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1315. = 0;
  1316. cbt->liveness.after_firsthop_idx++;
  1317. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1318. }
  1319. }
  1320. /**
  1321. * A circuit just timed out. If it failed after the first hop, record it
  1322. * in our history for later deciding if the network speed has changed.
  1323. *
  1324. * This is used by circuit_build_times_network_check_changed() to determine
  1325. * if we had too many recent timeouts and need to reset our learned timeout
  1326. * to something higher.
  1327. */
  1328. static void
  1329. circuit_build_times_network_timeout(circuit_build_times_t *cbt,
  1330. int did_onehop)
  1331. {
  1332. // Count circuit timeout
  1333. cbt->num_circ_timeouts++;
  1334. // If we're going to wrap int32, scale everything
  1335. if (cbt->num_circ_timeouts >= INT32_MAX) {
  1336. circuit_build_times_scale_circ_counts(cbt);
  1337. }
  1338. /* Check for NULLness because we might not be using adaptive timeouts */
  1339. if (cbt->liveness.timeouts_after_firsthop &&
  1340. cbt->liveness.num_recent_circs > 0) {
  1341. if (did_onehop) {
  1342. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1343. = 1;
  1344. cbt->liveness.after_firsthop_idx++;
  1345. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1346. }
  1347. }
  1348. }
  1349. /**
  1350. * A circuit was just forcibly closed. If there has been no recent network
  1351. * activity at all, but this circuit was launched back when we thought the
  1352. * network was live, increment the number of "nonlive" circuit timeouts.
  1353. *
  1354. * This is used by circuit_build_times_network_check_live() to decide
  1355. * if we should record the circuit build timeout or not.
  1356. */
  1357. static void
  1358. circuit_build_times_network_close(circuit_build_times_t *cbt,
  1359. int did_onehop, time_t start_time)
  1360. {
  1361. time_t now = time(NULL);
  1362. // Count circuit close
  1363. cbt->num_circ_closed++;
  1364. // If we're going to wrap int32, scale everything
  1365. if (cbt->num_circ_closed >= INT32_MAX) {
  1366. circuit_build_times_scale_circ_counts(cbt);
  1367. }
  1368. /*
  1369. * Check if this is a timeout that was for a circuit that spent its
  1370. * entire existence during a time where we have had no network activity.
  1371. */
  1372. if (cbt->liveness.network_last_live < start_time) {
  1373. if (did_onehop) {
  1374. char last_live_buf[ISO_TIME_LEN+1];
  1375. char start_time_buf[ISO_TIME_LEN+1];
  1376. char now_buf[ISO_TIME_LEN+1];
  1377. format_local_iso_time(last_live_buf, cbt->liveness.network_last_live);
  1378. format_local_iso_time(start_time_buf, start_time);
  1379. format_local_iso_time(now_buf, now);
  1380. log_notice(LD_CIRC,
  1381. "A circuit somehow completed a hop while the network was "
  1382. "not live. The network was last live at %s, but the circuit "
  1383. "launched at %s. It's now %s. This could mean your clock "
  1384. "changed.", last_live_buf, start_time_buf, now_buf);
  1385. }
  1386. cbt->liveness.nonlive_timeouts++;
  1387. if (cbt->liveness.nonlive_timeouts == 1) {
  1388. log_notice(LD_CIRC,
  1389. "Tor has not observed any network activity for the past %d "
  1390. "seconds. Disabling circuit build timeout recording.",
  1391. (int)(now - cbt->liveness.network_last_live));
  1392. /* Tell control.c */
  1393. control_event_network_liveness_update(0);
  1394. } else {
  1395. log_info(LD_CIRC,
  1396. "Got non-live timeout. Current count is: %d",
  1397. cbt->liveness.nonlive_timeouts);
  1398. }
  1399. }
  1400. }
  1401. /**
  1402. * When the network is not live, we do not record circuit build times.
  1403. *
  1404. * The network is considered not live if there has been at least one
  1405. * circuit build that began and ended (had its close_ms measurement
  1406. * period expire) since we last received a cell.
  1407. *
  1408. * Also has the side effect of rewinding the circuit time history
  1409. * in the case of recent liveness changes.
  1410. */
  1411. int
  1412. circuit_build_times_network_check_live(const circuit_build_times_t *cbt)
  1413. {
  1414. if (cbt->liveness.nonlive_timeouts > 0) {
  1415. return 0;
  1416. }
  1417. return 1;
  1418. }
  1419. /**
  1420. * Returns true if we have seen more than MAX_RECENT_TIMEOUT_COUNT of
  1421. * the past RECENT_CIRCUITS time out after the first hop. Used to detect
  1422. * if the network connection has changed significantly, and if so,
  1423. * resets our circuit build timeout to the default.
  1424. *
  1425. * Also resets the entire timeout history in this case and causes us
  1426. * to restart the process of building test circuits and estimating a
  1427. * new timeout.
  1428. */
  1429. STATIC int
  1430. circuit_build_times_network_check_changed(circuit_build_times_t *cbt)
  1431. {
  1432. int total_build_times = cbt->total_build_times;
  1433. int timeout_count=0;
  1434. int i;
  1435. if (cbt->liveness.timeouts_after_firsthop &&
  1436. cbt->liveness.num_recent_circs > 0) {
  1437. /* how many of our recent circuits made it to the first hop but then
  1438. * timed out? */
  1439. for (i = 0; i < cbt->liveness.num_recent_circs; i++) {
  1440. timeout_count += cbt->liveness.timeouts_after_firsthop[i];
  1441. }
  1442. }
  1443. /* If 80% of our recent circuits are timing out after the first hop,
  1444. * we need to re-estimate a new initial alpha and timeout. */
  1445. if (timeout_count < circuit_build_times_max_timeouts()) {
  1446. return 0;
  1447. }
  1448. circuit_build_times_reset(cbt);
  1449. if (cbt->liveness.timeouts_after_firsthop &&
  1450. cbt->liveness.num_recent_circs > 0) {
  1451. memset(cbt->liveness.timeouts_after_firsthop, 0,
  1452. sizeof(*cbt->liveness.timeouts_after_firsthop)*
  1453. cbt->liveness.num_recent_circs);
  1454. }
  1455. cbt->liveness.after_firsthop_idx = 0;
  1456. #define MAX_TIMEOUT ((int32_t) (INT32_MAX/2))
  1457. /* Check to see if this has happened before. If so, double the timeout
  1458. * to give clients on abysmally bad network connections a shot at access */
  1459. if (cbt->timeout_ms >= circuit_build_times_get_initial_timeout()) {
  1460. if (cbt->timeout_ms > MAX_TIMEOUT || cbt->close_ms > MAX_TIMEOUT) {
  1461. log_warn(LD_CIRC, "Insanely large circuit build timeout value. "
  1462. "(timeout = %fmsec, close = %fmsec)",
  1463. cbt->timeout_ms, cbt->close_ms);
  1464. } else {
  1465. cbt->timeout_ms *= 2;
  1466. cbt->close_ms *= 2;
  1467. }
  1468. } else {
  1469. cbt->close_ms = cbt->timeout_ms
  1470. = circuit_build_times_get_initial_timeout();
  1471. }
  1472. #undef MAX_TIMEOUT
  1473. cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  1474. log_notice(LD_CIRC,
  1475. "Your network connection speed appears to have changed. Resetting "
  1476. "timeout to %lds after %d timeouts and %d buildtimes.",
  1477. tor_lround(cbt->timeout_ms/1000), timeout_count,
  1478. total_build_times);
  1479. return 1;
  1480. }
  1481. /**
  1482. * Count the number of timeouts in a set of cbt data.
  1483. */
  1484. double
  1485. circuit_build_times_timeout_rate(const circuit_build_times_t *cbt)
  1486. {
  1487. int i=0,timeouts=0;
  1488. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1489. if (cbt->circuit_build_times[i] >= cbt->timeout_ms) {
  1490. timeouts++;
  1491. }
  1492. }
  1493. if (!cbt->total_build_times)
  1494. return 0;
  1495. return ((double)timeouts)/cbt->total_build_times;
  1496. }
  1497. /**
  1498. * Count the number of closed circuits in a set of cbt data.
  1499. */
  1500. double
  1501. circuit_build_times_close_rate(const circuit_build_times_t *cbt)
  1502. {
  1503. int i=0,closed=0;
  1504. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1505. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED) {
  1506. closed++;
  1507. }
  1508. }
  1509. if (!cbt->total_build_times)
  1510. return 0;
  1511. return ((double)closed)/cbt->total_build_times;
  1512. }
  1513. /**
  1514. * Store a timeout as a synthetic value.
  1515. *
  1516. * Returns true if the store was successful and we should possibly
  1517. * update our timeout estimate.
  1518. */
  1519. int
  1520. circuit_build_times_count_close(circuit_build_times_t *cbt,
  1521. int did_onehop,
  1522. time_t start_time)
  1523. {
  1524. if (circuit_build_times_disabled(get_options())) {
  1525. cbt->close_ms = cbt->timeout_ms
  1526. = circuit_build_times_get_initial_timeout();
  1527. return 0;
  1528. }
  1529. /* Record this force-close to help determine if the network is dead */
  1530. circuit_build_times_network_close(cbt, did_onehop, start_time);
  1531. /* Only count timeouts if network is live.. */
  1532. if (!circuit_build_times_network_check_live(cbt)) {
  1533. return 0;
  1534. }
  1535. circuit_build_times_add_time(cbt, CBT_BUILD_ABANDONED);
  1536. return 1;
  1537. }
  1538. /**
  1539. * Update timeout counts to determine if we need to expire
  1540. * our build time history due to excessive timeouts.
  1541. *
  1542. * We do not record any actual time values at this stage;
  1543. * we are only interested in recording the fact that a timeout
  1544. * happened. We record the time values via
  1545. * circuit_build_times_count_close() and circuit_build_times_add_time().
  1546. */
  1547. void
  1548. circuit_build_times_count_timeout(circuit_build_times_t *cbt,
  1549. int did_onehop)
  1550. {
  1551. if (circuit_build_times_disabled(get_options())) {
  1552. cbt->close_ms = cbt->timeout_ms
  1553. = circuit_build_times_get_initial_timeout();
  1554. return;
  1555. }
  1556. /* Register the fact that a timeout just occurred. */
  1557. circuit_build_times_network_timeout(cbt, did_onehop);
  1558. /* If there are a ton of timeouts, we should reset
  1559. * the circuit build timeout. */
  1560. circuit_build_times_network_check_changed(cbt);
  1561. }
  1562. /**
  1563. * Estimate a new timeout based on history and set our timeout
  1564. * variable accordingly.
  1565. */
  1566. static int
  1567. circuit_build_times_set_timeout_worker(circuit_build_times_t *cbt)
  1568. {
  1569. build_time_t max_time;
  1570. if (!circuit_build_times_enough_to_compute(cbt))
  1571. return 0;
  1572. if (!circuit_build_times_update_alpha(cbt))
  1573. return 0;
  1574. cbt->timeout_ms = circuit_build_times_calculate_timeout(cbt,
  1575. circuit_build_times_quantile_cutoff());
  1576. cbt->close_ms = circuit_build_times_calculate_timeout(cbt,
  1577. circuit_build_times_close_quantile());
  1578. max_time = circuit_build_times_max(cbt);
  1579. if (cbt->timeout_ms > max_time) {
  1580. log_info(LD_CIRC,
  1581. "Circuit build timeout of %dms is beyond the maximum build "
  1582. "time we have ever observed. Capping it to %dms.",
  1583. (int)cbt->timeout_ms, max_time);
  1584. cbt->timeout_ms = max_time;
  1585. }
  1586. if (max_time < INT32_MAX/2 && cbt->close_ms > 2*max_time) {
  1587. log_info(LD_CIRC,
  1588. "Circuit build measurement period of %dms is more than twice "
  1589. "the maximum build time we have ever observed. Capping it to "
  1590. "%dms.", (int)cbt->close_ms, 2*max_time);
  1591. cbt->close_ms = 2*max_time;
  1592. }
  1593. /* Sometimes really fast guard nodes give us such a steep curve
  1594. * that this ends up being not that much greater than timeout_ms.
  1595. * Make it be at least 1 min to handle this case. */
  1596. cbt->close_ms = MAX(cbt->close_ms, circuit_build_times_initial_timeout());
  1597. cbt->have_computed_timeout = 1;
  1598. return 1;
  1599. }
  1600. /**
  1601. * Exposed function to compute a new timeout. Dispatches events and
  1602. * also filters out extremely high timeout values.
  1603. */
  1604. void
  1605. circuit_build_times_set_timeout(circuit_build_times_t *cbt)
  1606. {
  1607. long prev_timeout = tor_lround(cbt->timeout_ms/1000);
  1608. double timeout_rate;
  1609. /*
  1610. * Just return if we aren't using adaptive timeouts
  1611. */
  1612. if (circuit_build_times_disabled(get_options()))
  1613. return;
  1614. if (!circuit_build_times_set_timeout_worker(cbt))
  1615. return;
  1616. if (cbt->timeout_ms < circuit_build_times_min_timeout()) {
  1617. log_info(LD_CIRC, "Set buildtimeout to low value %fms. Setting to %dms",
  1618. cbt->timeout_ms, circuit_build_times_min_timeout());
  1619. cbt->timeout_ms = circuit_build_times_min_timeout();
  1620. if (cbt->close_ms < cbt->timeout_ms) {
  1621. /* This shouldn't happen because of MAX() in timeout_worker above,
  1622. * but doing it just in case */
  1623. cbt->close_ms = circuit_build_times_initial_timeout();
  1624. }
  1625. }
  1626. cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_COMPUTED);
  1627. timeout_rate = circuit_build_times_timeout_rate(cbt);
  1628. if (prev_timeout > tor_lround(cbt->timeout_ms/1000)) {
  1629. log_info(LD_CIRC,
  1630. "Based on %d circuit times, it looks like we don't need to "
  1631. "wait so long for circuits to finish. We will now assume a "
  1632. "circuit is too slow to use after waiting %ld seconds.",
  1633. cbt->total_build_times,
  1634. tor_lround(cbt->timeout_ms/1000));
  1635. log_info(LD_CIRC,
  1636. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1637. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1638. timeout_rate);
  1639. } else if (prev_timeout < tor_lround(cbt->timeout_ms/1000)) {
  1640. log_info(LD_CIRC,
  1641. "Based on %d circuit times, it looks like we need to wait "
  1642. "longer for circuits to finish. We will now assume a "
  1643. "circuit is too slow to use after waiting %ld seconds.",
  1644. cbt->total_build_times,
  1645. tor_lround(cbt->timeout_ms/1000));
  1646. log_info(LD_CIRC,
  1647. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1648. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1649. timeout_rate);
  1650. } else {
  1651. log_info(LD_CIRC,
  1652. "Set circuit build timeout to %lds (%fms, %fms, Xm: %d, a: %f,"
  1653. " r: %f) based on %d circuit times",
  1654. tor_lround(cbt->timeout_ms/1000),
  1655. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha, timeout_rate,
  1656. cbt->total_build_times);
  1657. }
  1658. }
  1659. #ifdef TOR_UNIT_TESTS
  1660. /** Make a note that we're running unit tests (rather than running Tor
  1661. * itself), so we avoid clobbering our state file. */
  1662. void
  1663. circuitbuild_running_unit_tests(void)
  1664. {
  1665. unit_tests = 1;
  1666. }
  1667. #endif /* defined(TOR_UNIT_TESTS) */
  1668. void
  1669. circuit_build_times_update_last_circ(circuit_build_times_t *cbt)
  1670. {
  1671. cbt->last_circ_at = approx_time();
  1672. }
  1673. static void
  1674. cbt_control_event_buildtimeout_set(const circuit_build_times_t *cbt,
  1675. buildtimeout_set_event_t type)
  1676. {
  1677. char *args = NULL;
  1678. double qnt;
  1679. double timeout_rate = 0.0;
  1680. double close_rate = 0.0;
  1681. switch (type) {
  1682. case BUILDTIMEOUT_SET_EVENT_RESET:
  1683. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  1684. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  1685. qnt = 1.0;
  1686. break;
  1687. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  1688. case BUILDTIMEOUT_SET_EVENT_RESUME:
  1689. default:
  1690. qnt = circuit_build_times_quantile_cutoff();
  1691. break;
  1692. }
  1693. /* The timeout rate is the ratio of the timeout count over
  1694. * the total number of circuits attempted. The total number of
  1695. * circuits is (timeouts+succeeded+closed), since a circuit can
  1696. * either timeout, close, or succeed. We cast the denominator
  1697. * to promote it to double before the addition, to avoid int32
  1698. * overflow. */
  1699. const double total_circuits =
  1700. ((double)cbt->num_circ_timeouts) + cbt->num_circ_succeeded
  1701. + cbt->num_circ_closed;
  1702. if (total_circuits >= 1.0) {
  1703. timeout_rate = cbt->num_circ_timeouts / total_circuits;
  1704. close_rate = cbt->num_circ_closed / total_circuits;
  1705. }
  1706. tor_asprintf(&args, "TOTAL_TIMES=%lu "
  1707. "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
  1708. "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f",
  1709. (unsigned long)cbt->total_build_times,
  1710. (unsigned long)cbt->timeout_ms,
  1711. (unsigned long)cbt->Xm, cbt->alpha, qnt,
  1712. timeout_rate,
  1713. (unsigned long)cbt->close_ms,
  1714. close_rate);
  1715. control_event_buildtimeout_set(type, args);
  1716. tor_free(args);
  1717. }