circuitstats.c 62 KB

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