circuitstats.c 49 KB

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