circuitstats.c 49 KB

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