circuitstats.c 61 KB

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