circuitstats.c 53 KB

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