circuitstats.c 49 KB

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