circuitstats.c 54 KB

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