circuitstats.c 51 KB

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