circuitstats.c 57 KB

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