circuitstats.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  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 (get_options()->LearnCircuitBuildTimeout) {
  371. if (!unit_tests && get_options()->CircuitBuildTimeout) {
  372. timeout = get_options()->CircuitBuildTimeout*1000;
  373. if (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. } else {
  382. timeout = get_options()->CircuitBuildTimeout*1000;
  383. }
  384. return timeout;
  385. }
  386. /**
  387. * Reset the build time state.
  388. *
  389. * Leave estimated parameters, timeout and network liveness intact
  390. * for future use.
  391. */
  392. void
  393. circuit_build_times_reset(circuit_build_times_t *cbt)
  394. {
  395. memset(cbt->circuit_build_times, 0, sizeof(cbt->circuit_build_times));
  396. cbt->total_build_times = 0;
  397. cbt->build_times_idx = 0;
  398. cbt->have_computed_timeout = 0;
  399. }
  400. /**
  401. * Initialize the buildtimes structure for first use.
  402. *
  403. * Sets the initial timeout values based on either the config setting,
  404. * the consensus param, or the default (CBT_DEFAULT_TIMEOUT_INITIAL_VALUE).
  405. */
  406. void
  407. circuit_build_times_init(circuit_build_times_t *cbt)
  408. {
  409. memset(cbt, 0, sizeof(*cbt));
  410. /*
  411. * Check if we really are using adaptive timeouts, and don't keep
  412. * track of this stuff if not.
  413. */
  414. if (!circuit_build_times_disabled()) {
  415. cbt->liveness.num_recent_circs =
  416. circuit_build_times_recent_circuit_count(NULL);
  417. cbt->liveness.timeouts_after_firsthop =
  418. tor_malloc_zero(sizeof(int8_t)*cbt->liveness.num_recent_circs);
  419. } else {
  420. cbt->liveness.num_recent_circs = 0;
  421. cbt->liveness.timeouts_after_firsthop = NULL;
  422. }
  423. cbt->close_ms = cbt->timeout_ms = circuit_build_times_get_initial_timeout();
  424. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  425. }
  426. /**
  427. * Free the saved timeouts, if the cbtdisabled consensus parameter got turned
  428. * on or something.
  429. */
  430. void
  431. circuit_build_times_free_timeouts(circuit_build_times_t *cbt)
  432. {
  433. if (!cbt) return;
  434. if (cbt->liveness.timeouts_after_firsthop) {
  435. tor_free(cbt->liveness.timeouts_after_firsthop);
  436. }
  437. cbt->liveness.num_recent_circs = 0;
  438. }
  439. #if 0
  440. /**
  441. * Rewind our build time history by n positions.
  442. */
  443. static void
  444. circuit_build_times_rewind_history(circuit_build_times_t *cbt, int n)
  445. {
  446. int i = 0;
  447. cbt->build_times_idx -= n;
  448. cbt->build_times_idx %= CBT_NCIRCUITS_TO_OBSERVE;
  449. for (i = 0; i < n; i++) {
  450. cbt->circuit_build_times[(i+cbt->build_times_idx)
  451. %CBT_NCIRCUITS_TO_OBSERVE]=0;
  452. }
  453. if (cbt->total_build_times > n) {
  454. cbt->total_build_times -= n;
  455. } else {
  456. cbt->total_build_times = 0;
  457. }
  458. log_info(LD_CIRC,
  459. "Rewound history by %d places. Current index: %d. "
  460. "Total: %d", n, cbt->build_times_idx, cbt->total_build_times);
  461. }
  462. #endif
  463. /**
  464. * Add a new build time value <b>time</b> to the set of build times. Time
  465. * units are milliseconds.
  466. *
  467. * circuit_build_times <b>cbt</b> is a circular array, so loop around when
  468. * array is full.
  469. */
  470. int
  471. circuit_build_times_add_time(circuit_build_times_t *cbt, build_time_t time)
  472. {
  473. if (time <= 0 || time > CBT_BUILD_TIME_MAX) {
  474. log_warn(LD_BUG, "Circuit build time is too large (%u)."
  475. "This is probably a bug.", time);
  476. tor_fragile_assert();
  477. return -1;
  478. }
  479. log_debug(LD_CIRC, "Adding circuit build time %u", time);
  480. cbt->circuit_build_times[cbt->build_times_idx] = time;
  481. cbt->build_times_idx = (cbt->build_times_idx + 1) % CBT_NCIRCUITS_TO_OBSERVE;
  482. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  483. cbt->total_build_times++;
  484. if ((cbt->total_build_times % CBT_SAVE_STATE_EVERY) == 0) {
  485. /* Save state every n circuit builds */
  486. if (!unit_tests && !get_options()->AvoidDiskWrites)
  487. or_state_mark_dirty(get_or_state(), 0);
  488. }
  489. return 0;
  490. }
  491. /**
  492. * Return maximum circuit build time
  493. */
  494. static build_time_t
  495. circuit_build_times_max(circuit_build_times_t *cbt)
  496. {
  497. int i = 0;
  498. build_time_t max_build_time = 0;
  499. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  500. if (cbt->circuit_build_times[i] > max_build_time
  501. && cbt->circuit_build_times[i] != CBT_BUILD_ABANDONED)
  502. max_build_time = cbt->circuit_build_times[i];
  503. }
  504. return max_build_time;
  505. }
  506. #if 0
  507. /** Return minimum circuit build time */
  508. build_time_t
  509. circuit_build_times_min(circuit_build_times_t *cbt)
  510. {
  511. int i = 0;
  512. build_time_t min_build_time = CBT_BUILD_TIME_MAX;
  513. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  514. if (cbt->circuit_build_times[i] && /* 0 <-> uninitialized */
  515. cbt->circuit_build_times[i] < min_build_time)
  516. min_build_time = cbt->circuit_build_times[i];
  517. }
  518. if (min_build_time == CBT_BUILD_TIME_MAX) {
  519. log_warn(LD_CIRC, "No build times less than CBT_BUILD_TIME_MAX!");
  520. }
  521. return min_build_time;
  522. }
  523. #endif
  524. /**
  525. * Calculate and return a histogram for the set of build times.
  526. *
  527. * Returns an allocated array of histrogram bins representing
  528. * the frequency of index*CBT_BIN_WIDTH millisecond
  529. * build times. Also outputs the number of bins in nbins.
  530. *
  531. * The return value must be freed by the caller.
  532. */
  533. static uint32_t *
  534. circuit_build_times_create_histogram(circuit_build_times_t *cbt,
  535. build_time_t *nbins)
  536. {
  537. uint32_t *histogram;
  538. build_time_t max_build_time = circuit_build_times_max(cbt);
  539. int i, c;
  540. *nbins = 1 + (max_build_time / CBT_BIN_WIDTH);
  541. histogram = tor_malloc_zero(*nbins * sizeof(build_time_t));
  542. // calculate histogram
  543. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  544. if (cbt->circuit_build_times[i] == 0
  545. || cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  546. continue; /* 0 <-> uninitialized */
  547. c = (cbt->circuit_build_times[i] / CBT_BIN_WIDTH);
  548. histogram[c]++;
  549. }
  550. return histogram;
  551. }
  552. /**
  553. * Return the Pareto start-of-curve parameter Xm.
  554. *
  555. * Because we are not a true Pareto curve, we compute this as the
  556. * weighted average of the N most frequent build time bins. N is either
  557. * 1 if we don't have enough circuit build time data collected, or
  558. * determined by the consensus parameter cbtnummodes (default 3).
  559. */
  560. static build_time_t
  561. circuit_build_times_get_xm(circuit_build_times_t *cbt)
  562. {
  563. build_time_t i, nbins;
  564. build_time_t *nth_max_bin;
  565. int32_t bin_counts=0;
  566. build_time_t ret = 0;
  567. uint32_t *histogram = circuit_build_times_create_histogram(cbt, &nbins);
  568. int n=0;
  569. int num_modes = circuit_build_times_default_num_xm_modes();
  570. tor_assert(nbins > 0);
  571. tor_assert(num_modes > 0);
  572. // Only use one mode if < 1000 buildtimes. Not enough data
  573. // for multiple.
  574. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  575. num_modes = 1;
  576. nth_max_bin = (build_time_t*)tor_malloc_zero(num_modes*sizeof(build_time_t));
  577. /* Determine the N most common build times */
  578. for (i = 0; i < nbins; i++) {
  579. if (histogram[i] >= histogram[nth_max_bin[0]]) {
  580. nth_max_bin[0] = i;
  581. }
  582. for (n = 1; n < num_modes; n++) {
  583. if (histogram[i] >= histogram[nth_max_bin[n]] &&
  584. (!histogram[nth_max_bin[n-1]]
  585. || histogram[i] < histogram[nth_max_bin[n-1]])) {
  586. nth_max_bin[n] = i;
  587. }
  588. }
  589. }
  590. for (n = 0; n < num_modes; n++) {
  591. bin_counts += histogram[nth_max_bin[n]];
  592. ret += CBT_BIN_TO_MS(nth_max_bin[n])*histogram[nth_max_bin[n]];
  593. log_info(LD_CIRC, "Xm mode #%d: %u %u", n, CBT_BIN_TO_MS(nth_max_bin[n]),
  594. histogram[nth_max_bin[n]]);
  595. }
  596. /* The following assert is safe, because we don't get called when we
  597. * haven't observed at least CBT_MIN_MIN_CIRCUITS_TO_OBSERVE circuits. */
  598. tor_assert(bin_counts > 0);
  599. ret /= bin_counts;
  600. tor_free(histogram);
  601. tor_free(nth_max_bin);
  602. return ret;
  603. }
  604. /**
  605. * Output a histogram of current circuit build times to
  606. * the or_state_t state structure.
  607. */
  608. void
  609. circuit_build_times_update_state(circuit_build_times_t *cbt,
  610. or_state_t *state)
  611. {
  612. uint32_t *histogram;
  613. build_time_t i = 0;
  614. build_time_t nbins = 0;
  615. config_line_t **next, *line;
  616. histogram = circuit_build_times_create_histogram(cbt, &nbins);
  617. // write to state
  618. config_free_lines(state->BuildtimeHistogram);
  619. next = &state->BuildtimeHistogram;
  620. *next = NULL;
  621. state->TotalBuildTimes = cbt->total_build_times;
  622. state->CircuitBuildAbandonedCount = 0;
  623. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  624. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  625. state->CircuitBuildAbandonedCount++;
  626. }
  627. for (i = 0; i < nbins; i++) {
  628. // compress the histogram by skipping the blanks
  629. if (histogram[i] == 0) continue;
  630. *next = line = tor_malloc_zero(sizeof(config_line_t));
  631. line->key = tor_strdup("CircuitBuildTimeBin");
  632. tor_asprintf(&line->value, "%d %d",
  633. CBT_BIN_TO_MS(i), histogram[i]);
  634. next = &(line->next);
  635. }
  636. if (!unit_tests) {
  637. if (!get_options()->AvoidDiskWrites)
  638. or_state_mark_dirty(get_or_state(), 0);
  639. }
  640. tor_free(histogram);
  641. }
  642. /**
  643. * Shuffle the build times array.
  644. *
  645. * Adapted from http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  646. */
  647. static void
  648. circuit_build_times_shuffle_and_store_array(circuit_build_times_t *cbt,
  649. build_time_t *raw_times,
  650. uint32_t num_times)
  651. {
  652. uint32_t n = num_times;
  653. if (num_times > CBT_NCIRCUITS_TO_OBSERVE) {
  654. log_notice(LD_CIRC, "The number of circuit times that this Tor version "
  655. "uses to calculate build times is less than the number stored "
  656. "in your state file. Decreasing the circuit time history from "
  657. "%lu to %d.", (unsigned long)num_times,
  658. CBT_NCIRCUITS_TO_OBSERVE);
  659. }
  660. if (n > INT_MAX-1) {
  661. log_warn(LD_CIRC, "For some insane reasons, you had %lu circuit build "
  662. "observations in your state file. That's far too many; probably "
  663. "there's a bug here.", (unsigned long)n);
  664. n = INT_MAX-1;
  665. }
  666. /* This code can only be run on a compact array */
  667. while (n-- > 1) {
  668. int k = crypto_rand_int(n + 1); /* 0 <= k <= n. */
  669. build_time_t tmp = raw_times[k];
  670. raw_times[k] = raw_times[n];
  671. raw_times[n] = tmp;
  672. }
  673. /* Since the times are now shuffled, take a random CBT_NCIRCUITS_TO_OBSERVE
  674. * subset (ie the first CBT_NCIRCUITS_TO_OBSERVE values) */
  675. for (n = 0; n < MIN(num_times, CBT_NCIRCUITS_TO_OBSERVE); n++) {
  676. circuit_build_times_add_time(cbt, raw_times[n]);
  677. }
  678. }
  679. /**
  680. * Filter old synthetic timeouts that were created before the
  681. * new right-censored Pareto calculation was deployed.
  682. *
  683. * Once all clients before 0.2.1.13-alpha are gone, this code
  684. * will be unused.
  685. */
  686. static int
  687. circuit_build_times_filter_timeouts(circuit_build_times_t *cbt)
  688. {
  689. int num_filtered=0, i=0;
  690. double timeout_rate = 0;
  691. build_time_t max_timeout = 0;
  692. timeout_rate = circuit_build_times_timeout_rate(cbt);
  693. max_timeout = (build_time_t)cbt->close_ms;
  694. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  695. if (cbt->circuit_build_times[i] > max_timeout) {
  696. build_time_t replaced = cbt->circuit_build_times[i];
  697. num_filtered++;
  698. cbt->circuit_build_times[i] = CBT_BUILD_ABANDONED;
  699. log_debug(LD_CIRC, "Replaced timeout %d with %d", replaced,
  700. cbt->circuit_build_times[i]);
  701. }
  702. }
  703. log_info(LD_CIRC,
  704. "We had %d timeouts out of %d build times, "
  705. "and filtered %d above the max of %u",
  706. (int)(cbt->total_build_times*timeout_rate),
  707. cbt->total_build_times, num_filtered, max_timeout);
  708. return num_filtered;
  709. }
  710. /**
  711. * Load histogram from <b>state</b>, shuffling the resulting array
  712. * after we do so. Use this result to estimate parameters and
  713. * calculate the timeout.
  714. *
  715. * Return -1 on error.
  716. */
  717. int
  718. circuit_build_times_parse_state(circuit_build_times_t *cbt,
  719. or_state_t *state)
  720. {
  721. int tot_values = 0;
  722. uint32_t loaded_cnt = 0, N = 0;
  723. config_line_t *line;
  724. unsigned int i;
  725. build_time_t *loaded_times;
  726. int err = 0;
  727. circuit_build_times_init(cbt);
  728. if (circuit_build_times_disabled()) {
  729. return 0;
  730. }
  731. /* build_time_t 0 means uninitialized */
  732. loaded_times = tor_malloc_zero(sizeof(build_time_t)*state->TotalBuildTimes);
  733. for (line = state->BuildtimeHistogram; line; line = line->next) {
  734. smartlist_t *args = smartlist_new();
  735. smartlist_split_string(args, line->value, " ",
  736. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  737. if (smartlist_len(args) < 2) {
  738. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  739. "Too few arguments to CircuitBuildTime");
  740. err = 1;
  741. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  742. smartlist_free(args);
  743. break;
  744. } else {
  745. const char *ms_str = smartlist_get(args,0);
  746. const char *count_str = smartlist_get(args,1);
  747. uint32_t count, k;
  748. build_time_t ms;
  749. int ok;
  750. ms = (build_time_t)tor_parse_ulong(ms_str, 0, 0,
  751. CBT_BUILD_TIME_MAX, &ok, NULL);
  752. if (!ok) {
  753. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  754. "Unparsable bin number");
  755. err = 1;
  756. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  757. smartlist_free(args);
  758. break;
  759. }
  760. count = (uint32_t)tor_parse_ulong(count_str, 0, 0,
  761. UINT32_MAX, &ok, NULL);
  762. if (!ok) {
  763. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  764. "Unparsable bin count");
  765. err = 1;
  766. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  767. smartlist_free(args);
  768. break;
  769. }
  770. if (loaded_cnt+count+state->CircuitBuildAbandonedCount
  771. > state->TotalBuildTimes) {
  772. log_warn(LD_CIRC,
  773. "Too many build times in state file. "
  774. "Stopping short before %d",
  775. loaded_cnt+count);
  776. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  777. smartlist_free(args);
  778. break;
  779. }
  780. for (k = 0; k < count; k++) {
  781. loaded_times[loaded_cnt++] = ms;
  782. }
  783. N++;
  784. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  785. smartlist_free(args);
  786. }
  787. }
  788. log_info(LD_CIRC,
  789. "Adding %d timeouts.", state->CircuitBuildAbandonedCount);
  790. for (i=0; i < state->CircuitBuildAbandonedCount; i++) {
  791. loaded_times[loaded_cnt++] = CBT_BUILD_ABANDONED;
  792. }
  793. if (loaded_cnt != state->TotalBuildTimes) {
  794. log_warn(LD_CIRC,
  795. "Corrupt state file? Build times count mismatch. "
  796. "Read %d times, but file says %d", loaded_cnt,
  797. state->TotalBuildTimes);
  798. err = 1;
  799. circuit_build_times_reset(cbt);
  800. goto done;
  801. }
  802. circuit_build_times_shuffle_and_store_array(cbt, loaded_times, loaded_cnt);
  803. /* Verify that we didn't overwrite any indexes */
  804. for (i=0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  805. if (!cbt->circuit_build_times[i])
  806. break;
  807. tot_values++;
  808. }
  809. log_info(LD_CIRC,
  810. "Loaded %d/%d values from %d lines in circuit time histogram",
  811. tot_values, cbt->total_build_times, N);
  812. if (cbt->total_build_times != tot_values
  813. || cbt->total_build_times > CBT_NCIRCUITS_TO_OBSERVE) {
  814. log_warn(LD_CIRC,
  815. "Corrupt state file? Shuffled build times mismatch. "
  816. "Read %d times, but file says %d", tot_values,
  817. state->TotalBuildTimes);
  818. err = 1;
  819. circuit_build_times_reset(cbt);
  820. goto done;
  821. }
  822. circuit_build_times_set_timeout(cbt);
  823. if (!state->CircuitBuildAbandonedCount && cbt->total_build_times) {
  824. circuit_build_times_filter_timeouts(cbt);
  825. }
  826. done:
  827. tor_free(loaded_times);
  828. return err ? -1 : 0;
  829. }
  830. /**
  831. * Estimates the Xm and Alpha parameters using
  832. * http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
  833. *
  834. * The notable difference is that we use mode instead of min to estimate Xm.
  835. * This is because our distribution is frechet-like. We claim this is
  836. * an acceptable approximation because we are only concerned with the
  837. * accuracy of the CDF of the tail.
  838. */
  839. int
  840. circuit_build_times_update_alpha(circuit_build_times_t *cbt)
  841. {
  842. build_time_t *x=cbt->circuit_build_times;
  843. double a = 0;
  844. int n=0,i=0,abandoned_count=0;
  845. build_time_t max_time=0;
  846. /* http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation */
  847. /* We sort of cheat here and make our samples slightly more pareto-like
  848. * and less frechet-like. */
  849. cbt->Xm = circuit_build_times_get_xm(cbt);
  850. tor_assert(cbt->Xm > 0);
  851. for (i=0; i< CBT_NCIRCUITS_TO_OBSERVE; i++) {
  852. if (!x[i]) {
  853. continue;
  854. }
  855. if (x[i] < cbt->Xm) {
  856. a += tor_mathlog(cbt->Xm);
  857. } else if (x[i] == CBT_BUILD_ABANDONED) {
  858. abandoned_count++;
  859. } else {
  860. a += tor_mathlog(x[i]);
  861. if (x[i] > max_time)
  862. max_time = x[i];
  863. }
  864. n++;
  865. }
  866. /*
  867. * We are erring and asserting here because this can only happen
  868. * in codepaths other than startup. The startup state parsing code
  869. * performs this same check, and resets state if it hits it. If we
  870. * hit it at runtime, something serious has gone wrong.
  871. */
  872. if (n!=cbt->total_build_times) {
  873. log_err(LD_CIRC, "Discrepancy in build times count: %d vs %d", n,
  874. cbt->total_build_times);
  875. }
  876. tor_assert(n==cbt->total_build_times);
  877. if (max_time <= 0) {
  878. /* This can happen if Xm is actually the *maximum* value in the set.
  879. * It can also happen if we've abandoned every single circuit somehow.
  880. * In either case, tell the caller not to compute a new build timeout. */
  881. log_warn(LD_BUG,
  882. "Could not determine largest build time (%d). "
  883. "Xm is %dms and we've abandoned %d out of %d circuits.", max_time,
  884. cbt->Xm, abandoned_count, n);
  885. return 0;
  886. }
  887. a += abandoned_count*tor_mathlog(max_time);
  888. a -= n*tor_mathlog(cbt->Xm);
  889. // Estimator comes from Eq #4 in:
  890. // "Bayesian estimation based on trimmed samples from Pareto populations"
  891. // by Arturo J. Fernández. We are right-censored only.
  892. a = (n-abandoned_count)/a;
  893. cbt->alpha = a;
  894. return 1;
  895. }
  896. /**
  897. * This is the Pareto Quantile Function. It calculates the point x
  898. * in the distribution such that F(x) = quantile (ie quantile*100%
  899. * of the mass of the density function is below x on the curve).
  900. *
  901. * We use it to calculate the timeout and also to generate synthetic
  902. * values of time for circuits that timeout before completion.
  903. *
  904. * See http://en.wikipedia.org/wiki/Quantile_function,
  905. * http://en.wikipedia.org/wiki/Inverse_transform_sampling and
  906. * http://en.wikipedia.org/wiki/Pareto_distribution#Generating_a_
  907. * random_sample_from_Pareto_distribution
  908. * That's right. I'll cite wikipedia all day long.
  909. *
  910. * Return value is in milliseconds.
  911. */
  912. double
  913. circuit_build_times_calculate_timeout(circuit_build_times_t *cbt,
  914. double quantile)
  915. {
  916. double ret;
  917. tor_assert(quantile >= 0);
  918. tor_assert(1.0-quantile > 0);
  919. tor_assert(cbt->Xm > 0);
  920. ret = cbt->Xm/pow(1.0-quantile,1.0/cbt->alpha);
  921. if (ret > INT32_MAX) {
  922. ret = INT32_MAX;
  923. }
  924. tor_assert(ret > 0);
  925. return ret;
  926. }
  927. /** Pareto CDF */
  928. double
  929. circuit_build_times_cdf(circuit_build_times_t *cbt, double x)
  930. {
  931. double ret;
  932. tor_assert(cbt->Xm > 0);
  933. ret = 1.0-pow(cbt->Xm/x,cbt->alpha);
  934. tor_assert(0 <= ret && ret <= 1.0);
  935. return ret;
  936. }
  937. /**
  938. * Generate a synthetic time using our distribution parameters.
  939. *
  940. * The return value will be within the [q_lo, q_hi) quantile points
  941. * on the CDF.
  942. */
  943. build_time_t
  944. circuit_build_times_generate_sample(circuit_build_times_t *cbt,
  945. double q_lo, double q_hi)
  946. {
  947. double randval = crypto_rand_double();
  948. build_time_t ret;
  949. double u;
  950. /* Generate between [q_lo, q_hi) */
  951. /*XXXX This is what nextafter is supposed to be for; we should use it on the
  952. * platforms that support it. */
  953. q_hi -= 1.0/(INT32_MAX);
  954. tor_assert(q_lo >= 0);
  955. tor_assert(q_hi < 1);
  956. tor_assert(q_lo < q_hi);
  957. u = q_lo + (q_hi-q_lo)*randval;
  958. tor_assert(0 <= u && u < 1.0);
  959. /* circuit_build_times_calculate_timeout returns <= INT32_MAX */
  960. ret = (build_time_t)
  961. tor_lround(circuit_build_times_calculate_timeout(cbt, u));
  962. tor_assert(ret > 0);
  963. return ret;
  964. }
  965. /**
  966. * Estimate an initial alpha parameter by solving the quantile
  967. * function with a quantile point and a specific timeout value.
  968. */
  969. void
  970. circuit_build_times_initial_alpha(circuit_build_times_t *cbt,
  971. double quantile, double timeout_ms)
  972. {
  973. // Q(u) = Xm/((1-u)^(1/a))
  974. // Q(0.8) = Xm/((1-0.8))^(1/a)) = CircBuildTimeout
  975. // CircBuildTimeout = Xm/((1-0.8))^(1/a))
  976. // CircBuildTimeout = Xm*((1-0.8))^(-1/a))
  977. // ln(CircBuildTimeout) = ln(Xm)+ln(((1-0.8)))*(-1/a)
  978. // -ln(1-0.8)/(ln(CircBuildTimeout)-ln(Xm))=a
  979. tor_assert(quantile >= 0);
  980. tor_assert(cbt->Xm > 0);
  981. cbt->alpha = tor_mathlog(1.0-quantile)/
  982. (tor_mathlog(cbt->Xm)-tor_mathlog(timeout_ms));
  983. tor_assert(cbt->alpha > 0);
  984. }
  985. /**
  986. * Returns true if we need circuits to be built
  987. */
  988. int
  989. circuit_build_times_needs_circuits(circuit_build_times_t *cbt)
  990. {
  991. /* Return true if < MIN_CIRCUITS_TO_OBSERVE */
  992. return !circuit_build_times_enough_to_compute(cbt);
  993. }
  994. /**
  995. * Returns true if we should build a timeout test circuit
  996. * right now.
  997. */
  998. int
  999. circuit_build_times_needs_circuits_now(circuit_build_times_t *cbt)
  1000. {
  1001. return circuit_build_times_needs_circuits(cbt) &&
  1002. approx_time()-cbt->last_circ_at > circuit_build_times_test_frequency();
  1003. }
  1004. /**
  1005. * Called to indicate that the network showed some signs of liveness,
  1006. * i.e. we received a cell.
  1007. *
  1008. * This is used by circuit_build_times_network_check_live() to decide
  1009. * if we should record the circuit build timeout or not.
  1010. *
  1011. * This function is called every time we receive a cell. Avoid
  1012. * syscalls, events, and other high-intensity work.
  1013. */
  1014. void
  1015. circuit_build_times_network_is_live(circuit_build_times_t *cbt)
  1016. {
  1017. time_t now = approx_time();
  1018. if (cbt->liveness.nonlive_timeouts > 0) {
  1019. log_notice(LD_CIRC,
  1020. "Tor now sees network activity. Restoring circuit build "
  1021. "timeout recording. Network was down for %d seconds "
  1022. "during %d circuit attempts.",
  1023. (int)(now - cbt->liveness.network_last_live),
  1024. cbt->liveness.nonlive_timeouts);
  1025. }
  1026. cbt->liveness.network_last_live = now;
  1027. cbt->liveness.nonlive_timeouts = 0;
  1028. }
  1029. /**
  1030. * Called to indicate that we completed a circuit. Because this circuit
  1031. * succeeded, it doesn't count as a timeout-after-the-first-hop.
  1032. *
  1033. * This is used by circuit_build_times_network_check_changed() to determine
  1034. * if we had too many recent timeouts and need to reset our learned timeout
  1035. * to something higher.
  1036. */
  1037. void
  1038. circuit_build_times_network_circ_success(circuit_build_times_t *cbt)
  1039. {
  1040. /* Check for NULLness because we might not be using adaptive timeouts */
  1041. if (cbt->liveness.timeouts_after_firsthop &&
  1042. cbt->liveness.num_recent_circs > 0) {
  1043. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1044. = 0;
  1045. cbt->liveness.after_firsthop_idx++;
  1046. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1047. }
  1048. }
  1049. /**
  1050. * A circuit just timed out. If it failed after the first hop, record it
  1051. * in our history for later deciding if the network speed has changed.
  1052. *
  1053. * This is used by circuit_build_times_network_check_changed() to determine
  1054. * if we had too many recent timeouts and need to reset our learned timeout
  1055. * to something higher.
  1056. */
  1057. static void
  1058. circuit_build_times_network_timeout(circuit_build_times_t *cbt,
  1059. int did_onehop)
  1060. {
  1061. /* Check for NULLness because we might not be using adaptive timeouts */
  1062. if (cbt->liveness.timeouts_after_firsthop &&
  1063. cbt->liveness.num_recent_circs > 0) {
  1064. if (did_onehop) {
  1065. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1066. = 1;
  1067. cbt->liveness.after_firsthop_idx++;
  1068. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1069. }
  1070. }
  1071. }
  1072. /**
  1073. * A circuit was just forcibly closed. If there has been no recent network
  1074. * activity at all, but this circuit was launched back when we thought the
  1075. * network was live, increment the number of "nonlive" circuit timeouts.
  1076. *
  1077. * This is used by circuit_build_times_network_check_live() to decide
  1078. * if we should record the circuit build timeout or not.
  1079. */
  1080. static void
  1081. circuit_build_times_network_close(circuit_build_times_t *cbt,
  1082. int did_onehop, time_t start_time)
  1083. {
  1084. time_t now = time(NULL);
  1085. /*
  1086. * Check if this is a timeout that was for a circuit that spent its
  1087. * entire existence during a time where we have had no network activity.
  1088. */
  1089. if (cbt->liveness.network_last_live < start_time) {
  1090. if (did_onehop) {
  1091. char last_live_buf[ISO_TIME_LEN+1];
  1092. char start_time_buf[ISO_TIME_LEN+1];
  1093. char now_buf[ISO_TIME_LEN+1];
  1094. format_local_iso_time(last_live_buf, cbt->liveness.network_last_live);
  1095. format_local_iso_time(start_time_buf, start_time);
  1096. format_local_iso_time(now_buf, now);
  1097. log_warn(LD_BUG,
  1098. "Circuit somehow completed a hop while the network was "
  1099. "not live. Network was last live at %s, but circuit launched "
  1100. "at %s. It's now %s.", last_live_buf, start_time_buf,
  1101. now_buf);
  1102. }
  1103. cbt->liveness.nonlive_timeouts++;
  1104. if (cbt->liveness.nonlive_timeouts == 1) {
  1105. log_notice(LD_CIRC,
  1106. "Tor has not observed any network activity for the past %d "
  1107. "seconds. Disabling circuit build timeout recording.",
  1108. (int)(now - cbt->liveness.network_last_live));
  1109. } else {
  1110. log_info(LD_CIRC,
  1111. "Got non-live timeout. Current count is: %d",
  1112. cbt->liveness.nonlive_timeouts);
  1113. }
  1114. }
  1115. }
  1116. /**
  1117. * When the network is not live, we do not record circuit build times.
  1118. *
  1119. * The network is considered not live if there has been at least one
  1120. * circuit build that began and ended (had its close_ms measurement
  1121. * period expire) since we last received a cell.
  1122. *
  1123. * Also has the side effect of rewinding the circuit time history
  1124. * in the case of recent liveness changes.
  1125. */
  1126. int
  1127. circuit_build_times_network_check_live(circuit_build_times_t *cbt)
  1128. {
  1129. if (cbt->liveness.nonlive_timeouts > 0) {
  1130. return 0;
  1131. }
  1132. return 1;
  1133. }
  1134. /**
  1135. * Returns true if we have seen more than MAX_RECENT_TIMEOUT_COUNT of
  1136. * the past RECENT_CIRCUITS time out after the first hop. Used to detect
  1137. * if the network connection has changed significantly, and if so,
  1138. * resets our circuit build timeout to the default.
  1139. *
  1140. * Also resets the entire timeout history in this case and causes us
  1141. * to restart the process of building test circuits and estimating a
  1142. * new timeout.
  1143. */
  1144. int
  1145. circuit_build_times_network_check_changed(circuit_build_times_t *cbt)
  1146. {
  1147. int total_build_times = cbt->total_build_times;
  1148. int timeout_count=0;
  1149. int i;
  1150. if (cbt->liveness.timeouts_after_firsthop &&
  1151. cbt->liveness.num_recent_circs > 0) {
  1152. /* how many of our recent circuits made it to the first hop but then
  1153. * timed out? */
  1154. for (i = 0; i < cbt->liveness.num_recent_circs; i++) {
  1155. timeout_count += cbt->liveness.timeouts_after_firsthop[i];
  1156. }
  1157. }
  1158. /* If 80% of our recent circuits are timing out after the first hop,
  1159. * we need to re-estimate a new initial alpha and timeout. */
  1160. if (timeout_count < circuit_build_times_max_timeouts()) {
  1161. return 0;
  1162. }
  1163. circuit_build_times_reset(cbt);
  1164. if (cbt->liveness.timeouts_after_firsthop &&
  1165. cbt->liveness.num_recent_circs > 0) {
  1166. memset(cbt->liveness.timeouts_after_firsthop, 0,
  1167. sizeof(*cbt->liveness.timeouts_after_firsthop)*
  1168. cbt->liveness.num_recent_circs);
  1169. }
  1170. cbt->liveness.after_firsthop_idx = 0;
  1171. /* Check to see if this has happened before. If so, double the timeout
  1172. * to give people on abysmally bad network connections a shot at access */
  1173. if (cbt->timeout_ms >= circuit_build_times_get_initial_timeout()) {
  1174. if (cbt->timeout_ms > INT32_MAX/2 || cbt->close_ms > INT32_MAX/2) {
  1175. log_warn(LD_CIRC, "Insanely large circuit build timeout value. "
  1176. "(timeout = %fmsec, close = %fmsec)",
  1177. cbt->timeout_ms, cbt->close_ms);
  1178. } else {
  1179. cbt->timeout_ms *= 2;
  1180. cbt->close_ms *= 2;
  1181. }
  1182. } else {
  1183. cbt->close_ms = cbt->timeout_ms
  1184. = circuit_build_times_get_initial_timeout();
  1185. }
  1186. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  1187. log_notice(LD_CIRC,
  1188. "Your network connection speed appears to have changed. Resetting "
  1189. "timeout to %lds after %d timeouts and %d buildtimes.",
  1190. tor_lround(cbt->timeout_ms/1000), timeout_count,
  1191. total_build_times);
  1192. return 1;
  1193. }
  1194. /**
  1195. * Count the number of timeouts in a set of cbt data.
  1196. */
  1197. double
  1198. circuit_build_times_timeout_rate(const circuit_build_times_t *cbt)
  1199. {
  1200. int i=0,timeouts=0;
  1201. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1202. if (cbt->circuit_build_times[i] >= cbt->timeout_ms) {
  1203. timeouts++;
  1204. }
  1205. }
  1206. if (!cbt->total_build_times)
  1207. return 0;
  1208. return ((double)timeouts)/cbt->total_build_times;
  1209. }
  1210. /**
  1211. * Count the number of closed circuits in a set of cbt data.
  1212. */
  1213. double
  1214. circuit_build_times_close_rate(const circuit_build_times_t *cbt)
  1215. {
  1216. int i=0,closed=0;
  1217. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1218. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED) {
  1219. closed++;
  1220. }
  1221. }
  1222. if (!cbt->total_build_times)
  1223. return 0;
  1224. return ((double)closed)/cbt->total_build_times;
  1225. }
  1226. /**
  1227. * Store a timeout as a synthetic value.
  1228. *
  1229. * Returns true if the store was successful and we should possibly
  1230. * update our timeout estimate.
  1231. */
  1232. int
  1233. circuit_build_times_count_close(circuit_build_times_t *cbt,
  1234. int did_onehop,
  1235. time_t start_time)
  1236. {
  1237. if (circuit_build_times_disabled()) {
  1238. cbt->close_ms = cbt->timeout_ms
  1239. = circuit_build_times_get_initial_timeout();
  1240. return 0;
  1241. }
  1242. /* Record this force-close to help determine if the network is dead */
  1243. circuit_build_times_network_close(cbt, did_onehop, start_time);
  1244. /* Only count timeouts if network is live.. */
  1245. if (!circuit_build_times_network_check_live(cbt)) {
  1246. return 0;
  1247. }
  1248. circuit_build_times_add_time(cbt, CBT_BUILD_ABANDONED);
  1249. return 1;
  1250. }
  1251. /**
  1252. * Update timeout counts to determine if we need to expire
  1253. * our build time history due to excessive timeouts.
  1254. *
  1255. * We do not record any actual time values at this stage;
  1256. * we are only interested in recording the fact that a timeout
  1257. * happened. We record the time values via
  1258. * circuit_build_times_count_close() and circuit_build_times_add_time().
  1259. */
  1260. void
  1261. circuit_build_times_count_timeout(circuit_build_times_t *cbt,
  1262. int did_onehop)
  1263. {
  1264. if (circuit_build_times_disabled()) {
  1265. cbt->close_ms = cbt->timeout_ms
  1266. = circuit_build_times_get_initial_timeout();
  1267. return;
  1268. }
  1269. /* Register the fact that a timeout just occurred. */
  1270. circuit_build_times_network_timeout(cbt, did_onehop);
  1271. /* If there are a ton of timeouts, we should reset
  1272. * the circuit build timeout. */
  1273. circuit_build_times_network_check_changed(cbt);
  1274. }
  1275. /**
  1276. * Estimate a new timeout based on history and set our timeout
  1277. * variable accordingly.
  1278. */
  1279. static int
  1280. circuit_build_times_set_timeout_worker(circuit_build_times_t *cbt)
  1281. {
  1282. build_time_t max_time;
  1283. if (!circuit_build_times_enough_to_compute(cbt))
  1284. return 0;
  1285. if (!circuit_build_times_update_alpha(cbt))
  1286. return 0;
  1287. cbt->timeout_ms = circuit_build_times_calculate_timeout(cbt,
  1288. circuit_build_times_quantile_cutoff());
  1289. cbt->close_ms = circuit_build_times_calculate_timeout(cbt,
  1290. circuit_build_times_close_quantile());
  1291. max_time = circuit_build_times_max(cbt);
  1292. if (cbt->timeout_ms > max_time) {
  1293. log_info(LD_CIRC,
  1294. "Circuit build timeout of %dms is beyond the maximum build "
  1295. "time we have ever observed. Capping it to %dms.",
  1296. (int)cbt->timeout_ms, max_time);
  1297. cbt->timeout_ms = max_time;
  1298. }
  1299. if (max_time < INT32_MAX/2 && cbt->close_ms > 2*max_time) {
  1300. log_info(LD_CIRC,
  1301. "Circuit build measurement period of %dms is more than twice "
  1302. "the maximum build time we have ever observed. Capping it to "
  1303. "%dms.", (int)cbt->close_ms, 2*max_time);
  1304. cbt->close_ms = 2*max_time;
  1305. }
  1306. /* Sometimes really fast guard nodes give us such a steep curve
  1307. * that this ends up being not that much greater than timeout_ms.
  1308. * Make it be at least 1 min to handle this case. */
  1309. cbt->close_ms = MAX(cbt->close_ms, circuit_build_times_initial_timeout());
  1310. cbt->have_computed_timeout = 1;
  1311. return 1;
  1312. }
  1313. /**
  1314. * Exposed function to compute a new timeout. Dispatches events and
  1315. * also filters out extremely high timeout values.
  1316. */
  1317. void
  1318. circuit_build_times_set_timeout(circuit_build_times_t *cbt)
  1319. {
  1320. long prev_timeout = tor_lround(cbt->timeout_ms/1000);
  1321. double timeout_rate;
  1322. /*
  1323. * Just return if we aren't using adaptive timeouts
  1324. */
  1325. if (circuit_build_times_disabled())
  1326. return;
  1327. if (!circuit_build_times_set_timeout_worker(cbt))
  1328. return;
  1329. if (cbt->timeout_ms < circuit_build_times_min_timeout()) {
  1330. log_info(LD_CIRC, "Set buildtimeout to low value %fms. Setting to %dms",
  1331. cbt->timeout_ms, circuit_build_times_min_timeout());
  1332. cbt->timeout_ms = circuit_build_times_min_timeout();
  1333. if (cbt->close_ms < cbt->timeout_ms) {
  1334. /* This shouldn't happen because of MAX() in timeout_worker above,
  1335. * but doing it just in case */
  1336. cbt->close_ms = circuit_build_times_initial_timeout();
  1337. }
  1338. }
  1339. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_COMPUTED);
  1340. timeout_rate = circuit_build_times_timeout_rate(cbt);
  1341. if (prev_timeout > tor_lround(cbt->timeout_ms/1000)) {
  1342. log_info(LD_CIRC,
  1343. "Based on %d circuit times, it looks like we don't need to "
  1344. "wait so long for circuits to finish. We will now assume a "
  1345. "circuit is too slow to use after waiting %ld seconds.",
  1346. cbt->total_build_times,
  1347. tor_lround(cbt->timeout_ms/1000));
  1348. log_info(LD_CIRC,
  1349. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1350. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1351. timeout_rate);
  1352. } else if (prev_timeout < tor_lround(cbt->timeout_ms/1000)) {
  1353. log_info(LD_CIRC,
  1354. "Based on %d circuit times, it looks like we need to wait "
  1355. "longer for circuits to finish. We will now assume a "
  1356. "circuit is too slow to use after waiting %ld seconds.",
  1357. cbt->total_build_times,
  1358. tor_lround(cbt->timeout_ms/1000));
  1359. log_info(LD_CIRC,
  1360. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1361. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1362. timeout_rate);
  1363. } else {
  1364. log_info(LD_CIRC,
  1365. "Set circuit build timeout to %lds (%fms, %fms, Xm: %d, a: %f,"
  1366. " r: %f) based on %d circuit times",
  1367. tor_lround(cbt->timeout_ms/1000),
  1368. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha, timeout_rate,
  1369. cbt->total_build_times);
  1370. }
  1371. }
  1372. /** Make a note that we're running unit tests (rather than running Tor
  1373. * itself), so we avoid clobbering our state file. */
  1374. void
  1375. circuitbuild_running_unit_tests(void)
  1376. {
  1377. unit_tests = 1;
  1378. }