circuitstats.c 61 KB

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