circuitstats.c 55 KB

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