circuitstats.c 48 KB

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