circuitstats.c 52 KB

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