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