circuitstats.c 51 KB

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