circuitstats.c 62 KB

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