circuitstats.c 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  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-2016, 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
  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(void)
  96. {
  97. return circuit_build_times_disabled_(get_options());
  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
  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
  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()) {
  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. log_notice(LD_CIRC, "The Tor Directory Consensus has changed how many "
  388. "circuits we must track to detect network failures from %d "
  389. "to %d.", cbt->liveness.num_recent_circs, num);
  390. tor_assert(cbt->liveness.timeouts_after_firsthop ||
  391. cbt->liveness.num_recent_circs == 0);
  392. /*
  393. * Technically this is a circular array that we are reallocating
  394. * and memcopying. However, since it only consists of either 1s
  395. * or 0s, and is only used in a statistical test to determine when
  396. * we should discard our history after a sufficient number of 1's
  397. * have been reached, it is fine if order is not preserved or
  398. * elements are lost.
  399. *
  400. * cbtrecentcount should only be changing in cases of severe network
  401. * distress anyway, so memory correctness here is paramount over
  402. * doing acrobatics to preserve the array.
  403. */
  404. recent_circs = tor_calloc(num, sizeof(int8_t));
  405. if (cbt->liveness.timeouts_after_firsthop &&
  406. cbt->liveness.num_recent_circs > 0) {
  407. memcpy(recent_circs, cbt->liveness.timeouts_after_firsthop,
  408. sizeof(int8_t)*MIN(num, cbt->liveness.num_recent_circs));
  409. }
  410. // Adjust the index if it needs it.
  411. if (num < cbt->liveness.num_recent_circs) {
  412. cbt->liveness.after_firsthop_idx = MIN(num-1,
  413. cbt->liveness.after_firsthop_idx);
  414. }
  415. tor_free(cbt->liveness.timeouts_after_firsthop);
  416. cbt->liveness.timeouts_after_firsthop = recent_circs;
  417. cbt->liveness.num_recent_circs = num;
  418. }
  419. /* else no change, nothing to do */
  420. } else { /* num == 0 */
  421. /*
  422. * Weird. This probably shouldn't happen, so log a warning, but try
  423. * to do something sensible anyway.
  424. */
  425. log_warn(LD_CIRC,
  426. "The cbtrecentcircs consensus parameter came back zero! "
  427. "This disables adaptive timeouts since we can't keep track of "
  428. "any recent circuits.");
  429. circuit_build_times_free_timeouts(cbt);
  430. }
  431. } else {
  432. /*
  433. * Adaptive timeouts are disabled; this might be because of the
  434. * LearnCircuitBuildTimes config parameter, and hence permanent, or
  435. * the cbtdisabled consensus parameter, so it may be a new condition.
  436. * Treat it like getting num == 0 above and free the circuit history
  437. * if we have any.
  438. */
  439. circuit_build_times_free_timeouts(cbt);
  440. }
  441. }
  442. /**
  443. * Return the initial default or configured timeout in milliseconds
  444. */
  445. static double
  446. circuit_build_times_get_initial_timeout(void)
  447. {
  448. double timeout;
  449. /*
  450. * Check if we have LearnCircuitBuildTimeout, and if we don't,
  451. * always use CircuitBuildTimeout, no questions asked.
  452. */
  453. if (!unit_tests && get_options()->CircuitBuildTimeout) {
  454. timeout = get_options()->CircuitBuildTimeout*1000;
  455. if (!circuit_build_times_disabled() &&
  456. timeout < circuit_build_times_min_timeout()) {
  457. log_warn(LD_CIRC, "Config CircuitBuildTimeout too low. Setting to %ds",
  458. circuit_build_times_min_timeout()/1000);
  459. timeout = circuit_build_times_min_timeout();
  460. }
  461. } else {
  462. timeout = circuit_build_times_initial_timeout();
  463. }
  464. return timeout;
  465. }
  466. /**
  467. * Reset the build time state.
  468. *
  469. * Leave estimated parameters, timeout and network liveness intact
  470. * for future use.
  471. */
  472. STATIC void
  473. circuit_build_times_reset(circuit_build_times_t *cbt)
  474. {
  475. memset(cbt->circuit_build_times, 0, sizeof(cbt->circuit_build_times));
  476. cbt->total_build_times = 0;
  477. cbt->build_times_idx = 0;
  478. cbt->have_computed_timeout = 0;
  479. }
  480. /**
  481. * Initialize the buildtimes structure for first use.
  482. *
  483. * Sets the initial timeout values based on either the config setting,
  484. * the consensus param, or the default (CBT_DEFAULT_TIMEOUT_INITIAL_VALUE).
  485. */
  486. void
  487. circuit_build_times_init(circuit_build_times_t *cbt)
  488. {
  489. memset(cbt, 0, sizeof(*cbt));
  490. /*
  491. * Check if we really are using adaptive timeouts, and don't keep
  492. * track of this stuff if not.
  493. */
  494. if (!circuit_build_times_disabled()) {
  495. cbt->liveness.num_recent_circs =
  496. circuit_build_times_recent_circuit_count(NULL);
  497. cbt->liveness.timeouts_after_firsthop =
  498. tor_calloc(cbt->liveness.num_recent_circs, sizeof(int8_t));
  499. } else {
  500. cbt->liveness.num_recent_circs = 0;
  501. cbt->liveness.timeouts_after_firsthop = NULL;
  502. }
  503. cbt->close_ms = cbt->timeout_ms = circuit_build_times_get_initial_timeout();
  504. cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  505. }
  506. /**
  507. * Free the saved timeouts, if the cbtdisabled consensus parameter got turned
  508. * on or something.
  509. */
  510. void
  511. circuit_build_times_free_timeouts(circuit_build_times_t *cbt)
  512. {
  513. if (!cbt) return;
  514. if (cbt->liveness.timeouts_after_firsthop) {
  515. tor_free(cbt->liveness.timeouts_after_firsthop);
  516. }
  517. cbt->liveness.num_recent_circs = 0;
  518. }
  519. #if 0
  520. /**
  521. * Rewind our build time history by n positions.
  522. */
  523. static void
  524. circuit_build_times_rewind_history(circuit_build_times_t *cbt, int n)
  525. {
  526. int i = 0;
  527. cbt->build_times_idx -= n;
  528. cbt->build_times_idx %= CBT_NCIRCUITS_TO_OBSERVE;
  529. for (i = 0; i < n; i++) {
  530. cbt->circuit_build_times[(i+cbt->build_times_idx)
  531. %CBT_NCIRCUITS_TO_OBSERVE]=0;
  532. }
  533. if (cbt->total_build_times > n) {
  534. cbt->total_build_times -= n;
  535. } else {
  536. cbt->total_build_times = 0;
  537. }
  538. log_info(LD_CIRC,
  539. "Rewound history by %d places. Current index: %d. "
  540. "Total: %d", n, cbt->build_times_idx, cbt->total_build_times);
  541. }
  542. #endif
  543. /**
  544. * Add a new build time value <b>time</b> to the set of build times. Time
  545. * units are milliseconds.
  546. *
  547. * circuit_build_times <b>cbt</b> is a circular array, so loop around when
  548. * array is full.
  549. */
  550. int
  551. circuit_build_times_add_time(circuit_build_times_t *cbt, build_time_t btime)
  552. {
  553. if (btime <= 0 || btime > CBT_BUILD_TIME_MAX) {
  554. log_warn(LD_BUG, "Circuit build time is too large (%u)."
  555. "This is probably a bug.", btime);
  556. tor_fragile_assert();
  557. return -1;
  558. }
  559. log_debug(LD_CIRC, "Adding circuit build time %u", btime);
  560. cbt->circuit_build_times[cbt->build_times_idx] = btime;
  561. cbt->build_times_idx = (cbt->build_times_idx + 1) % CBT_NCIRCUITS_TO_OBSERVE;
  562. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  563. cbt->total_build_times++;
  564. if ((cbt->total_build_times % CBT_SAVE_STATE_EVERY) == 0) {
  565. /* Save state every n circuit builds */
  566. if (!unit_tests && !get_options()->AvoidDiskWrites)
  567. or_state_mark_dirty(get_or_state(), 0);
  568. }
  569. return 0;
  570. }
  571. /**
  572. * Return maximum circuit build time
  573. */
  574. static build_time_t
  575. circuit_build_times_max(const circuit_build_times_t *cbt)
  576. {
  577. int i = 0;
  578. build_time_t max_build_time = 0;
  579. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  580. if (cbt->circuit_build_times[i] > max_build_time
  581. && cbt->circuit_build_times[i] != CBT_BUILD_ABANDONED)
  582. max_build_time = cbt->circuit_build_times[i];
  583. }
  584. return max_build_time;
  585. }
  586. #if 0
  587. /** Return minimum circuit build time */
  588. build_time_t
  589. circuit_build_times_min(circuit_build_times_t *cbt)
  590. {
  591. int i = 0;
  592. build_time_t min_build_time = CBT_BUILD_TIME_MAX;
  593. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  594. if (cbt->circuit_build_times[i] && /* 0 <-> uninitialized */
  595. cbt->circuit_build_times[i] < min_build_time)
  596. min_build_time = cbt->circuit_build_times[i];
  597. }
  598. if (min_build_time == CBT_BUILD_TIME_MAX) {
  599. log_warn(LD_CIRC, "No build times less than CBT_BUILD_TIME_MAX!");
  600. }
  601. return min_build_time;
  602. }
  603. #endif
  604. /**
  605. * Calculate and return a histogram for the set of build times.
  606. *
  607. * Returns an allocated array of histrogram bins representing
  608. * the frequency of index*CBT_BIN_WIDTH millisecond
  609. * build times. Also outputs the number of bins in nbins.
  610. *
  611. * The return value must be freed by the caller.
  612. */
  613. static uint32_t *
  614. circuit_build_times_create_histogram(const circuit_build_times_t *cbt,
  615. build_time_t *nbins)
  616. {
  617. uint32_t *histogram;
  618. build_time_t max_build_time = circuit_build_times_max(cbt);
  619. int i, c;
  620. *nbins = 1 + (max_build_time / CBT_BIN_WIDTH);
  621. histogram = tor_calloc(*nbins, sizeof(build_time_t));
  622. // calculate histogram
  623. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  624. if (cbt->circuit_build_times[i] == 0
  625. || cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  626. continue; /* 0 <-> uninitialized */
  627. c = (cbt->circuit_build_times[i] / CBT_BIN_WIDTH);
  628. histogram[c]++;
  629. }
  630. return histogram;
  631. }
  632. /**
  633. * Return the Pareto start-of-curve parameter Xm.
  634. *
  635. * Because we are not a true Pareto curve, we compute this as the
  636. * weighted average of the N most frequent build time bins. N is either
  637. * 1 if we don't have enough circuit build time data collected, or
  638. * determined by the consensus parameter cbtnummodes (default 3).
  639. */
  640. static build_time_t
  641. circuit_build_times_get_xm(circuit_build_times_t *cbt)
  642. {
  643. build_time_t i, nbins;
  644. build_time_t *nth_max_bin;
  645. int32_t bin_counts=0;
  646. build_time_t ret = 0;
  647. uint32_t *histogram = circuit_build_times_create_histogram(cbt, &nbins);
  648. int n=0;
  649. int num_modes = circuit_build_times_default_num_xm_modes();
  650. tor_assert(nbins > 0);
  651. tor_assert(num_modes > 0);
  652. // Only use one mode if < 1000 buildtimes. Not enough data
  653. // for multiple.
  654. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  655. num_modes = 1;
  656. nth_max_bin = tor_calloc(num_modes, sizeof(build_time_t));
  657. /* Determine the N most common build times */
  658. for (i = 0; i < nbins; i++) {
  659. if (histogram[i] >= histogram[nth_max_bin[0]]) {
  660. nth_max_bin[0] = i;
  661. }
  662. for (n = 1; n < num_modes; n++) {
  663. if (histogram[i] >= histogram[nth_max_bin[n]] &&
  664. (!histogram[nth_max_bin[n-1]]
  665. || histogram[i] < histogram[nth_max_bin[n-1]])) {
  666. nth_max_bin[n] = i;
  667. }
  668. }
  669. }
  670. for (n = 0; n < num_modes; n++) {
  671. bin_counts += histogram[nth_max_bin[n]];
  672. ret += CBT_BIN_TO_MS(nth_max_bin[n])*histogram[nth_max_bin[n]];
  673. log_info(LD_CIRC, "Xm mode #%d: %u %u", n, CBT_BIN_TO_MS(nth_max_bin[n]),
  674. histogram[nth_max_bin[n]]);
  675. }
  676. /* The following assert is safe, because we don't get called when we
  677. * haven't observed at least CBT_MIN_MIN_CIRCUITS_TO_OBSERVE circuits. */
  678. tor_assert(bin_counts > 0);
  679. ret /= bin_counts;
  680. tor_free(histogram);
  681. tor_free(nth_max_bin);
  682. return ret;
  683. }
  684. /**
  685. * Output a histogram of current circuit build times to
  686. * the or_state_t state structure.
  687. */
  688. void
  689. circuit_build_times_update_state(const circuit_build_times_t *cbt,
  690. or_state_t *state)
  691. {
  692. uint32_t *histogram;
  693. build_time_t i = 0;
  694. build_time_t nbins = 0;
  695. config_line_t **next, *line;
  696. histogram = circuit_build_times_create_histogram(cbt, &nbins);
  697. // write to state
  698. config_free_lines(state->BuildtimeHistogram);
  699. next = &state->BuildtimeHistogram;
  700. *next = NULL;
  701. state->TotalBuildTimes = cbt->total_build_times;
  702. state->CircuitBuildAbandonedCount = 0;
  703. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  704. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  705. state->CircuitBuildAbandonedCount++;
  706. }
  707. for (i = 0; i < nbins; i++) {
  708. // compress the histogram by skipping the blanks
  709. if (histogram[i] == 0) continue;
  710. *next = line = tor_malloc_zero(sizeof(config_line_t));
  711. line->key = tor_strdup("CircuitBuildTimeBin");
  712. tor_asprintf(&line->value, "%d %d",
  713. CBT_BIN_TO_MS(i), histogram[i]);
  714. next = &(line->next);
  715. }
  716. if (!unit_tests) {
  717. if (!get_options()->AvoidDiskWrites)
  718. or_state_mark_dirty(get_or_state(), 0);
  719. }
  720. tor_free(histogram);
  721. }
  722. /**
  723. * Shuffle the build times array.
  724. *
  725. * Adapted from http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  726. */
  727. static void
  728. circuit_build_times_shuffle_and_store_array(circuit_build_times_t *cbt,
  729. build_time_t *raw_times,
  730. uint32_t num_times)
  731. {
  732. uint32_t n = num_times;
  733. if (num_times > CBT_NCIRCUITS_TO_OBSERVE) {
  734. log_notice(LD_CIRC, "The number of circuit times that this Tor version "
  735. "uses to calculate build times is less than the number stored "
  736. "in your state file. Decreasing the circuit time history from "
  737. "%lu to %d.", (unsigned long)num_times,
  738. CBT_NCIRCUITS_TO_OBSERVE);
  739. }
  740. if (n > INT_MAX-1) {
  741. log_warn(LD_CIRC, "For some insane reasons, you had %lu circuit build "
  742. "observations in your state file. That's far too many; probably "
  743. "there's a bug here.", (unsigned long)n);
  744. n = INT_MAX-1;
  745. }
  746. /* This code can only be run on a compact array */
  747. while (n-- > 1) {
  748. int k = crypto_rand_int(n + 1); /* 0 <= k <= n. */
  749. build_time_t tmp = raw_times[k];
  750. raw_times[k] = raw_times[n];
  751. raw_times[n] = tmp;
  752. }
  753. /* Since the times are now shuffled, take a random CBT_NCIRCUITS_TO_OBSERVE
  754. * subset (ie the first CBT_NCIRCUITS_TO_OBSERVE values) */
  755. for (n = 0; n < MIN(num_times, CBT_NCIRCUITS_TO_OBSERVE); n++) {
  756. circuit_build_times_add_time(cbt, raw_times[n]);
  757. }
  758. }
  759. /**
  760. * Filter old synthetic timeouts that were created before the
  761. * new right-censored Pareto calculation was deployed.
  762. *
  763. * Once all clients before 0.2.1.13-alpha are gone, this code
  764. * will be unused.
  765. */
  766. static int
  767. circuit_build_times_filter_timeouts(circuit_build_times_t *cbt)
  768. {
  769. int num_filtered=0, i=0;
  770. double timeout_rate = 0;
  771. build_time_t max_timeout = 0;
  772. timeout_rate = circuit_build_times_timeout_rate(cbt);
  773. max_timeout = (build_time_t)cbt->close_ms;
  774. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  775. if (cbt->circuit_build_times[i] > max_timeout) {
  776. build_time_t replaced = cbt->circuit_build_times[i];
  777. num_filtered++;
  778. cbt->circuit_build_times[i] = CBT_BUILD_ABANDONED;
  779. log_debug(LD_CIRC, "Replaced timeout %d with %d", replaced,
  780. cbt->circuit_build_times[i]);
  781. }
  782. }
  783. log_info(LD_CIRC,
  784. "We had %d timeouts out of %d build times, "
  785. "and filtered %d above the max of %u",
  786. (int)(cbt->total_build_times*timeout_rate),
  787. cbt->total_build_times, num_filtered, max_timeout);
  788. return num_filtered;
  789. }
  790. /**
  791. * Load histogram from <b>state</b>, shuffling the resulting array
  792. * after we do so. Use this result to estimate parameters and
  793. * calculate the timeout.
  794. *
  795. * Return -1 on error.
  796. */
  797. int
  798. circuit_build_times_parse_state(circuit_build_times_t *cbt,
  799. or_state_t *state)
  800. {
  801. int tot_values = 0;
  802. uint32_t loaded_cnt = 0, N = 0;
  803. config_line_t *line;
  804. unsigned int i;
  805. build_time_t *loaded_times;
  806. int err = 0;
  807. circuit_build_times_init(cbt);
  808. if (circuit_build_times_disabled()) {
  809. return 0;
  810. }
  811. /* build_time_t 0 means uninitialized */
  812. loaded_times = tor_calloc(state->TotalBuildTimes, sizeof(build_time_t));
  813. for (line = state->BuildtimeHistogram; line; line = line->next) {
  814. smartlist_t *args = smartlist_new();
  815. smartlist_split_string(args, line->value, " ",
  816. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  817. if (smartlist_len(args) < 2) {
  818. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  819. "Too few arguments to CircuitBuildTime");
  820. err = 1;
  821. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  822. smartlist_free(args);
  823. break;
  824. } else {
  825. const char *ms_str = smartlist_get(args,0);
  826. const char *count_str = smartlist_get(args,1);
  827. uint32_t count, k;
  828. build_time_t ms;
  829. int ok;
  830. ms = (build_time_t)tor_parse_ulong(ms_str, 0, 0,
  831. CBT_BUILD_TIME_MAX, &ok, NULL);
  832. if (!ok) {
  833. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  834. "Unparsable bin number");
  835. err = 1;
  836. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  837. smartlist_free(args);
  838. break;
  839. }
  840. count = (uint32_t)tor_parse_ulong(count_str, 0, 0,
  841. UINT32_MAX, &ok, NULL);
  842. if (!ok) {
  843. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  844. "Unparsable bin count");
  845. err = 1;
  846. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  847. smartlist_free(args);
  848. break;
  849. }
  850. if (loaded_cnt+count+state->CircuitBuildAbandonedCount
  851. > state->TotalBuildTimes) {
  852. log_warn(LD_CIRC,
  853. "Too many build times in state file. "
  854. "Stopping short before %d",
  855. loaded_cnt+count);
  856. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  857. smartlist_free(args);
  858. break;
  859. }
  860. for (k = 0; k < count; k++) {
  861. loaded_times[loaded_cnt++] = ms;
  862. }
  863. N++;
  864. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  865. smartlist_free(args);
  866. }
  867. }
  868. log_info(LD_CIRC,
  869. "Adding %d timeouts.", state->CircuitBuildAbandonedCount);
  870. for (i=0; i < state->CircuitBuildAbandonedCount; i++) {
  871. loaded_times[loaded_cnt++] = CBT_BUILD_ABANDONED;
  872. }
  873. if (loaded_cnt != state->TotalBuildTimes) {
  874. log_warn(LD_CIRC,
  875. "Corrupt state file? Build times count mismatch. "
  876. "Read %d times, but file says %d", loaded_cnt,
  877. state->TotalBuildTimes);
  878. err = 1;
  879. circuit_build_times_reset(cbt);
  880. goto done;
  881. }
  882. circuit_build_times_shuffle_and_store_array(cbt, loaded_times, loaded_cnt);
  883. /* Verify that we didn't overwrite any indexes */
  884. for (i=0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  885. if (!cbt->circuit_build_times[i])
  886. break;
  887. tot_values++;
  888. }
  889. log_info(LD_CIRC,
  890. "Loaded %d/%d values from %d lines in circuit time histogram",
  891. tot_values, cbt->total_build_times, N);
  892. if (cbt->total_build_times != tot_values
  893. || cbt->total_build_times > CBT_NCIRCUITS_TO_OBSERVE) {
  894. log_warn(LD_CIRC,
  895. "Corrupt state file? Shuffled build times mismatch. "
  896. "Read %d times, but file says %d", tot_values,
  897. state->TotalBuildTimes);
  898. err = 1;
  899. circuit_build_times_reset(cbt);
  900. goto done;
  901. }
  902. circuit_build_times_set_timeout(cbt);
  903. if (!state->CircuitBuildAbandonedCount && cbt->total_build_times) {
  904. circuit_build_times_filter_timeouts(cbt);
  905. }
  906. done:
  907. tor_free(loaded_times);
  908. return err ? -1 : 0;
  909. }
  910. /**
  911. * Estimates the Xm and Alpha parameters using
  912. * http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
  913. *
  914. * The notable difference is that we use mode instead of min to estimate Xm.
  915. * This is because our distribution is frechet-like. We claim this is
  916. * an acceptable approximation because we are only concerned with the
  917. * accuracy of the CDF of the tail.
  918. */
  919. STATIC int
  920. circuit_build_times_update_alpha(circuit_build_times_t *cbt)
  921. {
  922. build_time_t *x=cbt->circuit_build_times;
  923. double a = 0;
  924. int n=0,i=0,abandoned_count=0;
  925. build_time_t max_time=0;
  926. /* http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation */
  927. /* We sort of cheat here and make our samples slightly more pareto-like
  928. * and less frechet-like. */
  929. cbt->Xm = circuit_build_times_get_xm(cbt);
  930. tor_assert(cbt->Xm > 0);
  931. for (i=0; i< CBT_NCIRCUITS_TO_OBSERVE; i++) {
  932. if (!x[i]) {
  933. continue;
  934. }
  935. if (x[i] < cbt->Xm) {
  936. a += tor_mathlog(cbt->Xm);
  937. } else if (x[i] == CBT_BUILD_ABANDONED) {
  938. abandoned_count++;
  939. } else {
  940. a += tor_mathlog(x[i]);
  941. if (x[i] > max_time)
  942. max_time = x[i];
  943. }
  944. n++;
  945. }
  946. /*
  947. * We are erring and asserting here because this can only happen
  948. * in codepaths other than startup. The startup state parsing code
  949. * performs this same check, and resets state if it hits it. If we
  950. * hit it at runtime, something serious has gone wrong.
  951. */
  952. if (n!=cbt->total_build_times) {
  953. log_err(LD_CIRC, "Discrepancy in build times count: %d vs %d", n,
  954. cbt->total_build_times);
  955. }
  956. tor_assert(n==cbt->total_build_times);
  957. if (max_time <= 0) {
  958. /* This can happen if Xm is actually the *maximum* value in the set.
  959. * It can also happen if we've abandoned every single circuit somehow.
  960. * In either case, tell the caller not to compute a new build timeout. */
  961. log_warn(LD_BUG,
  962. "Could not determine largest build time (%d). "
  963. "Xm is %dms and we've abandoned %d out of %d circuits.", max_time,
  964. cbt->Xm, abandoned_count, n);
  965. return 0;
  966. }
  967. a += abandoned_count*tor_mathlog(max_time);
  968. a -= n*tor_mathlog(cbt->Xm);
  969. // Estimator comes from Eq #4 in:
  970. // "Bayesian estimation based on trimmed samples from Pareto populations"
  971. // by Arturo J. Fernández. We are right-censored only.
  972. a = (n-abandoned_count)/a;
  973. cbt->alpha = a;
  974. return 1;
  975. }
  976. /**
  977. * This is the Pareto Quantile Function. It calculates the point x
  978. * in the distribution such that F(x) = quantile (ie quantile*100%
  979. * of the mass of the density function is below x on the curve).
  980. *
  981. * We use it to calculate the timeout and also to generate synthetic
  982. * values of time for circuits that timeout before completion.
  983. *
  984. * See http://en.wikipedia.org/wiki/Quantile_function,
  985. * http://en.wikipedia.org/wiki/Inverse_transform_sampling and
  986. * http://en.wikipedia.org/wiki/Pareto_distribution#Generating_a_
  987. * random_sample_from_Pareto_distribution
  988. * That's right. I'll cite wikipedia all day long.
  989. *
  990. * Return value is in milliseconds, clamped to INT32_MAX.
  991. */
  992. STATIC double
  993. circuit_build_times_calculate_timeout(circuit_build_times_t *cbt,
  994. double quantile)
  995. {
  996. double ret;
  997. tor_assert(quantile >= 0);
  998. tor_assert(1.0-quantile > 0);
  999. tor_assert(cbt->Xm > 0);
  1000. /* If either alpha or p are 0, we would divide by zero, yielding an
  1001. * infinite (double) result; which would be clamped to INT32_MAX.
  1002. * Instead, initialise ret to INT32_MAX, and skip over these
  1003. * potentially illegal/trapping divides by zero.
  1004. */
  1005. ret = INT32_MAX;
  1006. if (cbt->alpha > 0) {
  1007. double p;
  1008. p = pow(1.0-quantile,1.0/cbt->alpha);
  1009. if (p > 0) {
  1010. ret = cbt->Xm/p;
  1011. }
  1012. }
  1013. if (ret > INT32_MAX) {
  1014. ret = INT32_MAX;
  1015. }
  1016. tor_assert(ret > 0);
  1017. return ret;
  1018. }
  1019. #ifdef TOR_UNIT_TESTS
  1020. /** Pareto CDF */
  1021. double
  1022. circuit_build_times_cdf(circuit_build_times_t *cbt, double x)
  1023. {
  1024. double ret;
  1025. tor_assert(cbt->Xm > 0);
  1026. ret = 1.0-pow(cbt->Xm/x,cbt->alpha);
  1027. tor_assert(0 <= ret && ret <= 1.0);
  1028. return ret;
  1029. }
  1030. #endif
  1031. #ifdef TOR_UNIT_TESTS
  1032. /**
  1033. * Generate a synthetic time using our distribution parameters.
  1034. *
  1035. * The return value will be within the [q_lo, q_hi) quantile points
  1036. * on the CDF.
  1037. */
  1038. build_time_t
  1039. circuit_build_times_generate_sample(circuit_build_times_t *cbt,
  1040. double q_lo, double q_hi)
  1041. {
  1042. double randval = crypto_rand_double();
  1043. build_time_t ret;
  1044. double u;
  1045. /* Generate between [q_lo, q_hi) */
  1046. /*XXXX This is what nextafter is supposed to be for; we should use it on the
  1047. * platforms that support it. */
  1048. q_hi -= 1.0/(INT32_MAX);
  1049. tor_assert(q_lo >= 0);
  1050. tor_assert(q_hi < 1);
  1051. tor_assert(q_lo < q_hi);
  1052. u = q_lo + (q_hi-q_lo)*randval;
  1053. tor_assert(0 <= u && u < 1.0);
  1054. /* circuit_build_times_calculate_timeout returns <= INT32_MAX */
  1055. ret = (build_time_t)
  1056. tor_lround(circuit_build_times_calculate_timeout(cbt, u));
  1057. tor_assert(ret > 0);
  1058. return ret;
  1059. }
  1060. #endif
  1061. #ifdef TOR_UNIT_TESTS
  1062. /**
  1063. * Estimate an initial alpha parameter by solving the quantile
  1064. * function with a quantile point and a specific timeout value.
  1065. */
  1066. void
  1067. circuit_build_times_initial_alpha(circuit_build_times_t *cbt,
  1068. double quantile, double timeout_ms)
  1069. {
  1070. // Q(u) = Xm/((1-u)^(1/a))
  1071. // Q(0.8) = Xm/((1-0.8))^(1/a)) = CircBuildTimeout
  1072. // CircBuildTimeout = Xm/((1-0.8))^(1/a))
  1073. // CircBuildTimeout = Xm*((1-0.8))^(-1/a))
  1074. // ln(CircBuildTimeout) = ln(Xm)+ln(((1-0.8)))*(-1/a)
  1075. // -ln(1-0.8)/(ln(CircBuildTimeout)-ln(Xm))=a
  1076. tor_assert(quantile >= 0);
  1077. tor_assert(cbt->Xm > 0);
  1078. cbt->alpha = tor_mathlog(1.0-quantile)/
  1079. (tor_mathlog(cbt->Xm)-tor_mathlog(timeout_ms));
  1080. tor_assert(cbt->alpha > 0);
  1081. }
  1082. #endif
  1083. /**
  1084. * Returns true if we need circuits to be built
  1085. */
  1086. int
  1087. circuit_build_times_needs_circuits(const circuit_build_times_t *cbt)
  1088. {
  1089. /* Return true if < MIN_CIRCUITS_TO_OBSERVE */
  1090. return !circuit_build_times_enough_to_compute(cbt);
  1091. }
  1092. /**
  1093. * Returns true if we should build a timeout test circuit
  1094. * right now.
  1095. */
  1096. int
  1097. circuit_build_times_needs_circuits_now(const circuit_build_times_t *cbt)
  1098. {
  1099. return circuit_build_times_needs_circuits(cbt) &&
  1100. approx_time()-cbt->last_circ_at > circuit_build_times_test_frequency();
  1101. }
  1102. /**
  1103. * How long should we be unreachable before we think we need to check if
  1104. * our published IP address has changed.
  1105. */
  1106. #define CIRCUIT_TIMEOUT_BEFORE_RECHECK_IP (60*3)
  1107. /**
  1108. * Called to indicate that the network showed some signs of liveness,
  1109. * i.e. we received a cell.
  1110. *
  1111. * This is used by circuit_build_times_network_check_live() to decide
  1112. * if we should record the circuit build timeout or not.
  1113. *
  1114. * This function is called every time we receive a cell. Avoid
  1115. * syscalls, events, and other high-intensity work.
  1116. */
  1117. void
  1118. circuit_build_times_network_is_live(circuit_build_times_t *cbt)
  1119. {
  1120. time_t now = approx_time();
  1121. if (cbt->liveness.nonlive_timeouts > 0) {
  1122. time_t time_since_live = now - cbt->liveness.network_last_live;
  1123. log_notice(LD_CIRC,
  1124. "Tor now sees network activity. Restoring circuit build "
  1125. "timeout recording. Network was down for %d seconds "
  1126. "during %d circuit attempts.",
  1127. (int)time_since_live,
  1128. cbt->liveness.nonlive_timeouts);
  1129. if (time_since_live > CIRCUIT_TIMEOUT_BEFORE_RECHECK_IP)
  1130. reschedule_descriptor_update_check();
  1131. }
  1132. cbt->liveness.network_last_live = now;
  1133. cbt->liveness.nonlive_timeouts = 0;
  1134. /* Tell control.c */
  1135. control_event_network_liveness_update(1);
  1136. }
  1137. /**
  1138. * Called to indicate that we completed a circuit. Because this circuit
  1139. * succeeded, it doesn't count as a timeout-after-the-first-hop.
  1140. *
  1141. * This is used by circuit_build_times_network_check_changed() to determine
  1142. * if we had too many recent timeouts and need to reset our learned timeout
  1143. * to something higher.
  1144. */
  1145. void
  1146. circuit_build_times_network_circ_success(circuit_build_times_t *cbt)
  1147. {
  1148. /* Check for NULLness because we might not be using adaptive timeouts */
  1149. if (cbt->liveness.timeouts_after_firsthop &&
  1150. cbt->liveness.num_recent_circs > 0) {
  1151. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1152. = 0;
  1153. cbt->liveness.after_firsthop_idx++;
  1154. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1155. }
  1156. }
  1157. /**
  1158. * A circuit just timed out. If it failed after the first hop, record it
  1159. * in our history for later deciding if the network speed has changed.
  1160. *
  1161. * This is used by circuit_build_times_network_check_changed() to determine
  1162. * if we had too many recent timeouts and need to reset our learned timeout
  1163. * to something higher.
  1164. */
  1165. static void
  1166. circuit_build_times_network_timeout(circuit_build_times_t *cbt,
  1167. int did_onehop)
  1168. {
  1169. /* Check for NULLness because we might not be using adaptive timeouts */
  1170. if (cbt->liveness.timeouts_after_firsthop &&
  1171. cbt->liveness.num_recent_circs > 0) {
  1172. if (did_onehop) {
  1173. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1174. = 1;
  1175. cbt->liveness.after_firsthop_idx++;
  1176. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1177. }
  1178. }
  1179. }
  1180. /**
  1181. * A circuit was just forcibly closed. If there has been no recent network
  1182. * activity at all, but this circuit was launched back when we thought the
  1183. * network was live, increment the number of "nonlive" circuit timeouts.
  1184. *
  1185. * This is used by circuit_build_times_network_check_live() to decide
  1186. * if we should record the circuit build timeout or not.
  1187. */
  1188. static void
  1189. circuit_build_times_network_close(circuit_build_times_t *cbt,
  1190. int did_onehop, time_t start_time)
  1191. {
  1192. time_t now = time(NULL);
  1193. /*
  1194. * Check if this is a timeout that was for a circuit that spent its
  1195. * entire existence during a time where we have had no network activity.
  1196. */
  1197. if (cbt->liveness.network_last_live < start_time) {
  1198. if (did_onehop) {
  1199. char last_live_buf[ISO_TIME_LEN+1];
  1200. char start_time_buf[ISO_TIME_LEN+1];
  1201. char now_buf[ISO_TIME_LEN+1];
  1202. format_local_iso_time(last_live_buf, cbt->liveness.network_last_live);
  1203. format_local_iso_time(start_time_buf, start_time);
  1204. format_local_iso_time(now_buf, now);
  1205. log_notice(LD_CIRC,
  1206. "A circuit somehow completed a hop while the network was "
  1207. "not live. The network was last live at %s, but the circuit "
  1208. "launched at %s. It's now %s. This could mean your clock "
  1209. "changed.", last_live_buf, start_time_buf, now_buf);
  1210. }
  1211. cbt->liveness.nonlive_timeouts++;
  1212. if (cbt->liveness.nonlive_timeouts == 1) {
  1213. log_notice(LD_CIRC,
  1214. "Tor has not observed any network activity for the past %d "
  1215. "seconds. Disabling circuit build timeout recording.",
  1216. (int)(now - cbt->liveness.network_last_live));
  1217. /* Tell control.c */
  1218. control_event_network_liveness_update(0);
  1219. } else {
  1220. log_info(LD_CIRC,
  1221. "Got non-live timeout. Current count is: %d",
  1222. cbt->liveness.nonlive_timeouts);
  1223. }
  1224. }
  1225. }
  1226. /**
  1227. * When the network is not live, we do not record circuit build times.
  1228. *
  1229. * The network is considered not live if there has been at least one
  1230. * circuit build that began and ended (had its close_ms measurement
  1231. * period expire) since we last received a cell.
  1232. *
  1233. * Also has the side effect of rewinding the circuit time history
  1234. * in the case of recent liveness changes.
  1235. */
  1236. int
  1237. circuit_build_times_network_check_live(const circuit_build_times_t *cbt)
  1238. {
  1239. if (cbt->liveness.nonlive_timeouts > 0) {
  1240. return 0;
  1241. }
  1242. return 1;
  1243. }
  1244. /**
  1245. * Returns true if we have seen more than MAX_RECENT_TIMEOUT_COUNT of
  1246. * the past RECENT_CIRCUITS time out after the first hop. Used to detect
  1247. * if the network connection has changed significantly, and if so,
  1248. * resets our circuit build timeout to the default.
  1249. *
  1250. * Also resets the entire timeout history in this case and causes us
  1251. * to restart the process of building test circuits and estimating a
  1252. * new timeout.
  1253. */
  1254. STATIC int
  1255. circuit_build_times_network_check_changed(circuit_build_times_t *cbt)
  1256. {
  1257. int total_build_times = cbt->total_build_times;
  1258. int timeout_count=0;
  1259. int i;
  1260. if (cbt->liveness.timeouts_after_firsthop &&
  1261. cbt->liveness.num_recent_circs > 0) {
  1262. /* how many of our recent circuits made it to the first hop but then
  1263. * timed out? */
  1264. for (i = 0; i < cbt->liveness.num_recent_circs; i++) {
  1265. timeout_count += cbt->liveness.timeouts_after_firsthop[i];
  1266. }
  1267. }
  1268. /* If 80% of our recent circuits are timing out after the first hop,
  1269. * we need to re-estimate a new initial alpha and timeout. */
  1270. if (timeout_count < circuit_build_times_max_timeouts()) {
  1271. return 0;
  1272. }
  1273. circuit_build_times_reset(cbt);
  1274. if (cbt->liveness.timeouts_after_firsthop &&
  1275. cbt->liveness.num_recent_circs > 0) {
  1276. memset(cbt->liveness.timeouts_after_firsthop, 0,
  1277. sizeof(*cbt->liveness.timeouts_after_firsthop)*
  1278. cbt->liveness.num_recent_circs);
  1279. }
  1280. cbt->liveness.after_firsthop_idx = 0;
  1281. #define MAX_TIMEOUT ((int32_t) (INT32_MAX/2))
  1282. /* Check to see if this has happened before. If so, double the timeout
  1283. * to give people on abysmally bad network connections a shot at access */
  1284. if (cbt->timeout_ms >= circuit_build_times_get_initial_timeout()) {
  1285. if (cbt->timeout_ms > MAX_TIMEOUT || cbt->close_ms > MAX_TIMEOUT) {
  1286. log_warn(LD_CIRC, "Insanely large circuit build timeout value. "
  1287. "(timeout = %fmsec, close = %fmsec)",
  1288. cbt->timeout_ms, cbt->close_ms);
  1289. } else {
  1290. cbt->timeout_ms *= 2;
  1291. cbt->close_ms *= 2;
  1292. }
  1293. } else {
  1294. cbt->close_ms = cbt->timeout_ms
  1295. = circuit_build_times_get_initial_timeout();
  1296. }
  1297. #undef MAX_TIMEOUT
  1298. cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  1299. log_notice(LD_CIRC,
  1300. "Your network connection speed appears to have changed. Resetting "
  1301. "timeout to %lds after %d timeouts and %d buildtimes.",
  1302. tor_lround(cbt->timeout_ms/1000), timeout_count,
  1303. total_build_times);
  1304. return 1;
  1305. }
  1306. /**
  1307. * Count the number of timeouts in a set of cbt data.
  1308. */
  1309. double
  1310. circuit_build_times_timeout_rate(const circuit_build_times_t *cbt)
  1311. {
  1312. int i=0,timeouts=0;
  1313. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1314. if (cbt->circuit_build_times[i] >= cbt->timeout_ms) {
  1315. timeouts++;
  1316. }
  1317. }
  1318. if (!cbt->total_build_times)
  1319. return 0;
  1320. return ((double)timeouts)/cbt->total_build_times;
  1321. }
  1322. /**
  1323. * Count the number of closed circuits in a set of cbt data.
  1324. */
  1325. double
  1326. circuit_build_times_close_rate(const circuit_build_times_t *cbt)
  1327. {
  1328. int i=0,closed=0;
  1329. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1330. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED) {
  1331. closed++;
  1332. }
  1333. }
  1334. if (!cbt->total_build_times)
  1335. return 0;
  1336. return ((double)closed)/cbt->total_build_times;
  1337. }
  1338. /**
  1339. * Store a timeout as a synthetic value.
  1340. *
  1341. * Returns true if the store was successful and we should possibly
  1342. * update our timeout estimate.
  1343. */
  1344. int
  1345. circuit_build_times_count_close(circuit_build_times_t *cbt,
  1346. int did_onehop,
  1347. time_t start_time)
  1348. {
  1349. if (circuit_build_times_disabled()) {
  1350. cbt->close_ms = cbt->timeout_ms
  1351. = circuit_build_times_get_initial_timeout();
  1352. return 0;
  1353. }
  1354. /* Record this force-close to help determine if the network is dead */
  1355. circuit_build_times_network_close(cbt, did_onehop, start_time);
  1356. /* Only count timeouts if network is live.. */
  1357. if (!circuit_build_times_network_check_live(cbt)) {
  1358. return 0;
  1359. }
  1360. circuit_build_times_add_time(cbt, CBT_BUILD_ABANDONED);
  1361. return 1;
  1362. }
  1363. /**
  1364. * Update timeout counts to determine if we need to expire
  1365. * our build time history due to excessive timeouts.
  1366. *
  1367. * We do not record any actual time values at this stage;
  1368. * we are only interested in recording the fact that a timeout
  1369. * happened. We record the time values via
  1370. * circuit_build_times_count_close() and circuit_build_times_add_time().
  1371. */
  1372. void
  1373. circuit_build_times_count_timeout(circuit_build_times_t *cbt,
  1374. int did_onehop)
  1375. {
  1376. if (circuit_build_times_disabled()) {
  1377. cbt->close_ms = cbt->timeout_ms
  1378. = circuit_build_times_get_initial_timeout();
  1379. return;
  1380. }
  1381. /* Register the fact that a timeout just occurred. */
  1382. circuit_build_times_network_timeout(cbt, did_onehop);
  1383. /* If there are a ton of timeouts, we should reset
  1384. * the circuit build timeout. */
  1385. circuit_build_times_network_check_changed(cbt);
  1386. }
  1387. /**
  1388. * Estimate a new timeout based on history and set our timeout
  1389. * variable accordingly.
  1390. */
  1391. static int
  1392. circuit_build_times_set_timeout_worker(circuit_build_times_t *cbt)
  1393. {
  1394. build_time_t max_time;
  1395. if (!circuit_build_times_enough_to_compute(cbt))
  1396. return 0;
  1397. if (!circuit_build_times_update_alpha(cbt))
  1398. return 0;
  1399. cbt->timeout_ms = circuit_build_times_calculate_timeout(cbt,
  1400. circuit_build_times_quantile_cutoff());
  1401. cbt->close_ms = circuit_build_times_calculate_timeout(cbt,
  1402. circuit_build_times_close_quantile());
  1403. max_time = circuit_build_times_max(cbt);
  1404. if (cbt->timeout_ms > max_time) {
  1405. log_info(LD_CIRC,
  1406. "Circuit build timeout of %dms is beyond the maximum build "
  1407. "time we have ever observed. Capping it to %dms.",
  1408. (int)cbt->timeout_ms, max_time);
  1409. cbt->timeout_ms = max_time;
  1410. }
  1411. if (max_time < INT32_MAX/2 && cbt->close_ms > 2*max_time) {
  1412. log_info(LD_CIRC,
  1413. "Circuit build measurement period of %dms is more than twice "
  1414. "the maximum build time we have ever observed. Capping it to "
  1415. "%dms.", (int)cbt->close_ms, 2*max_time);
  1416. cbt->close_ms = 2*max_time;
  1417. }
  1418. /* Sometimes really fast guard nodes give us such a steep curve
  1419. * that this ends up being not that much greater than timeout_ms.
  1420. * Make it be at least 1 min to handle this case. */
  1421. cbt->close_ms = MAX(cbt->close_ms, circuit_build_times_initial_timeout());
  1422. cbt->have_computed_timeout = 1;
  1423. return 1;
  1424. }
  1425. /**
  1426. * Exposed function to compute a new timeout. Dispatches events and
  1427. * also filters out extremely high timeout values.
  1428. */
  1429. void
  1430. circuit_build_times_set_timeout(circuit_build_times_t *cbt)
  1431. {
  1432. long prev_timeout = tor_lround(cbt->timeout_ms/1000);
  1433. double timeout_rate;
  1434. /*
  1435. * Just return if we aren't using adaptive timeouts
  1436. */
  1437. if (circuit_build_times_disabled())
  1438. return;
  1439. if (!circuit_build_times_set_timeout_worker(cbt))
  1440. return;
  1441. if (cbt->timeout_ms < circuit_build_times_min_timeout()) {
  1442. log_info(LD_CIRC, "Set buildtimeout to low value %fms. Setting to %dms",
  1443. cbt->timeout_ms, circuit_build_times_min_timeout());
  1444. cbt->timeout_ms = circuit_build_times_min_timeout();
  1445. if (cbt->close_ms < cbt->timeout_ms) {
  1446. /* This shouldn't happen because of MAX() in timeout_worker above,
  1447. * but doing it just in case */
  1448. cbt->close_ms = circuit_build_times_initial_timeout();
  1449. }
  1450. }
  1451. cbt_control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_COMPUTED);
  1452. timeout_rate = circuit_build_times_timeout_rate(cbt);
  1453. if (prev_timeout > tor_lround(cbt->timeout_ms/1000)) {
  1454. log_info(LD_CIRC,
  1455. "Based on %d circuit times, it looks like we don't need to "
  1456. "wait so long for circuits to finish. We will now assume a "
  1457. "circuit is too slow to use after waiting %ld seconds.",
  1458. cbt->total_build_times,
  1459. tor_lround(cbt->timeout_ms/1000));
  1460. log_info(LD_CIRC,
  1461. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1462. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1463. timeout_rate);
  1464. } else if (prev_timeout < tor_lround(cbt->timeout_ms/1000)) {
  1465. log_info(LD_CIRC,
  1466. "Based on %d circuit times, it looks like we need to wait "
  1467. "longer for circuits to finish. We will now assume a "
  1468. "circuit is too slow to use after waiting %ld seconds.",
  1469. cbt->total_build_times,
  1470. tor_lround(cbt->timeout_ms/1000));
  1471. log_info(LD_CIRC,
  1472. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1473. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1474. timeout_rate);
  1475. } else {
  1476. log_info(LD_CIRC,
  1477. "Set circuit build timeout to %lds (%fms, %fms, Xm: %d, a: %f,"
  1478. " r: %f) based on %d circuit times",
  1479. tor_lround(cbt->timeout_ms/1000),
  1480. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha, timeout_rate,
  1481. cbt->total_build_times);
  1482. }
  1483. }
  1484. #ifdef TOR_UNIT_TESTS
  1485. /** Make a note that we're running unit tests (rather than running Tor
  1486. * itself), so we avoid clobbering our state file. */
  1487. void
  1488. circuitbuild_running_unit_tests(void)
  1489. {
  1490. unit_tests = 1;
  1491. }
  1492. #endif
  1493. void
  1494. circuit_build_times_update_last_circ(circuit_build_times_t *cbt)
  1495. {
  1496. cbt->last_circ_at = approx_time();
  1497. }
  1498. static void
  1499. cbt_control_event_buildtimeout_set(const circuit_build_times_t *cbt,
  1500. buildtimeout_set_event_t type)
  1501. {
  1502. char *args = NULL;
  1503. double qnt;
  1504. switch (type) {
  1505. case BUILDTIMEOUT_SET_EVENT_RESET:
  1506. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  1507. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  1508. qnt = 1.0;
  1509. break;
  1510. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  1511. case BUILDTIMEOUT_SET_EVENT_RESUME:
  1512. default:
  1513. qnt = circuit_build_times_quantile_cutoff();
  1514. break;
  1515. }
  1516. tor_asprintf(&args, "TOTAL_TIMES=%lu "
  1517. "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
  1518. "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f",
  1519. (unsigned long)cbt->total_build_times,
  1520. (unsigned long)cbt->timeout_ms,
  1521. (unsigned long)cbt->Xm, cbt->alpha, qnt,
  1522. circuit_build_times_timeout_rate(cbt),
  1523. (unsigned long)cbt->close_ms,
  1524. circuit_build_times_close_rate(cbt));
  1525. control_event_buildtimeout_set(type, args);
  1526. tor_free(args);
  1527. }