entrynodes.c 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413
  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-2016, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file entrynodes.c
  8. * \brief Code to manage our fixed first nodes for various functions.
  9. *
  10. * Entry nodes can be guards (for general use) or bridges (for censorship
  11. * circumvention).
  12. *
  13. * In general, we use entry guards to prevent traffic-sampling attacks:
  14. * if we chose every circuit independently, an adversary controlling
  15. * some fraction of paths on the network would observe a sample of every
  16. * user's traffic. Using guards gives users a chance of not being
  17. * profiled.
  18. *
  19. * The current entry guard selection code is designed to try to avoid
  20. * _ever_ trying every guard on the network, to try to stick to guards
  21. * that we've used before, to handle hostile/broken networks, and
  22. * to behave sanely when the network goes up and down.
  23. *
  24. * Our algorithm works as follows: First, we maintain a SAMPLE of guards
  25. * we've seen in the networkstatus consensus. We maintain this sample
  26. * over time, and store it persistently; it is chosen without reference
  27. * to our configuration or firewall rules. Guards remain in the sample
  28. * as they enter and leave the consensus. We expand this sample as
  29. * needed, up to a maximum size.
  30. *
  31. * As a subset of the sample, we maintain a FILTERED SET of the guards
  32. * that we would be willing to use if we could connect to them. The
  33. * filter removes all the guards that we're excluding because they're
  34. * bridges (or not bridges), because we have restrictive firewall rules,
  35. * because of ExcludeNodes, because we of path bias restrictions,
  36. * because they're absent from the network at present, and so on.
  37. *
  38. * As a subset of the filtered set, we keep a REACHABLE FILTERED SET
  39. * (also called a "usable filtered set") of those guards that we call
  40. * "reachable" or "maybe reachable". A guard is reachable if we've
  41. * connected to it more recently than we've failed. A guard is "maybe
  42. * reachable" if we have never tried to connect to it, or if we
  43. * failed to connect to it so long ago that we no longer think our
  44. * failure means it's down.
  45. *
  46. * As a persistent ordered list whose elements are taken from the
  47. * sampled set, we track a CONFIRMED GUARDS LIST. A guard becomes
  48. * confirmed when we successfully build a circuit through it, and decide
  49. * to use that circuit. We order the guards on this list by the order
  50. * in which they became confirmed.
  51. *
  52. * And as a final group, we have an ordered list of PRIMARY GUARDS,
  53. * whose elements are taken from the filtered set. We prefer
  54. * confirmed guards to non-confirmed guards for this list, and place
  55. * other restrictions on it. The primary guards are the ones that we
  56. * connect to "when nothing is wrong" -- circuits through them can be used
  57. * immediately.
  58. *
  59. * To build circuits, we take a primary guard if possible -- or a
  60. * reachable filtered confirmed guard if no primary guard is possible --
  61. * or a random reachable filtered guard otherwise. If the guard is
  62. * primary, we can use the circuit immediately on success. Otherwise,
  63. * the guard is now "pending" -- we won't use its circuit unless all
  64. * of the circuits we're trying to build through better guards have
  65. * definitely failed.
  66. *
  67. * While we're building circuits, we track a little "guard state" for
  68. * each circuit. We use this to keep track of whether the circuit is
  69. * one that we can use as soon as its done, or whether it's one that
  70. * we should keep around to see if we can do better. In the latter case,
  71. * a periodic call to entry_guards_upgrade_waiting_circuits() will
  72. * eventually upgrade it.
  73. **/
  74. /* DOCDOC -- expand this.
  75. *
  76. * Information invariants:
  77. *
  78. * [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
  79. *
  80. * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
  81. * flag is set, set its usable_filtered flag.
  82. *
  83. * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
  84. *
  85. * [x] Whenever the configuration changes in a relevant way, update the
  86. * filtered/usable flags. (LATER.)
  87. *
  88. * [x] Whenever we add a guard to the sample, make sure its filtered/usable
  89. * flags are set as possible.
  90. *
  91. * [x] Whenever we remove a guard from the sample, remove it from the primary
  92. * and confirmed lists.
  93. *
  94. * [x] When we make a guard confirmed, update the primary list.
  95. *
  96. * [x] When we make a guard filtered or unfiltered, update the primary list.
  97. *
  98. * [x] When we are about to pick a guard, make sure that the primary list is
  99. * full.
  100. *
  101. * [x] Before calling sample_reachable_filtered_entry_guards(), make sure
  102. * that the filtered, primary, and confirmed flags are up-to-date.
  103. *
  104. * [x] Call entry_guard_consider_retry every time we are about to check
  105. * is_usable_filtered or is_reachable, and every time we set
  106. * is_filtered to 1.
  107. *
  108. * [x] Call entry_guards_changed_for_guard_selection() whenever we update
  109. * a persistent field.
  110. */
  111. #define ENTRYNODES_PRIVATE
  112. #include "or.h"
  113. #include "channel.h"
  114. #include "bridges.h"
  115. #include "circpathbias.h"
  116. #include "circuitbuild.h"
  117. #include "circuitlist.h"
  118. #include "circuitstats.h"
  119. #include "config.h"
  120. #include "confparse.h"
  121. #include "connection.h"
  122. #include "control.h"
  123. #include "directory.h"
  124. #include "entrynodes.h"
  125. #include "main.h"
  126. #include "microdesc.h"
  127. #include "networkstatus.h"
  128. #include "nodelist.h"
  129. #include "policies.h"
  130. #include "router.h"
  131. #include "routerlist.h"
  132. #include "routerparse.h"
  133. #include "routerset.h"
  134. #include "transports.h"
  135. #include "statefile.h"
  136. /** A list of existing guard selection contexts. */
  137. static smartlist_t *guard_contexts = NULL;
  138. /** The currently enabled guard selection context. */
  139. static guard_selection_t *curr_guard_context = NULL;
  140. /** A value of 1 means that at least one context has changed,
  141. * and those changes need to be flushed to disk. */
  142. static int entry_guards_dirty = 0;
  143. static void entry_guard_set_filtered_flags(const or_options_t *options,
  144. guard_selection_t *gs,
  145. entry_guard_t *guard);
  146. static void pathbias_check_use_success_count(entry_guard_t *guard);
  147. static void pathbias_check_close_success_count(entry_guard_t *guard);
  148. static int node_is_possible_guard(const node_t *node);
  149. static int node_passes_guard_filter(const or_options_t *options,
  150. const node_t *node);
  151. static entry_guard_t *entry_guard_add_to_sample_impl(guard_selection_t *gs,
  152. const uint8_t *rsa_id_digest,
  153. const char *nickname,
  154. const tor_addr_port_t *bridge_addrport);
  155. static entry_guard_t *get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
  156. const tor_addr_port_t *addrport);
  157. static int entry_guard_obeys_restriction(const entry_guard_t *guard,
  158. const entry_guard_restriction_t *rst);
  159. /** Return 0 if we should apply guardfraction information found in the
  160. * consensus. A specific consensus can be specified with the
  161. * <b>ns</b> argument, if NULL the most recent one will be picked.*/
  162. int
  163. should_apply_guardfraction(const networkstatus_t *ns)
  164. {
  165. /* We need to check the corresponding torrc option and the consensus
  166. * parameter if we need to. */
  167. const or_options_t *options = get_options();
  168. /* If UseGuardFraction is 'auto' then check the same-named consensus
  169. * parameter. If the consensus parameter is not present, default to
  170. * "off". */
  171. if (options->UseGuardFraction == -1) {
  172. return networkstatus_get_param(ns, "UseGuardFraction",
  173. 0, /* default to "off" */
  174. 0, 1);
  175. }
  176. return options->UseGuardFraction;
  177. }
  178. /** Return true iff we know a descriptor for <b>guard</b> */
  179. static int
  180. guard_has_descriptor(const entry_guard_t *guard)
  181. {
  182. const node_t *node = node_get_by_id(guard->identity);
  183. if (!node)
  184. return 0;
  185. return node_has_descriptor(node);
  186. }
  187. /**
  188. * Try to determine the correct type for a selection named "name",
  189. * if <b>type</b> is GS_TYPE_INFER.
  190. */
  191. STATIC guard_selection_type_t
  192. guard_selection_infer_type(guard_selection_type_t type,
  193. const char *name)
  194. {
  195. if (type == GS_TYPE_INFER) {
  196. if (!strcmp(name, "bridges"))
  197. type = GS_TYPE_BRIDGE;
  198. else if (!strcmp(name, "restricted"))
  199. type = GS_TYPE_RESTRICTED;
  200. else
  201. type = GS_TYPE_NORMAL;
  202. }
  203. return type;
  204. }
  205. /**
  206. * Allocate and return a new guard_selection_t, with the name <b>name</b>.
  207. */
  208. STATIC guard_selection_t *
  209. guard_selection_new(const char *name,
  210. guard_selection_type_t type)
  211. {
  212. guard_selection_t *gs;
  213. type = guard_selection_infer_type(type, name);
  214. gs = tor_malloc_zero(sizeof(*gs));
  215. gs->name = tor_strdup(name);
  216. gs->type = type;
  217. gs->sampled_entry_guards = smartlist_new();
  218. gs->confirmed_entry_guards = smartlist_new();
  219. gs->primary_entry_guards = smartlist_new();
  220. return gs;
  221. }
  222. /**
  223. * Return the guard selection called <b>name</b>. If there is none, and
  224. * <b>create_if_absent</b> is true, then create and return it. If there
  225. * is none, and <b>create_if_absent</b> is false, then return NULL.
  226. */
  227. STATIC guard_selection_t *
  228. get_guard_selection_by_name(const char *name,
  229. guard_selection_type_t type,
  230. int create_if_absent)
  231. {
  232. if (!guard_contexts) {
  233. guard_contexts = smartlist_new();
  234. }
  235. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  236. if (!strcmp(gs->name, name))
  237. return gs;
  238. } SMARTLIST_FOREACH_END(gs);
  239. if (! create_if_absent)
  240. return NULL;
  241. log_debug(LD_GUARD, "Creating a guard selection called %s", name);
  242. guard_selection_t *new_selection = guard_selection_new(name, type);
  243. smartlist_add(guard_contexts, new_selection);
  244. return new_selection;
  245. }
  246. /**
  247. * Allocate the first guard context that we're planning to use,
  248. * and make it the current context.
  249. */
  250. static void
  251. create_initial_guard_context(void)
  252. {
  253. tor_assert(! curr_guard_context);
  254. if (!guard_contexts) {
  255. guard_contexts = smartlist_new();
  256. }
  257. guard_selection_type_t type = GS_TYPE_INFER;
  258. const char *name = choose_guard_selection(
  259. get_options(),
  260. networkstatus_get_live_consensus(approx_time()),
  261. NULL,
  262. &type);
  263. tor_assert(name); // "name" can only be NULL if we had an old name.
  264. tor_assert(type != GS_TYPE_INFER);
  265. log_notice(LD_GUARD, "Starting with guard context \"%s\"", name);
  266. curr_guard_context = get_guard_selection_by_name(name, type, 1);
  267. }
  268. /** Get current default guard_selection_t, creating it if necessary */
  269. guard_selection_t *
  270. get_guard_selection_info(void)
  271. {
  272. if (!curr_guard_context) {
  273. create_initial_guard_context();
  274. }
  275. return curr_guard_context;
  276. }
  277. /** Return a statically allocated human-readable description of <b>guard</b>
  278. */
  279. const char *
  280. entry_guard_describe(const entry_guard_t *guard)
  281. {
  282. static char buf[256];
  283. tor_snprintf(buf, sizeof(buf),
  284. "%s ($%s)",
  285. strlen(guard->nickname) ? guard->nickname : "[bridge]",
  286. hex_str(guard->identity, DIGEST_LEN));
  287. return buf;
  288. }
  289. /** Return <b>guard</b>'s 20-byte RSA identity digest */
  290. const char *
  291. entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
  292. {
  293. return guard->identity;
  294. }
  295. /** Return the pathbias state associated with <b>guard</b>. */
  296. guard_pathbias_t *
  297. entry_guard_get_pathbias_state(entry_guard_t *guard)
  298. {
  299. return &guard->pb;
  300. }
  301. HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC)
  302. /** Return an interval betweeen 'now' and 'max_backdate' seconds in the past,
  303. * chosen uniformly at random. We use this before recording persistent
  304. * dates, so that we aren't leaking exactly when we recorded it.
  305. */
  306. MOCK_IMPL(STATIC time_t,
  307. randomize_time,(time_t now, time_t max_backdate))
  308. {
  309. tor_assert(max_backdate > 0);
  310. time_t earliest = now - max_backdate;
  311. time_t latest = now;
  312. if (earliest <= 0)
  313. earliest = 1;
  314. if (latest <= earliest)
  315. latest = earliest + 1;
  316. return crypto_rand_time_range(earliest, latest);
  317. }
  318. /**
  319. * @name parameters for networkstatus algorithm
  320. *
  321. * These parameters are taken from the consensus; some are overrideable in
  322. * the torrc.
  323. */
  324. /**@{*/
  325. /**
  326. * We never let our sampled guard set grow larger than this fraction
  327. * of the guards on the network.
  328. */
  329. STATIC double
  330. get_max_sample_threshold(void)
  331. {
  332. int32_t pct =
  333. networkstatus_get_param(NULL, "guard-max-sample-threshold-percent",
  334. DFLT_MAX_SAMPLE_THRESHOLD_PERCENT,
  335. 1, 100);
  336. return pct / 100.0;
  337. }
  338. /**
  339. * We never let our sampled guard set grow larger than this number.
  340. */
  341. STATIC int
  342. get_max_sample_size_absolute(void)
  343. {
  344. return (int) networkstatus_get_param(NULL, "guard-max-sample-size",
  345. DFLT_MAX_SAMPLE_SIZE,
  346. 1, INT32_MAX);
  347. }
  348. /**
  349. * We always try to make our sample contain at least this many guards.
  350. */
  351. STATIC int
  352. get_min_filtered_sample_size(void)
  353. {
  354. return networkstatus_get_param(NULL, "guard-min-filtered-sample-size",
  355. DFLT_MIN_FILTERED_SAMPLE_SIZE,
  356. 1, INT32_MAX);
  357. }
  358. /**
  359. * If a guard is unlisted for this many days in a row, we remove it.
  360. */
  361. STATIC int
  362. get_remove_unlisted_guards_after_days(void)
  363. {
  364. return networkstatus_get_param(NULL,
  365. "guard-remove-unlisted-guards-after-days",
  366. DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS,
  367. 1, 365*10);
  368. }
  369. /**
  370. * We remove unconfirmed guards from the sample after this many days,
  371. * regardless of whether they are listed or unlisted.
  372. */
  373. STATIC int
  374. get_guard_lifetime(void)
  375. {
  376. if (get_options()->GuardLifetime >= 86400)
  377. return get_options()->GuardLifetime;
  378. int32_t days;
  379. days = networkstatus_get_param(NULL,
  380. "guard-lifetime-days",
  381. DFLT_GUARD_LIFETIME_DAYS, 1, 365*10);
  382. return days * 86400;
  383. }
  384. /**
  385. * We remove confirmed guards from the sample if they were sampled
  386. * GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
  387. */
  388. STATIC int
  389. get_guard_confirmed_min_lifetime(void)
  390. {
  391. if (get_options()->GuardLifetime >= 86400)
  392. return get_options()->GuardLifetime;
  393. int32_t days;
  394. days = networkstatus_get_param(NULL, "guard-confirmed-min-lifetime-days",
  395. DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS,
  396. 1, 365*10);
  397. return days * 86400;
  398. }
  399. /**
  400. * How many guards do we try to keep on our primary guard list?
  401. */
  402. STATIC int
  403. get_n_primary_guards(void)
  404. {
  405. const int n = get_options()->NumEntryGuards;
  406. const int n_dir = get_options()->NumDirectoryGuards;
  407. if (n > 5) {
  408. return MAX(n_dir, n + n / 2);
  409. } else if (n >= 1) {
  410. return MAX(n_dir, n * 2);
  411. }
  412. return networkstatus_get_param(NULL,
  413. "guard-n-primary-guards",
  414. DFLT_N_PRIMARY_GUARDS, 1, INT32_MAX);
  415. }
  416. /**
  417. * Return the number of the live primary guards we should look at when
  418. * making a circuit.
  419. */
  420. STATIC int
  421. get_n_primary_guards_to_use(guard_usage_t usage)
  422. {
  423. int configured;
  424. const char *param_name;
  425. int param_default;
  426. if (usage == GUARD_USAGE_DIRGUARD) {
  427. configured = get_options()->NumDirectoryGuards;
  428. param_name = "guard-n-primary-dir-guards-to-use";
  429. param_default = DFLT_N_PRIMARY_DIR_GUARDS_TO_USE;
  430. } else {
  431. configured = get_options()->NumEntryGuards;
  432. param_name = "guard-n-primary-guards-to-use";
  433. param_default = DFLT_N_PRIMARY_GUARDS_TO_USE;
  434. }
  435. if (configured >= 1) {
  436. return configured;
  437. }
  438. return networkstatus_get_param(NULL,
  439. param_name, param_default, 1, INT32_MAX);
  440. }
  441. /**
  442. * If we haven't successfully built or used a circuit in this long, then
  443. * consider that the internet is probably down.
  444. */
  445. STATIC int
  446. get_internet_likely_down_interval(void)
  447. {
  448. return networkstatus_get_param(NULL, "guard-internet-likely-down-interval",
  449. DFLT_INTERNET_LIKELY_DOWN_INTERVAL,
  450. 1, INT32_MAX);
  451. }
  452. /**
  453. * If we're trying to connect to a nonprimary guard for at least this
  454. * many seconds, and we haven't gotten the connection to work, we will treat
  455. * lower-priority guards as usable.
  456. */
  457. STATIC int
  458. get_nonprimary_guard_connect_timeout(void)
  459. {
  460. return networkstatus_get_param(NULL,
  461. "guard-nonprimary-guard-connect-timeout",
  462. DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT,
  463. 1, INT32_MAX);
  464. }
  465. /**
  466. * If a circuit has been sitting around in 'waiting for better guard' state
  467. * for at least this long, we'll expire it.
  468. */
  469. STATIC int
  470. get_nonprimary_guard_idle_timeout(void)
  471. {
  472. return networkstatus_get_param(NULL,
  473. "guard-nonprimary-guard-idle-timeout",
  474. DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT,
  475. 1, INT32_MAX);
  476. }
  477. /**
  478. * If our configuration retains fewer than this fraction of guards from the
  479. * torrc, we are in a restricted setting.
  480. */
  481. STATIC double
  482. get_meaningful_restriction_threshold(void)
  483. {
  484. int32_t pct = networkstatus_get_param(NULL,
  485. "guard-meaningful-restriction-percent",
  486. DFLT_MEANINGFUL_RESTRICTION_PERCENT,
  487. 1, INT32_MAX);
  488. return pct / 100.0;
  489. }
  490. /**
  491. * If our configuration retains fewer than this fraction of guards from the
  492. * torrc, we are in an extremely restricted setting, and should warn.
  493. */
  494. STATIC double
  495. get_extreme_restriction_threshold(void)
  496. {
  497. int32_t pct = networkstatus_get_param(NULL,
  498. "guard-extreme-restriction-percent",
  499. DFLT_EXTREME_RESTRICTION_PERCENT,
  500. 1, INT32_MAX);
  501. return pct / 100.0;
  502. }
  503. /**@}*/
  504. /**
  505. * Given our options and our list of nodes, return the name of the
  506. * guard selection that we should use. Return NULL for "use the
  507. * same selection you were using before.
  508. */
  509. STATIC const char *
  510. choose_guard_selection(const or_options_t *options,
  511. const networkstatus_t *live_ns,
  512. const guard_selection_t *old_selection,
  513. guard_selection_type_t *type_out)
  514. {
  515. tor_assert(options);
  516. tor_assert(type_out);
  517. if (options->UseBridges) {
  518. *type_out = GS_TYPE_BRIDGE;
  519. return "bridges";
  520. }
  521. if (! live_ns) {
  522. /* without a networkstatus, we can't tell any more than that. */
  523. *type_out = GS_TYPE_NORMAL;
  524. return "default";
  525. }
  526. const smartlist_t *nodes = nodelist_get_list();
  527. int n_guards = 0, n_passing_filter = 0;
  528. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  529. if (node_is_possible_guard(node)) {
  530. ++n_guards;
  531. if (node_passes_guard_filter(options, node)) {
  532. ++n_passing_filter;
  533. }
  534. }
  535. } SMARTLIST_FOREACH_END(node);
  536. /* We use separate 'high' and 'low' thresholds here to prevent flapping
  537. * back and forth */
  538. const int meaningful_threshold_high =
  539. (int)(n_guards * get_meaningful_restriction_threshold() * 1.05);
  540. const int meaningful_threshold_mid =
  541. (int)(n_guards * get_meaningful_restriction_threshold());
  542. const int meaningful_threshold_low =
  543. (int)(n_guards * get_meaningful_restriction_threshold() * .95);
  544. const int extreme_threshold =
  545. (int)(n_guards * get_extreme_restriction_threshold());
  546. /*
  547. If we have no previous selection, then we're "restricted" iff we are
  548. below the meaningful restriction threshold. That's easy enough.
  549. But if we _do_ have a previous selection, we make it a little
  550. "sticky": we only move from "restricted" to "default" when we find
  551. that we're above the threshold plus 5%, and we only move from
  552. "default" to "restricted" when we're below the threshold minus 5%.
  553. That should prevent us from flapping back and forth if we happen to
  554. be hovering very close to the default.
  555. The extreme threshold is for warning only.
  556. */
  557. static int have_warned_extreme_threshold = 0;
  558. if (n_guards &&
  559. n_passing_filter < extreme_threshold &&
  560. ! have_warned_extreme_threshold) {
  561. have_warned_extreme_threshold = 1;
  562. const double exclude_frac =
  563. (n_guards - n_passing_filter) / (double)n_guards;
  564. log_warn(LD_GUARD, "Your configuration excludes %d%% of all possible "
  565. "guards. That's likely to make you stand out from the "
  566. "rest of the world.", (int)(exclude_frac * 100));
  567. }
  568. /* Easy case: no previous selection. Just check if we are in restricted or
  569. normal guard selection. */
  570. if (old_selection == NULL) {
  571. if (n_passing_filter >= meaningful_threshold_mid) {
  572. *type_out = GS_TYPE_NORMAL;
  573. return "default";
  574. } else {
  575. *type_out = GS_TYPE_RESTRICTED;
  576. return "restricted";
  577. }
  578. }
  579. /* Trickier case: we do have a previous guard selection context. */
  580. tor_assert(old_selection);
  581. /* Use high and low thresholds to decide guard selection, and if we fall in
  582. the middle then keep the current guard selection context. */
  583. if (n_passing_filter >= meaningful_threshold_high) {
  584. *type_out = GS_TYPE_NORMAL;
  585. return "default";
  586. } else if (n_passing_filter < meaningful_threshold_low) {
  587. *type_out = GS_TYPE_RESTRICTED;
  588. return "restricted";
  589. } else {
  590. /* we are in the middle: maintain previous guard selection */
  591. *type_out = old_selection->type;
  592. return old_selection->name;
  593. }
  594. }
  595. /**
  596. * Check whether we should switch from our current guard selection to a
  597. * different one. If so, switch and return 1. Return 0 otherwise.
  598. *
  599. * On a 1 return, the caller should mark all currently live circuits unusable
  600. * for new streams, by calling circuit_mark_all_unused_circs() and
  601. * circuit_mark_all_dirty_circs_as_unusable().
  602. */
  603. int
  604. update_guard_selection_choice(const or_options_t *options)
  605. {
  606. if (!curr_guard_context) {
  607. create_initial_guard_context();
  608. return 1;
  609. }
  610. guard_selection_type_t type = GS_TYPE_INFER;
  611. const char *new_name = choose_guard_selection(
  612. options,
  613. networkstatus_get_live_consensus(approx_time()),
  614. curr_guard_context,
  615. &type);
  616. tor_assert(new_name);
  617. tor_assert(type != GS_TYPE_INFER);
  618. const char *cur_name = curr_guard_context->name;
  619. if (! strcmp(cur_name, new_name)) {
  620. log_debug(LD_GUARD,
  621. "Staying with guard context \"%s\" (no change)", new_name);
  622. return 0; // No change
  623. }
  624. log_notice(LD_GUARD, "Switching to guard context \"%s\" (was using \"%s\")",
  625. new_name, cur_name);
  626. guard_selection_t *new_guard_context;
  627. new_guard_context = get_guard_selection_by_name(new_name, type, 1);
  628. tor_assert(new_guard_context);
  629. tor_assert(new_guard_context != curr_guard_context);
  630. curr_guard_context = new_guard_context;
  631. return 1;
  632. }
  633. /**
  634. * Return true iff <b>node</b> has all the flags needed for us to consider it
  635. * a possible guard when sampling guards.
  636. */
  637. static int
  638. node_is_possible_guard(const node_t *node)
  639. {
  640. /* The "GUARDS" set is all nodes in the nodelist for which this predicate
  641. * holds. */
  642. tor_assert(node);
  643. return (node->is_possible_guard &&
  644. node->is_stable &&
  645. node->is_fast &&
  646. node->is_valid &&
  647. node_is_dir(node));
  648. }
  649. /**
  650. * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
  651. * NULL if we don't have one. */
  652. STATIC entry_guard_t *
  653. get_sampled_guard_with_id(guard_selection_t *gs,
  654. const uint8_t *rsa_id)
  655. {
  656. tor_assert(gs);
  657. tor_assert(rsa_id);
  658. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  659. if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN))
  660. return guard;
  661. } SMARTLIST_FOREACH_END(guard);
  662. return NULL;
  663. }
  664. /** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>,
  665. * return that guard. Otherwise return NULL. */
  666. static entry_guard_t *
  667. get_sampled_guard_for_bridge(guard_selection_t *gs,
  668. const bridge_info_t *bridge)
  669. {
  670. const uint8_t *id = bridge_get_rsa_id_digest(bridge);
  671. const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
  672. entry_guard_t *guard;
  673. if (id) {
  674. guard = get_sampled_guard_with_id(gs, id);
  675. if (guard)
  676. return guard;
  677. }
  678. if (BUG(!addrport))
  679. return NULL; // LCOV_EXCL_LINE
  680. guard = get_sampled_guard_by_bridge_addr(gs, addrport);
  681. if (! guard || (id && tor_memneq(id, guard->identity, DIGEST_LEN)))
  682. return NULL;
  683. else
  684. return guard;
  685. }
  686. /** If we know a bridge_info_t matching <b>guard</b>, return that
  687. * bridge. Otherwise return NULL. */
  688. static bridge_info_t *
  689. get_bridge_info_for_guard(const entry_guard_t *guard)
  690. {
  691. if (! tor_digest_is_zero(guard->identity)) {
  692. bridge_info_t *bridge = find_bridge_by_digest(guard->identity);
  693. if (bridge)
  694. return bridge;
  695. }
  696. if (BUG(guard->bridge_addr == NULL))
  697. return NULL;
  698. return get_configured_bridge_by_addr_port_digest(&guard->bridge_addr->addr,
  699. guard->bridge_addr->port,
  700. NULL);
  701. }
  702. /**
  703. * Return true iff we have a sampled guard with the RSA identity digest
  704. * <b>rsa_id</b>. */
  705. static inline int
  706. have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
  707. {
  708. return get_sampled_guard_with_id(gs, rsa_id) != NULL;
  709. }
  710. /**
  711. * Allocate a new entry_guard_t object for <b>node</b>, add it to the
  712. * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
  713. * not currently be a sampled guard in <b>gs</b>.
  714. */
  715. STATIC entry_guard_t *
  716. entry_guard_add_to_sample(guard_selection_t *gs,
  717. const node_t *node)
  718. {
  719. log_info(LD_GUARD, "Adding %s as to the entry guard sample set.",
  720. node_describe(node));
  721. return entry_guard_add_to_sample_impl(gs,
  722. (const uint8_t*)node->identity,
  723. node_get_nickname(node),
  724. NULL);
  725. }
  726. /**
  727. * Backend: adds a new sampled guard to <b>gs</b>, with given identity,
  728. * nickname, and ORPort. rsa_id_digest and bridge_addrport are optional, but
  729. * we need one of them. nickname is optional. The caller is responsible for
  730. * maintaining the size limit of the SAMPLED_GUARDS set.
  731. */
  732. static entry_guard_t *
  733. entry_guard_add_to_sample_impl(guard_selection_t *gs,
  734. const uint8_t *rsa_id_digest,
  735. const char *nickname,
  736. const tor_addr_port_t *bridge_addrport)
  737. {
  738. const int GUARD_LIFETIME = get_guard_lifetime();
  739. tor_assert(gs);
  740. // XXXX prop271 take ed25519 identity here too.
  741. /* make sure that the guard is not already sampled. */
  742. if (rsa_id_digest && BUG(have_sampled_guard_with_id(gs, rsa_id_digest)))
  743. return NULL; // LCOV_EXCL_LINE
  744. /* Make sure we can actually identify the guard. */
  745. if (BUG(!rsa_id_digest && !bridge_addrport))
  746. return NULL; // LCOV_EXCL_LINE
  747. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  748. /* persistent fields */
  749. guard->is_persistent = (rsa_id_digest != NULL);
  750. guard->selection_name = tor_strdup(gs->name);
  751. if (rsa_id_digest)
  752. memcpy(guard->identity, rsa_id_digest, DIGEST_LEN);
  753. if (nickname)
  754. strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  755. guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  756. tor_free(guard->sampled_by_version);
  757. guard->sampled_by_version = tor_strdup(VERSION);
  758. guard->currently_listed = 1;
  759. guard->confirmed_idx = -1;
  760. /* non-persistent fields */
  761. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  762. if (bridge_addrport)
  763. guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport));
  764. smartlist_add(gs->sampled_entry_guards, guard);
  765. guard->in_selection = gs;
  766. entry_guard_set_filtered_flags(get_options(), gs, guard);
  767. entry_guards_changed_for_guard_selection(gs);
  768. return guard;
  769. }
  770. /**
  771. * Add an entry guard to the "bridges" guard selection sample, with
  772. * information taken from <b>bridge</b>. Return that entry guard.
  773. */
  774. static entry_guard_t *
  775. entry_guard_add_bridge_to_sample(guard_selection_t *gs,
  776. const bridge_info_t *bridge)
  777. {
  778. const uint8_t *id_digest = bridge_get_rsa_id_digest(bridge);
  779. const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
  780. tor_assert(addrport);
  781. return entry_guard_add_to_sample_impl(gs, id_digest, NULL, addrport);
  782. }
  783. /**
  784. * Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>,
  785. * or NULL if none exists.
  786. */
  787. static entry_guard_t *
  788. get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
  789. const tor_addr_port_t *addrport)
  790. {
  791. if (! gs)
  792. return NULL;
  793. if (BUG(!addrport))
  794. return NULL;
  795. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, g) {
  796. if (g->bridge_addr && tor_addr_port_eq(addrport, g->bridge_addr))
  797. return g;
  798. } SMARTLIST_FOREACH_END(g);
  799. return NULL;
  800. }
  801. /** Update the guard subsystem's knowledge of the identity of the bridge
  802. * at <b>addrport</b>. Idempotent.
  803. */
  804. void
  805. entry_guard_learned_bridge_identity(const tor_addr_port_t *addrport,
  806. const uint8_t *rsa_id_digest)
  807. {
  808. guard_selection_t *gs = get_guard_selection_by_name("bridges",
  809. GS_TYPE_BRIDGE,
  810. 0);
  811. if (!gs)
  812. return;
  813. entry_guard_t *g = get_sampled_guard_by_bridge_addr(gs, addrport);
  814. if (!g)
  815. return;
  816. int make_persistent = 0;
  817. if (tor_digest_is_zero(g->identity)) {
  818. memcpy(g->identity, rsa_id_digest, DIGEST_LEN);
  819. make_persistent = 1;
  820. } else if (tor_memeq(g->identity, rsa_id_digest, DIGEST_LEN)) {
  821. /* Nothing to see here; we learned something we already knew. */
  822. if (BUG(! g->is_persistent))
  823. make_persistent = 1;
  824. } else {
  825. char old_id[HEX_DIGEST_LEN+1];
  826. base16_encode(old_id, sizeof(old_id), g->identity, sizeof(g->identity));
  827. log_warn(LD_BUG, "We 'learned' an identity %s for a bridge at %s:%d, but "
  828. "we already knew a different one (%s). Ignoring the new info as "
  829. "possibly bogus.",
  830. hex_str((const char *)rsa_id_digest, DIGEST_LEN),
  831. fmt_and_decorate_addr(&addrport->addr), addrport->port,
  832. old_id);
  833. return; // redundant, but let's be clear: we're not making this persistent.
  834. }
  835. if (make_persistent) {
  836. g->is_persistent = 1;
  837. entry_guards_changed_for_guard_selection(gs);
  838. }
  839. }
  840. /**
  841. * Return the number of sampled guards in <b>gs</b> that are "filtered"
  842. * (that is, we're willing to connect to them) and that are "usable"
  843. * (that is, either "reachable" or "maybe reachable").
  844. *
  845. * If a restriction is provided in <b>rst</b>, do not count any guards that
  846. * violate it.
  847. */
  848. STATIC int
  849. num_reachable_filtered_guards(guard_selection_t *gs,
  850. const entry_guard_restriction_t *rst)
  851. {
  852. int n_reachable_filtered_guards = 0;
  853. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  854. entry_guard_consider_retry(guard);
  855. if (! entry_guard_obeys_restriction(guard, rst))
  856. continue;
  857. if (guard->is_usable_filtered_guard)
  858. ++n_reachable_filtered_guards;
  859. } SMARTLIST_FOREACH_END(guard);
  860. return n_reachable_filtered_guards;
  861. }
  862. /** Return the actual maximum size for the sample in <b>gs</b>,
  863. * given that we know about <b>n_guards</b> total. */
  864. static int
  865. get_max_sample_size(guard_selection_t *gs,
  866. int n_guards)
  867. {
  868. const int using_bridges = (gs->type == GS_TYPE_BRIDGE);
  869. const int min_sample = get_min_filtered_sample_size();
  870. /* With bridges, max_sample is "all of them" */
  871. if (using_bridges)
  872. return n_guards;
  873. const int max_sample_by_pct = (int)(n_guards * get_max_sample_threshold());
  874. const int max_sample_absolute = get_max_sample_size_absolute();
  875. const int max_sample = MIN(max_sample_by_pct, max_sample_absolute);
  876. if (max_sample < min_sample)
  877. return min_sample;
  878. else
  879. return max_sample;
  880. }
  881. /**
  882. * Return a smartlist of the all the guards that are not currently
  883. * members of the sample (GUARDS - SAMPLED_GUARDS). The elements of
  884. * this list are node_t pointers in the non-bridge case, and
  885. * bridge_info_t pointers in the bridge case. Set *<b>n_guards_out/b>
  886. * to the number of guards that we found in GUARDS, including those
  887. * that were already sampled.
  888. */
  889. static smartlist_t *
  890. get_eligible_guards(const or_options_t *options,
  891. guard_selection_t *gs,
  892. int *n_guards_out)
  893. {
  894. /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
  895. smartlist_t *eligible_guards = smartlist_new();
  896. int n_guards = 0; // total size of "GUARDS"
  897. if (gs->type == GS_TYPE_BRIDGE) {
  898. const smartlist_t *bridges = bridge_list_get();
  899. SMARTLIST_FOREACH_BEGIN(bridges, bridge_info_t *, bridge) {
  900. ++n_guards;
  901. if (NULL != get_sampled_guard_for_bridge(gs, bridge)) {
  902. continue;
  903. }
  904. smartlist_add(eligible_guards, bridge);
  905. } SMARTLIST_FOREACH_END(bridge);
  906. } else {
  907. const smartlist_t *nodes = nodelist_get_list();
  908. const int n_sampled = smartlist_len(gs->sampled_entry_guards);
  909. /* Build a bloom filter of our current guards: let's keep this O(N). */
  910. digestset_t *sampled_guard_ids = digestset_new(n_sampled);
  911. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *,
  912. guard) {
  913. digestset_add(sampled_guard_ids, guard->identity);
  914. } SMARTLIST_FOREACH_END(guard);
  915. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  916. if (! node_is_possible_guard(node))
  917. continue;
  918. if (gs->type == GS_TYPE_RESTRICTED) {
  919. /* In restricted mode, we apply the filter BEFORE sampling, so
  920. * that we are sampling from the nodes that we might actually
  921. * select. If we sampled first, we might wind up with a sample
  922. * that didn't include any EntryNodes at all. */
  923. if (! node_passes_guard_filter(options, node))
  924. continue;
  925. }
  926. ++n_guards;
  927. if (digestset_contains(sampled_guard_ids, node->identity))
  928. continue;
  929. smartlist_add(eligible_guards, (node_t*)node);
  930. } SMARTLIST_FOREACH_END(node);
  931. /* Now we can free that bloom filter. */
  932. digestset_free(sampled_guard_ids);
  933. }
  934. *n_guards_out = n_guards;
  935. return eligible_guards;
  936. }
  937. /** Helper: given a smartlist of either bridge_info_t (if gs->type is
  938. * GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard,
  939. * add it as a guard, remove it from the list, and return a new
  940. * entry_guard_t. Return NULL on failure. */
  941. static entry_guard_t *
  942. select_and_add_guard_item_for_sample(guard_selection_t *gs,
  943. smartlist_t *eligible_guards)
  944. {
  945. entry_guard_t *added_guard;
  946. if (gs->type == GS_TYPE_BRIDGE) {
  947. const bridge_info_t *bridge = smartlist_choose(eligible_guards);
  948. if (BUG(!bridge))
  949. return NULL; // LCOV_EXCL_LINE
  950. smartlist_remove(eligible_guards, bridge);
  951. added_guard = entry_guard_add_bridge_to_sample(gs, bridge);
  952. } else {
  953. const node_t *node =
  954. node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD);
  955. if (BUG(!node))
  956. return NULL; // LCOV_EXCL_LINE
  957. smartlist_remove(eligible_guards, node);
  958. added_guard = entry_guard_add_to_sample(gs, node);
  959. }
  960. return added_guard;
  961. }
  962. /**
  963. * Add new guards to the sampled guards in <b>gs</b> until there are
  964. * enough usable filtered guards, but never grow the sample beyond its
  965. * maximum size. Return the last guard added, or NULL if none were
  966. * added.
  967. */
  968. STATIC entry_guard_t *
  969. entry_guards_expand_sample(guard_selection_t *gs)
  970. {
  971. tor_assert(gs);
  972. const or_options_t *options = get_options();
  973. int n_sampled = smartlist_len(gs->sampled_entry_guards);
  974. entry_guard_t *added_guard = NULL;
  975. int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL);
  976. int n_guards = 0;
  977. smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards);
  978. const int max_sample = get_max_sample_size(gs, n_guards);
  979. const int min_filtered_sample = get_min_filtered_sample_size();
  980. log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
  981. "in the sample, and %d eligible guards to extend it with.",
  982. n_sampled, smartlist_len(eligible_guards));
  983. while (n_usable_filtered_guards < min_filtered_sample) {
  984. /* Has our sample grown too large to expand? */
  985. if (n_sampled >= max_sample) {
  986. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  987. "just hit the maximum sample threshold of %d",
  988. max_sample);
  989. goto done;
  990. }
  991. /* Did we run out of guards? */
  992. if (smartlist_len(eligible_guards) == 0) {
  993. /* LCOV_EXCL_START
  994. As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
  995. allow all guards to be sampled, this can't be reached.
  996. */
  997. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  998. "just ran out of eligible guards");
  999. goto done;
  1000. /* LCOV_EXCL_STOP */
  1001. }
  1002. /* Otherwise we can add at least one new guard. */
  1003. added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards);
  1004. if (!added_guard)
  1005. goto done; // LCOV_EXCL_LINE -- only fails on BUG.
  1006. ++n_sampled;
  1007. if (added_guard->is_usable_filtered_guard)
  1008. ++n_usable_filtered_guards;
  1009. }
  1010. done:
  1011. smartlist_free(eligible_guards);
  1012. return added_guard;
  1013. }
  1014. /**
  1015. * Helper: <b>guard</b> has just been removed from the sampled guards:
  1016. * also remove it from primary and confirmed. */
  1017. static void
  1018. remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs,
  1019. entry_guard_t *guard)
  1020. {
  1021. if (guard->is_primary) {
  1022. guard->is_primary = 0;
  1023. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  1024. } else {
  1025. if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
  1026. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  1027. }
  1028. }
  1029. if (guard->confirmed_idx >= 0) {
  1030. entry_guard_t *found_guard = NULL;
  1031. if (guard->confirmed_idx < smartlist_len(gs->confirmed_entry_guards))
  1032. found_guard = smartlist_get(gs->confirmed_entry_guards,
  1033. guard->confirmed_idx);
  1034. if (BUG(guard != found_guard)) {
  1035. // LCOV_EXCL_START
  1036. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  1037. // LCOV_EXCL_STOP
  1038. } else {
  1039. smartlist_del_keeporder(gs->confirmed_entry_guards,
  1040. guard->confirmed_idx);
  1041. }
  1042. guard->confirmed_idx = -1;
  1043. guard->confirmed_on_date = 0;
  1044. } else {
  1045. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
  1046. // LCOV_EXCL_START
  1047. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  1048. // LCOV_EXCL_STOP
  1049. }
  1050. }
  1051. }
  1052. /** Return true iff <b>guard</b> is currently "listed" -- that is, it
  1053. * appears in the consensus, or as a configured bridge (as
  1054. * appropriate) */
  1055. MOCK_IMPL(STATIC int,
  1056. entry_guard_is_listed,(guard_selection_t *gs, const entry_guard_t *guard))
  1057. {
  1058. if (gs->type == GS_TYPE_BRIDGE) {
  1059. return NULL != get_bridge_info_for_guard(guard);
  1060. } else {
  1061. const node_t *node = node_get_by_id(guard->identity);
  1062. return node && node_is_possible_guard(node);
  1063. }
  1064. }
  1065. /**
  1066. * Update the status of all sampled guards based on the arrival of a
  1067. * new consensus networkstatus document. This will include marking
  1068. * some guards as listed or unlisted, and removing expired guards. */
  1069. STATIC void
  1070. sampled_guards_update_from_consensus(guard_selection_t *gs)
  1071. {
  1072. tor_assert(gs);
  1073. const int REMOVE_UNLISTED_GUARDS_AFTER =
  1074. (get_remove_unlisted_guards_after_days() * 86400);
  1075. const int unlisted_since_slop = REMOVE_UNLISTED_GUARDS_AFTER / 5;
  1076. // It's important to use only a live consensus here; we don't want to
  1077. // make changes based on anything expired or old.
  1078. if (gs->type != GS_TYPE_BRIDGE) {
  1079. networkstatus_t *ns = networkstatus_get_live_consensus(approx_time());
  1080. if (! ns) {
  1081. log_info(LD_GUARD, "No live consensus; can't update "
  1082. "sampled entry guards.");
  1083. return;
  1084. } else {
  1085. log_info(LD_GUARD, "Updating sampled guard status based on received "
  1086. "consensus.");
  1087. }
  1088. }
  1089. int n_changes = 0;
  1090. /* First: Update listed/unlisted. */
  1091. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1092. /* XXXX prop271 check ed ID too */
  1093. const int is_listed = entry_guard_is_listed(gs, guard);
  1094. if (is_listed && ! guard->currently_listed) {
  1095. ++n_changes;
  1096. guard->currently_listed = 1;
  1097. guard->unlisted_since_date = 0;
  1098. log_info(LD_GUARD, "Sampled guard %s is now listed again.",
  1099. entry_guard_describe(guard));
  1100. } else if (!is_listed && guard->currently_listed) {
  1101. ++n_changes;
  1102. guard->currently_listed = 0;
  1103. guard->unlisted_since_date = randomize_time(approx_time(),
  1104. unlisted_since_slop);
  1105. log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
  1106. entry_guard_describe(guard));
  1107. } else if (is_listed && guard->currently_listed) {
  1108. log_debug(LD_GUARD, "Sampled guard %s is still listed.",
  1109. entry_guard_describe(guard));
  1110. } else {
  1111. tor_assert(! is_listed && ! guard->currently_listed);
  1112. log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
  1113. entry_guard_describe(guard));
  1114. }
  1115. /* Clean up unlisted_since_date, just in case. */
  1116. if (guard->currently_listed && guard->unlisted_since_date) {
  1117. ++n_changes;
  1118. guard->unlisted_since_date = 0;
  1119. log_warn(LD_BUG, "Sampled guard %s was listed, but with "
  1120. "unlisted_since_date set. Fixing.",
  1121. entry_guard_describe(guard));
  1122. } else if (!guard->currently_listed && ! guard->unlisted_since_date) {
  1123. ++n_changes;
  1124. guard->unlisted_since_date = randomize_time(approx_time(),
  1125. unlisted_since_slop);
  1126. log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
  1127. "unlisted_since_date unset. Fixing.",
  1128. entry_guard_describe(guard));
  1129. }
  1130. } SMARTLIST_FOREACH_END(guard);
  1131. const time_t remove_if_unlisted_since =
  1132. approx_time() - REMOVE_UNLISTED_GUARDS_AFTER;
  1133. const time_t maybe_remove_if_sampled_before =
  1134. approx_time() - get_guard_lifetime();
  1135. const time_t remove_if_confirmed_before =
  1136. approx_time() - get_guard_confirmed_min_lifetime();
  1137. /* Then: remove the ones that have been junk for too long */
  1138. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1139. int rmv = 0;
  1140. if (guard->currently_listed == 0 &&
  1141. guard->unlisted_since_date < remove_if_unlisted_since) {
  1142. /*
  1143. "We have a live consensus, and {IS_LISTED} is false, and
  1144. {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}
  1145. days in the past."
  1146. */
  1147. log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
  1148. "for over %d days", entry_guard_describe(guard),
  1149. get_remove_unlisted_guards_after_days());
  1150. rmv = 1;
  1151. } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
  1152. /* We have a live consensus, and {ADDED_ON_DATE} is over
  1153. {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
  1154. "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
  1155. */
  1156. if (guard->confirmed_on_date == 0) {
  1157. rmv = 1;
  1158. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  1159. "over %d days ago, but never confirmed.",
  1160. entry_guard_describe(guard),
  1161. get_guard_lifetime() / 86400);
  1162. } else if (guard->confirmed_on_date < remove_if_confirmed_before) {
  1163. rmv = 1;
  1164. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  1165. "over %d days ago, and confirmed over %d days ago.",
  1166. entry_guard_describe(guard),
  1167. get_guard_lifetime() / 86400,
  1168. get_guard_confirmed_min_lifetime() / 86400);
  1169. }
  1170. }
  1171. if (rmv) {
  1172. ++n_changes;
  1173. SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard);
  1174. remove_guard_from_confirmed_and_primary_lists(gs, guard);
  1175. entry_guard_free(guard);
  1176. }
  1177. } SMARTLIST_FOREACH_END(guard);
  1178. if (n_changes) {
  1179. gs->primary_guards_up_to_date = 0;
  1180. entry_guards_update_filtered_sets(gs);
  1181. /* We don't need to rebuild the confirmed list right here -- we may have
  1182. * removed confirmed guards above, but we can't have added any new
  1183. * confirmed guards.
  1184. */
  1185. entry_guards_changed_for_guard_selection(gs);
  1186. }
  1187. }
  1188. /**
  1189. * Return true iff <b>node</b> is a Tor relay that we are configured to
  1190. * be able to connect to. */
  1191. static int
  1192. node_passes_guard_filter(const or_options_t *options,
  1193. const node_t *node)
  1194. {
  1195. /* NOTE: Make sure that this function stays in sync with
  1196. * options_transition_affects_entry_guards */
  1197. if (routerset_contains_node(options->ExcludeNodes, node))
  1198. return 0;
  1199. if (options->EntryNodes &&
  1200. !routerset_contains_node(options->EntryNodes, node))
  1201. return 0;
  1202. if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
  1203. return 0;
  1204. if (node_is_a_configured_bridge(node))
  1205. return 0;
  1206. return 1;
  1207. }
  1208. /** Helper: Return true iff <b>bridge</b> passes our configuration
  1209. * filter-- if it is a relay that we are configured to be able to
  1210. * connect to. */
  1211. static int
  1212. bridge_passes_guard_filter(const or_options_t *options,
  1213. const bridge_info_t *bridge)
  1214. {
  1215. tor_assert(bridge);
  1216. if (!bridge)
  1217. return 0;
  1218. if (routerset_contains_bridge(options->ExcludeNodes, bridge))
  1219. return 0;
  1220. /* Ignore entrynodes */
  1221. const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
  1222. if (!fascist_firewall_allows_address_addr(&addrport->addr,
  1223. addrport->port,
  1224. FIREWALL_OR_CONNECTION,
  1225. 0, 0))
  1226. return 0;
  1227. return 1;
  1228. }
  1229. /**
  1230. * Return true iff <b>guard</b> is a Tor relay that we are configured to
  1231. * be able to connect to, and we haven't disabled it for omission from
  1232. * the consensus or path bias issues. */
  1233. static int
  1234. entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
  1235. entry_guard_t *guard)
  1236. {
  1237. if (guard->currently_listed == 0)
  1238. return 0;
  1239. if (guard->pb.path_bias_disabled)
  1240. return 0;
  1241. if (gs->type == GS_TYPE_BRIDGE) {
  1242. const bridge_info_t *bridge = get_bridge_info_for_guard(guard);
  1243. if (bridge == NULL)
  1244. return 0;
  1245. return bridge_passes_guard_filter(options, bridge);
  1246. } else {
  1247. const node_t *node = node_get_by_id(guard->identity);
  1248. if (node == NULL) {
  1249. // This can happen when currently_listed is true, and we're not updating
  1250. // it because we don't have a live consensus.
  1251. return 0;
  1252. }
  1253. return node_passes_guard_filter(options, node);
  1254. }
  1255. }
  1256. /**
  1257. * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
  1258. * (If <b>rst</b> is NULL, there are no restrictions.)
  1259. */
  1260. static int
  1261. entry_guard_obeys_restriction(const entry_guard_t *guard,
  1262. const entry_guard_restriction_t *rst)
  1263. {
  1264. tor_assert(guard);
  1265. if (! rst)
  1266. return 1; // No restriction? No problem.
  1267. // Only one kind of restriction exists right now
  1268. return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
  1269. }
  1270. /**
  1271. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  1272. * flags on <b>guard</b>. */
  1273. void
  1274. entry_guard_set_filtered_flags(const or_options_t *options,
  1275. guard_selection_t *gs,
  1276. entry_guard_t *guard)
  1277. {
  1278. unsigned was_filtered = guard->is_filtered_guard;
  1279. guard->is_filtered_guard = 0;
  1280. guard->is_usable_filtered_guard = 0;
  1281. if (entry_guard_passes_filter(options, gs, guard)) {
  1282. guard->is_filtered_guard = 1;
  1283. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1284. guard->is_usable_filtered_guard = 1;
  1285. entry_guard_consider_retry(guard);
  1286. }
  1287. log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
  1288. "reachable_filtered=%d.", entry_guard_describe(guard),
  1289. guard->is_filtered_guard, guard->is_usable_filtered_guard);
  1290. if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
  1291. /* This guard might now be primary or nonprimary. */
  1292. gs->primary_guards_up_to_date = 0;
  1293. }
  1294. }
  1295. /**
  1296. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  1297. * flag on every guard in <b>gs</b>. */
  1298. STATIC void
  1299. entry_guards_update_filtered_sets(guard_selection_t *gs)
  1300. {
  1301. const or_options_t *options = get_options();
  1302. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1303. entry_guard_set_filtered_flags(options, gs, guard);
  1304. } SMARTLIST_FOREACH_END(guard);
  1305. }
  1306. /**
  1307. * Return a random guard from the reachable filtered sample guards
  1308. * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
  1309. * Return NULL if no such guard can be found.
  1310. *
  1311. * Make sure that the sample is big enough, and that all the filter flags
  1312. * are set correctly, before calling this function.
  1313. *
  1314. * If a restriction is provided in <b>rst</b>, do not return any guards that
  1315. * violate it.
  1316. **/
  1317. STATIC entry_guard_t *
  1318. sample_reachable_filtered_entry_guards(guard_selection_t *gs,
  1319. const entry_guard_restriction_t *rst,
  1320. unsigned flags)
  1321. {
  1322. tor_assert(gs);
  1323. entry_guard_t *result = NULL;
  1324. const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
  1325. const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
  1326. const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
  1327. const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
  1328. const unsigned need_descriptor = flags & SAMPLE_EXCLUDE_NO_DESCRIPTOR;
  1329. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1330. entry_guard_consider_retry(guard);
  1331. } SMARTLIST_FOREACH_END(guard);
  1332. const int n_reachable_filtered = num_reachable_filtered_guards(gs, rst);
  1333. log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
  1334. "in the USABLE_FILTERED set.", n_reachable_filtered);
  1335. const int min_filtered_sample = get_min_filtered_sample_size();
  1336. if (n_reachable_filtered < min_filtered_sample) {
  1337. log_info(LD_GUARD, " (That isn't enough. Trying to expand the sample.)");
  1338. entry_guards_expand_sample(gs);
  1339. }
  1340. if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
  1341. entry_guards_update_primary(gs);
  1342. /* Build the set of reachable filtered guards. */
  1343. smartlist_t *reachable_filtered_sample = smartlist_new();
  1344. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1345. entry_guard_consider_retry(guard);// redundant, but cheap.
  1346. if (! entry_guard_obeys_restriction(guard, rst))
  1347. continue;
  1348. if (! guard->is_usable_filtered_guard)
  1349. continue;
  1350. if (exclude_confirmed && guard->confirmed_idx >= 0)
  1351. continue;
  1352. if (exclude_primary && guard->is_primary)
  1353. continue;
  1354. if (exclude_pending && guard->is_pending)
  1355. continue;
  1356. if (need_descriptor && !guard_has_descriptor(guard))
  1357. continue;
  1358. smartlist_add(reachable_filtered_sample, guard);
  1359. } SMARTLIST_FOREACH_END(guard);
  1360. log_info(LD_GUARD, " (After filters [%x], we have %d guards to consider.)",
  1361. flags, smartlist_len(reachable_filtered_sample));
  1362. if (smartlist_len(reachable_filtered_sample)) {
  1363. result = smartlist_choose(reachable_filtered_sample);
  1364. log_info(LD_GUARD, " (Selected %s.)",
  1365. result ? entry_guard_describe(result) : "<null>");
  1366. }
  1367. smartlist_free(reachable_filtered_sample);
  1368. return result;
  1369. }
  1370. /**
  1371. * Helper: compare two entry_guard_t by their confirmed_idx values.
  1372. * Used to sort the confirmed list.
  1373. */
  1374. static int
  1375. compare_guards_by_confirmed_idx(const void **a_, const void **b_)
  1376. {
  1377. const entry_guard_t *a = *a_, *b = *b_;
  1378. if (a->confirmed_idx < b->confirmed_idx)
  1379. return -1;
  1380. else if (a->confirmed_idx > b->confirmed_idx)
  1381. return 1;
  1382. else
  1383. return 0;
  1384. }
  1385. /**
  1386. * Find the confirmed guards from among the sampled guards in <b>gs</b>,
  1387. * and put them in confirmed_entry_guards in the correct
  1388. * order. Recalculate their indices.
  1389. */
  1390. STATIC void
  1391. entry_guards_update_confirmed(guard_selection_t *gs)
  1392. {
  1393. smartlist_clear(gs->confirmed_entry_guards);
  1394. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1395. if (guard->confirmed_idx >= 0)
  1396. smartlist_add(gs->confirmed_entry_guards, guard);
  1397. } SMARTLIST_FOREACH_END(guard);
  1398. smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
  1399. int any_changed = 0;
  1400. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1401. if (guard->confirmed_idx != guard_sl_idx) {
  1402. any_changed = 1;
  1403. guard->confirmed_idx = guard_sl_idx;
  1404. }
  1405. } SMARTLIST_FOREACH_END(guard);
  1406. gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
  1407. if (any_changed) {
  1408. entry_guards_changed_for_guard_selection(gs);
  1409. }
  1410. }
  1411. /**
  1412. * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
  1413. * connected to, and intend to use again.
  1414. */
  1415. STATIC void
  1416. make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
  1417. {
  1418. if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
  1419. return; // LCOV_EXCL_LINE
  1420. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
  1421. return; // LCOV_EXCL_LINE
  1422. const int GUARD_LIFETIME = get_guard_lifetime();
  1423. guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  1424. log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
  1425. entry_guard_describe(guard),
  1426. gs->next_confirmed_idx);
  1427. guard->confirmed_idx = gs->next_confirmed_idx++;
  1428. smartlist_add(gs->confirmed_entry_guards, guard);
  1429. // This confirmed guard might kick something else out of the primary
  1430. // guards.
  1431. gs->primary_guards_up_to_date = 0;
  1432. entry_guards_changed_for_guard_selection(gs);
  1433. }
  1434. /**
  1435. * Recalculate the list of primary guards (the ones we'd prefer to use) from
  1436. * the filtered sample and the confirmed list.
  1437. */
  1438. STATIC void
  1439. entry_guards_update_primary(guard_selection_t *gs)
  1440. {
  1441. tor_assert(gs);
  1442. // prevent recursion. Recursion is potentially very bad here.
  1443. static int running = 0;
  1444. tor_assert(!running);
  1445. running = 1;
  1446. const int N_PRIMARY_GUARDS = get_n_primary_guards();
  1447. smartlist_t *new_primary_guards = smartlist_new();
  1448. smartlist_t *old_primary_guards = smartlist_new();
  1449. smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
  1450. /* Set this flag now, to prevent the calls below from recursing. */
  1451. gs->primary_guards_up_to_date = 1;
  1452. /* First, can we fill it up with confirmed guards? */
  1453. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1454. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  1455. break;
  1456. if (! guard->is_filtered_guard)
  1457. continue;
  1458. guard->is_primary = 1;
  1459. smartlist_add(new_primary_guards, guard);
  1460. } SMARTLIST_FOREACH_END(guard);
  1461. /* Can we keep any older primary guards? First remove all the ones
  1462. * that we already kept. */
  1463. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1464. if (smartlist_contains(new_primary_guards, guard)) {
  1465. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  1466. }
  1467. } SMARTLIST_FOREACH_END(guard);
  1468. /* Now add any that are still good. */
  1469. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1470. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  1471. break;
  1472. if (! guard->is_filtered_guard)
  1473. continue;
  1474. guard->is_primary = 1;
  1475. smartlist_add(new_primary_guards, guard);
  1476. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  1477. } SMARTLIST_FOREACH_END(guard);
  1478. /* Mark the remaining previous primary guards as non-primary */
  1479. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1480. guard->is_primary = 0;
  1481. } SMARTLIST_FOREACH_END(guard);
  1482. /* Finally, fill out the list with sampled guards. */
  1483. while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
  1484. entry_guard_t *guard = sample_reachable_filtered_entry_guards(gs, NULL,
  1485. SAMPLE_EXCLUDE_CONFIRMED|
  1486. SAMPLE_EXCLUDE_PRIMARY|
  1487. SAMPLE_NO_UPDATE_PRIMARY);
  1488. if (!guard)
  1489. break;
  1490. guard->is_primary = 1;
  1491. smartlist_add(new_primary_guards, guard);
  1492. }
  1493. #if 1
  1494. /* Debugging. */
  1495. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
  1496. tor_assert_nonfatal(
  1497. bool_eq(guard->is_primary,
  1498. smartlist_contains(new_primary_guards, guard)));
  1499. });
  1500. #endif
  1501. int any_change = 0;
  1502. if (smartlist_len(gs->primary_entry_guards) !=
  1503. smartlist_len(new_primary_guards)) {
  1504. any_change = 1;
  1505. } else {
  1506. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, g) {
  1507. if (g != smartlist_get(new_primary_guards, g_sl_idx)) {
  1508. any_change = 1;
  1509. }
  1510. } SMARTLIST_FOREACH_END(g);
  1511. }
  1512. if (any_change) {
  1513. log_info(LD_GUARD, "Primary entry guards have changed. "
  1514. "New primary guard list is: ");
  1515. int n = smartlist_len(new_primary_guards);
  1516. SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
  1517. log_info(LD_GUARD, " %d/%d: %s%s%s",
  1518. g_sl_idx+1, n, entry_guard_describe(g),
  1519. g->confirmed_idx >= 0 ? " (confirmed)" : "",
  1520. g->is_filtered_guard ? "" : " (excluded by filter)");
  1521. } SMARTLIST_FOREACH_END(g);
  1522. }
  1523. smartlist_free(old_primary_guards);
  1524. smartlist_free(gs->primary_entry_guards);
  1525. gs->primary_entry_guards = new_primary_guards;
  1526. gs->primary_guards_up_to_date = 1;
  1527. running = 0;
  1528. }
  1529. /**
  1530. * Return the number of seconds after the last attempt at which we should
  1531. * retry a guard that has been failing since <b>failing_since</b>.
  1532. */
  1533. static int
  1534. get_retry_schedule(time_t failing_since, time_t now,
  1535. int is_primary)
  1536. {
  1537. const unsigned SIX_HOURS = 6 * 3600;
  1538. const unsigned FOUR_DAYS = 4 * 86400;
  1539. const unsigned SEVEN_DAYS = 7 * 86400;
  1540. time_t tdiff;
  1541. if (now > failing_since) {
  1542. tdiff = now - failing_since;
  1543. } else {
  1544. tdiff = 0;
  1545. }
  1546. const struct {
  1547. time_t maximum; int primary_delay; int nonprimary_delay;
  1548. } delays[] = {
  1549. { SIX_HOURS, 10*60, 1*60*60 },
  1550. { FOUR_DAYS, 90*60, 4*60*60 },
  1551. { SEVEN_DAYS, 4*60*60, 18*60*60 },
  1552. { TIME_MAX, 9*60*60, 36*60*60 }
  1553. };
  1554. unsigned i;
  1555. for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
  1556. if (tdiff <= delays[i].maximum) {
  1557. return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
  1558. }
  1559. }
  1560. /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
  1561. tor_assert_nonfatal_unreached();
  1562. return 36*60*60;
  1563. /* LCOV_EXCL_STOP */
  1564. }
  1565. /**
  1566. * If <b>guard</b> is unreachable, consider whether enough time has passed
  1567. * to consider it maybe-reachable again.
  1568. */
  1569. STATIC void
  1570. entry_guard_consider_retry(entry_guard_t *guard)
  1571. {
  1572. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1573. return; /* No retry needed. */
  1574. const time_t now = approx_time();
  1575. const int delay =
  1576. get_retry_schedule(guard->failing_since, now, guard->is_primary);
  1577. const time_t last_attempt = guard->last_tried_to_connect;
  1578. if (BUG(last_attempt == 0) ||
  1579. now >= last_attempt + delay) {
  1580. /* We should mark this retriable. */
  1581. char tbuf[ISO_TIME_LEN+1];
  1582. format_local_iso_time(tbuf, last_attempt);
  1583. log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
  1584. "haven't tried to use it since %s.",
  1585. guard->is_primary?"primary ":"",
  1586. guard->confirmed_idx>=0?"confirmed ":"",
  1587. entry_guard_describe(guard),
  1588. tbuf);
  1589. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  1590. if (guard->is_filtered_guard)
  1591. guard->is_usable_filtered_guard = 1;
  1592. }
  1593. }
  1594. /** Tell the entry guards subsystem that we have confirmed that as of
  1595. * just now, we're on the internet. */
  1596. void
  1597. entry_guards_note_internet_connectivity(guard_selection_t *gs)
  1598. {
  1599. gs->last_time_on_internet = approx_time();
  1600. }
  1601. /**
  1602. * Get a guard for use with a circuit. Prefer to pick a running primary
  1603. * guard; then a non-pending running filtered confirmed guard; then a
  1604. * non-pending runnable filtered guard. Update the
  1605. * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
  1606. * guard as appropriate. Set <b>state_out</b> to the new guard-state
  1607. * of the circuit.
  1608. */
  1609. STATIC entry_guard_t *
  1610. select_entry_guard_for_circuit(guard_selection_t *gs,
  1611. guard_usage_t usage,
  1612. const entry_guard_restriction_t *rst,
  1613. unsigned *state_out)
  1614. {
  1615. const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
  1616. tor_assert(gs);
  1617. tor_assert(state_out);
  1618. if (!gs->primary_guards_up_to_date)
  1619. entry_guards_update_primary(gs);
  1620. int num_entry_guards = get_n_primary_guards_to_use(usage);
  1621. smartlist_t *usable_primary_guards = smartlist_new();
  1622. /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
  1623. <maybe> or <yes>, return the first such guard." */
  1624. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1625. entry_guard_consider_retry(guard);
  1626. if (! entry_guard_obeys_restriction(guard, rst))
  1627. continue;
  1628. if (guard->is_reachable != GUARD_REACHABLE_NO) {
  1629. if (need_descriptor && BUG(!guard_has_descriptor(guard))) {
  1630. continue;
  1631. }
  1632. *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
  1633. guard->last_tried_to_connect = approx_time();
  1634. smartlist_add(usable_primary_guards, guard);
  1635. if (smartlist_len(usable_primary_guards) >= num_entry_guards)
  1636. break;
  1637. }
  1638. } SMARTLIST_FOREACH_END(guard);
  1639. if (smartlist_len(usable_primary_guards)) {
  1640. entry_guard_t *guard = smartlist_choose(usable_primary_guards);
  1641. smartlist_free(usable_primary_guards);
  1642. log_info(LD_GUARD, "Selected primary guard %s for circuit.",
  1643. entry_guard_describe(guard));
  1644. return guard;
  1645. }
  1646. smartlist_free(usable_primary_guards);
  1647. /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
  1648. and {USABLE_FILTERED_GUARDS} is nonempty, return the first
  1649. entry in that intersection that has {is_pending} set to
  1650. false." */
  1651. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1652. if (guard->is_primary)
  1653. continue; /* we already considered this one. */
  1654. if (! entry_guard_obeys_restriction(guard, rst))
  1655. continue;
  1656. entry_guard_consider_retry(guard);
  1657. if (guard->is_usable_filtered_guard && ! guard->is_pending) {
  1658. if (need_descriptor && !guard_has_descriptor(guard))
  1659. continue; /* not a bug */
  1660. guard->is_pending = 1;
  1661. guard->last_tried_to_connect = approx_time();
  1662. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1663. log_info(LD_GUARD, "No primary guards available. Selected confirmed "
  1664. "guard %s for circuit. Will try other guards before using "
  1665. "this circuit.",
  1666. entry_guard_describe(guard));
  1667. return guard;
  1668. }
  1669. } SMARTLIST_FOREACH_END(guard);
  1670. /* "Otherwise, if there is no such entry, select a member at
  1671. random from {USABLE_FILTERED_GUARDS}." */
  1672. {
  1673. entry_guard_t *guard;
  1674. unsigned flags = 0;
  1675. if (need_descriptor)
  1676. flags |= SAMPLE_EXCLUDE_NO_DESCRIPTOR;
  1677. guard = sample_reachable_filtered_entry_guards(gs,
  1678. rst,
  1679. SAMPLE_EXCLUDE_CONFIRMED |
  1680. SAMPLE_EXCLUDE_PRIMARY |
  1681. SAMPLE_EXCLUDE_PENDING |
  1682. flags);
  1683. if (guard == NULL) {
  1684. log_info(LD_GUARD, "Absolutely no sampled guards were available.");
  1685. return NULL;
  1686. }
  1687. guard->is_pending = 1;
  1688. guard->last_tried_to_connect = approx_time();
  1689. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1690. log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
  1691. "random guard %s for circuit. Will try other guards before "
  1692. "using this circuit.",
  1693. entry_guard_describe(guard));
  1694. return guard;
  1695. }
  1696. }
  1697. /**
  1698. * Note that we failed to connect to or build circuits through <b>guard</b>.
  1699. * Use with a guard returned by select_entry_guard_for_circuit().
  1700. */
  1701. STATIC void
  1702. entry_guards_note_guard_failure(guard_selection_t *gs,
  1703. entry_guard_t *guard)
  1704. {
  1705. tor_assert(gs);
  1706. guard->is_reachable = GUARD_REACHABLE_NO;
  1707. guard->is_usable_filtered_guard = 0;
  1708. guard->is_pending = 0;
  1709. if (guard->failing_since == 0)
  1710. guard->failing_since = approx_time();
  1711. log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
  1712. guard->is_primary?"primary ":"",
  1713. guard->confirmed_idx>=0?"confirmed ":"",
  1714. entry_guard_describe(guard));
  1715. }
  1716. /**
  1717. * Called when the network comes up after having seemed to be down for
  1718. * a while: Mark the primary guards as maybe-reachable so that we'll
  1719. * try them again.
  1720. */
  1721. STATIC void
  1722. mark_primary_guards_maybe_reachable(guard_selection_t *gs)
  1723. {
  1724. if (!gs->primary_guards_up_to_date)
  1725. entry_guards_update_primary(gs);
  1726. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1727. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1728. continue;
  1729. /* Note that we do not clear failing_since: this guard is now only
  1730. * _maybe-reachable_. */
  1731. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  1732. if (guard->is_filtered_guard)
  1733. guard->is_usable_filtered_guard = 1;
  1734. } SMARTLIST_FOREACH_END(guard);
  1735. }
  1736. /**
  1737. * Note that we successfully connected to, and built a circuit through
  1738. * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
  1739. * return the new guard-state of the circuit.
  1740. *
  1741. * Be aware: the circuit is only usable when its guard-state becomes
  1742. * GUARD_CIRC_STATE_COMPLETE.
  1743. **/
  1744. STATIC unsigned
  1745. entry_guards_note_guard_success(guard_selection_t *gs,
  1746. entry_guard_t *guard,
  1747. unsigned old_state)
  1748. {
  1749. tor_assert(gs);
  1750. /* Save this, since we're about to overwrite it. */
  1751. const time_t last_time_on_internet = gs->last_time_on_internet;
  1752. gs->last_time_on_internet = approx_time();
  1753. guard->is_reachable = GUARD_REACHABLE_YES;
  1754. guard->failing_since = 0;
  1755. guard->is_pending = 0;
  1756. if (guard->is_filtered_guard)
  1757. guard->is_usable_filtered_guard = 1;
  1758. if (guard->confirmed_idx < 0) {
  1759. make_guard_confirmed(gs, guard);
  1760. if (!gs->primary_guards_up_to_date)
  1761. entry_guards_update_primary(gs);
  1762. }
  1763. unsigned new_state;
  1764. switch (old_state) {
  1765. case GUARD_CIRC_STATE_COMPLETE:
  1766. case GUARD_CIRC_STATE_USABLE_ON_COMPLETION:
  1767. new_state = GUARD_CIRC_STATE_COMPLETE;
  1768. break;
  1769. default:
  1770. tor_assert_nonfatal_unreached();
  1771. /* Fall through. */
  1772. case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD:
  1773. if (guard->is_primary) {
  1774. /* XXXX prop271 -- I don't actually like this logic. It seems to make
  1775. * us a little more susceptible to evil-ISP attacks. The mitigations
  1776. * I'm thinking of, however, aren't local to this point, so I'll leave
  1777. * it alone. */
  1778. /* This guard may have become primary by virtue of being confirmed.
  1779. * If so, the circuit for it is now complete.
  1780. */
  1781. new_state = GUARD_CIRC_STATE_COMPLETE;
  1782. } else {
  1783. new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
  1784. }
  1785. break;
  1786. }
  1787. if (! guard->is_primary) {
  1788. if (last_time_on_internet + get_internet_likely_down_interval()
  1789. < approx_time()) {
  1790. mark_primary_guards_maybe_reachable(gs);
  1791. }
  1792. }
  1793. log_info(LD_GUARD, "Recorded success for %s%sguard %s",
  1794. guard->is_primary?"primary ":"",
  1795. guard->confirmed_idx>=0?"confirmed ":"",
  1796. entry_guard_describe(guard));
  1797. return new_state;
  1798. }
  1799. /**
  1800. * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
  1801. */
  1802. STATIC int
  1803. entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
  1804. {
  1805. tor_assert(a && b);
  1806. if (a == b)
  1807. return 0;
  1808. /* Confirmed is always better than unconfirmed; lower index better
  1809. than higher */
  1810. if (a->confirmed_idx < 0) {
  1811. if (b->confirmed_idx >= 0)
  1812. return 0;
  1813. } else {
  1814. if (b->confirmed_idx < 0)
  1815. return 1;
  1816. /* Lower confirmed_idx is better than higher. */
  1817. return (a->confirmed_idx < b->confirmed_idx);
  1818. }
  1819. /* If we reach this point, both are unconfirmed. If one is pending, it
  1820. * has higher priority. */
  1821. if (a->is_pending) {
  1822. if (! b->is_pending)
  1823. return 1;
  1824. /* Both are pending: earlier last_tried_connect wins. */
  1825. return a->last_tried_to_connect < b->last_tried_to_connect;
  1826. } else {
  1827. if (b->is_pending)
  1828. return 0;
  1829. /* Neither is pending: priorities are equal. */
  1830. return 0; // XXXX prop271 return a tristate instead?
  1831. }
  1832. }
  1833. /** Release all storage held in <b>restriction</b> */
  1834. static void
  1835. entry_guard_restriction_free(entry_guard_restriction_t *rst)
  1836. {
  1837. tor_free(rst);
  1838. }
  1839. /**
  1840. * Release all storage held in <b>state</b>.
  1841. */
  1842. void
  1843. circuit_guard_state_free(circuit_guard_state_t *state)
  1844. {
  1845. if (!state)
  1846. return;
  1847. entry_guard_restriction_free(state->restrictions);
  1848. entry_guard_handle_free(state->guard);
  1849. tor_free(state);
  1850. }
  1851. /**
  1852. * Pick a suitable entry guard for a circuit in, and place that guard
  1853. * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
  1854. * state object that will record whether the circuit is ready to be used
  1855. * or not. Return 0 on success; on failure, return -1.
  1856. *
  1857. * If a restriction is provided in <b>rst</b>, do not return any guards that
  1858. * violate it, and remember that restriction in <b>guard_state_out</b> for
  1859. * later use. (Takes ownership of the <b>rst</b> object.)
  1860. */
  1861. int
  1862. entry_guard_pick_for_circuit(guard_selection_t *gs,
  1863. guard_usage_t usage,
  1864. entry_guard_restriction_t *rst,
  1865. const node_t **chosen_node_out,
  1866. circuit_guard_state_t **guard_state_out)
  1867. {
  1868. tor_assert(gs);
  1869. tor_assert(chosen_node_out);
  1870. tor_assert(guard_state_out);
  1871. *chosen_node_out = NULL;
  1872. *guard_state_out = NULL;
  1873. unsigned state = 0;
  1874. entry_guard_t *guard =
  1875. select_entry_guard_for_circuit(gs, usage, rst, &state);
  1876. if (! guard)
  1877. goto fail;
  1878. if (BUG(state == 0))
  1879. goto fail;
  1880. const node_t *node = node_get_by_id(guard->identity);
  1881. // XXXX prop271 check Ed ID.
  1882. if (! node)
  1883. goto fail;
  1884. if (BUG(usage != GUARD_USAGE_DIRGUARD && !node_has_descriptor(node)))
  1885. goto fail;
  1886. *chosen_node_out = node;
  1887. *guard_state_out = tor_malloc_zero(sizeof(circuit_guard_state_t));
  1888. (*guard_state_out)->guard = entry_guard_handle_new(guard);
  1889. (*guard_state_out)->state = state;
  1890. (*guard_state_out)->state_set_at = approx_time();
  1891. (*guard_state_out)->restrictions = rst;
  1892. return 0;
  1893. fail:
  1894. entry_guard_restriction_free(rst);
  1895. return -1;
  1896. }
  1897. /**
  1898. * Called by the circuit building module when a circuit has succeeded: informs
  1899. * the guards code that the guard in *<b>guard_state_p</b> is working, and
  1900. * advances the state of the guard module. On a GUARD_USABLE_NEVER return
  1901. * value, the circuit is broken and should not be used. On a GUARD_USABLE_NOW
  1902. * return value, the circuit is ready to use. On a GUARD_MAYBE_USABLE_LATER
  1903. * return value, the circuit should not be used until we find out whether
  1904. * preferred guards will work for us.
  1905. */
  1906. guard_usable_t
  1907. entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
  1908. {
  1909. if (BUG(*guard_state_p == NULL))
  1910. return GUARD_USABLE_NEVER;
  1911. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1912. if (! guard || BUG(guard->in_selection == NULL))
  1913. return GUARD_USABLE_NEVER;
  1914. unsigned newstate =
  1915. entry_guards_note_guard_success(guard->in_selection, guard,
  1916. (*guard_state_p)->state);
  1917. (*guard_state_p)->state = newstate;
  1918. (*guard_state_p)->state_set_at = approx_time();
  1919. if (newstate == GUARD_CIRC_STATE_COMPLETE) {
  1920. return GUARD_USABLE_NOW;
  1921. } else {
  1922. return GUARD_MAYBE_USABLE_LATER;
  1923. }
  1924. }
  1925. /** Cancel the selection of *<b>guard_state_p</b> without declaring
  1926. * success or failure. It is safe to call this function if success or
  1927. * failure _has_ already been declared. */
  1928. void
  1929. entry_guard_cancel(circuit_guard_state_t **guard_state_p)
  1930. {
  1931. if (BUG(*guard_state_p == NULL))
  1932. return;
  1933. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1934. if (! guard)
  1935. return;
  1936. /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
  1937. * function will only get called in "bug" cases anyway. */
  1938. guard->is_pending = 0;
  1939. circuit_guard_state_free(*guard_state_p);
  1940. *guard_state_p = NULL;
  1941. }
  1942. /**
  1943. * Called by the circuit building module when a circuit has succeeded:
  1944. * informs the guards code that the guard in *<b>guard_state_p</b> is
  1945. * not working, and advances the state of the guard module.
  1946. */
  1947. void
  1948. entry_guard_failed(circuit_guard_state_t **guard_state_p)
  1949. {
  1950. if (BUG(*guard_state_p == NULL))
  1951. return;
  1952. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1953. if (! guard || BUG(guard->in_selection == NULL))
  1954. return;
  1955. entry_guards_note_guard_failure(guard->in_selection, guard);
  1956. (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
  1957. (*guard_state_p)->state_set_at = approx_time();
  1958. }
  1959. /**
  1960. * Run the entry_guard_failed() function on every circuit that is
  1961. * pending on <b>chan</b>.
  1962. */
  1963. void
  1964. entry_guard_chan_failed(channel_t *chan)
  1965. {
  1966. if (!chan)
  1967. return;
  1968. smartlist_t *pending = smartlist_new();
  1969. circuit_get_all_pending_on_channel(pending, chan);
  1970. SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
  1971. if (!CIRCUIT_IS_ORIGIN(circ))
  1972. continue;
  1973. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1974. entry_guard_failed(&origin_circ->guard_state);
  1975. } SMARTLIST_FOREACH_END(circ);
  1976. smartlist_free(pending);
  1977. }
  1978. /**
  1979. * Return true iff every primary guard in <b>gs</b> is believed to
  1980. * be unreachable.
  1981. */
  1982. STATIC int
  1983. entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
  1984. {
  1985. tor_assert(gs);
  1986. if (!gs->primary_guards_up_to_date)
  1987. entry_guards_update_primary(gs);
  1988. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1989. entry_guard_consider_retry(guard);
  1990. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1991. return 0;
  1992. } SMARTLIST_FOREACH_END(guard);
  1993. return 1;
  1994. }
  1995. /** Wrapper for entry_guard_has_higher_priority that compares the
  1996. * guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher
  1997. * priority than <b>b</b>.
  1998. *
  1999. * If a restriction is provided in <b>rst</b>, then do not consider
  2000. * <b>a</b> to have higher priority if it violates the restriction.
  2001. */
  2002. static int
  2003. circ_state_has_higher_priority(origin_circuit_t *a,
  2004. const entry_guard_restriction_t *rst,
  2005. origin_circuit_t *b)
  2006. {
  2007. circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
  2008. circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);
  2009. tor_assert(state_a);
  2010. tor_assert(state_b);
  2011. entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
  2012. entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);
  2013. if (! guard_a) {
  2014. /* Unknown guard -- never higher priority. */
  2015. return 0;
  2016. } else if (! guard_b) {
  2017. /* Known guard -- higher priority than any unknown guard. */
  2018. return 1;
  2019. } else if (! entry_guard_obeys_restriction(guard_a, rst)) {
  2020. /* Restriction violated; guard_a cannot have higher priority. */
  2021. return 0;
  2022. } else {
  2023. /* Both known -- compare.*/
  2024. return entry_guard_has_higher_priority(guard_a, guard_b);
  2025. }
  2026. }
  2027. /**
  2028. * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
  2029. * and see if any of them that were previously not ready to use for
  2030. * guard-related reasons are now ready to use. Place those circuits
  2031. * in <b>newly_complete_out</b>, and mark them COMPLETE.
  2032. *
  2033. * Return 1 if we upgraded any circuits, and 0 otherwise.
  2034. */
  2035. int
  2036. entry_guards_upgrade_waiting_circuits(guard_selection_t *gs,
  2037. const smartlist_t *all_circuits_in,
  2038. smartlist_t *newly_complete_out)
  2039. {
  2040. tor_assert(gs);
  2041. tor_assert(all_circuits_in);
  2042. tor_assert(newly_complete_out);
  2043. if (! entry_guards_all_primary_guards_are_down(gs)) {
  2044. /* We only upgrade a waiting circuit if the primary guards are all
  2045. * down. */
  2046. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  2047. "but not all primary guards were definitely down.");
  2048. return 0;
  2049. }
  2050. int n_waiting = 0;
  2051. int n_complete = 0;
  2052. int n_complete_blocking = 0;
  2053. origin_circuit_t *best_waiting_circuit = NULL;
  2054. smartlist_t *all_circuits = smartlist_new();
  2055. SMARTLIST_FOREACH_BEGIN(all_circuits_in, origin_circuit_t *, circ) {
  2056. // We filter out circuits that aren't ours, or which we can't
  2057. // reason about.
  2058. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2059. if (state == NULL)
  2060. continue;
  2061. entry_guard_t *guard = entry_guard_handle_get(state->guard);
  2062. if (!guard || guard->in_selection != gs)
  2063. continue;
  2064. smartlist_add(all_circuits, circ);
  2065. } SMARTLIST_FOREACH_END(circ);
  2066. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2067. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2068. if BUG((state == NULL))
  2069. continue;
  2070. if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
  2071. ++n_waiting;
  2072. if (! best_waiting_circuit ||
  2073. circ_state_has_higher_priority(circ, NULL, best_waiting_circuit)) {
  2074. best_waiting_circuit = circ;
  2075. }
  2076. }
  2077. } SMARTLIST_FOREACH_END(circ);
  2078. if (! best_waiting_circuit) {
  2079. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  2080. "but didn't find any.");
  2081. goto no_change;
  2082. }
  2083. /* We'll need to keep track of what restrictions were used when picking this
  2084. * circuit, so that we don't allow any circuit without those restrictions to
  2085. * block it. */
  2086. const entry_guard_restriction_t *rst_on_best_waiting =
  2087. origin_circuit_get_guard_state(best_waiting_circuit)->restrictions;
  2088. /* First look at the complete circuits: Do any block this circuit? */
  2089. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2090. /* "C2 "blocks" C1 if:
  2091. * C2 obeys all the restrictions that C1 had to obey, AND
  2092. * C2 has higher priority than C1, AND
  2093. * Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
  2094. or C2 has been <usable_if_no_better_guard> for no more than
  2095. {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
  2096. */
  2097. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2098. if BUG((state == NULL))
  2099. continue;
  2100. if (state->state != GUARD_CIRC_STATE_COMPLETE)
  2101. continue;
  2102. ++n_complete;
  2103. if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
  2104. best_waiting_circuit))
  2105. ++n_complete_blocking;
  2106. } SMARTLIST_FOREACH_END(circ);
  2107. if (n_complete_blocking) {
  2108. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  2109. "%d complete and %d guard-stalled. At least one complete "
  2110. "circuit had higher priority, so not upgrading.",
  2111. n_complete, n_waiting);
  2112. goto no_change;
  2113. }
  2114. /* " * If any circuit C1 is <waiting_for_better_guard>, AND:
  2115. * All primary guards have reachable status of <no>.
  2116. * There is no circuit C2 that "blocks" C1.
  2117. Then, upgrade C1 to <complete>.""
  2118. */
  2119. int n_blockers_found = 0;
  2120. const time_t state_set_at_cutoff =
  2121. approx_time() - get_nonprimary_guard_connect_timeout();
  2122. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2123. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2124. if (BUG(state == NULL))
  2125. continue;
  2126. if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
  2127. continue;
  2128. if (state->state_set_at <= state_set_at_cutoff)
  2129. continue;
  2130. if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
  2131. best_waiting_circuit))
  2132. ++n_blockers_found;
  2133. } SMARTLIST_FOREACH_END(circ);
  2134. if (n_blockers_found) {
  2135. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  2136. "%d guard-stalled, but %d pending circuit(s) had higher "
  2137. "guard priority, so not upgrading.",
  2138. n_waiting, n_blockers_found);
  2139. goto no_change;
  2140. }
  2141. /* Okay. We have a best waiting circuit, and we aren't waiting for
  2142. anything better. Add all circuits with that priority to the
  2143. list, and call them COMPLETE. */
  2144. int n_succeeded = 0;
  2145. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2146. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2147. if (BUG(state == NULL))
  2148. continue;
  2149. if (circ != best_waiting_circuit && rst_on_best_waiting) {
  2150. /* Can't upgrade other circ with same priority as best; might
  2151. be blocked. */
  2152. continue;
  2153. }
  2154. if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
  2155. continue;
  2156. if (circ_state_has_higher_priority(best_waiting_circuit, NULL, circ))
  2157. continue;
  2158. state->state = GUARD_CIRC_STATE_COMPLETE;
  2159. state->state_set_at = approx_time();
  2160. smartlist_add(newly_complete_out, circ);
  2161. ++n_succeeded;
  2162. } SMARTLIST_FOREACH_END(circ);
  2163. log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  2164. "%d guard-stalled, %d complete. %d of the guard-stalled "
  2165. "circuit(s) had high enough priority to upgrade.",
  2166. n_waiting, n_complete, n_succeeded);
  2167. tor_assert_nonfatal(n_succeeded >= 1);
  2168. smartlist_free(all_circuits);
  2169. return 1;
  2170. no_change:
  2171. smartlist_free(all_circuits);
  2172. return 0;
  2173. }
  2174. /**
  2175. * Return true iff the circuit whose state is <b>guard_state</b> should
  2176. * expire.
  2177. */
  2178. int
  2179. entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
  2180. {
  2181. if (guard_state == NULL)
  2182. return 0;
  2183. const time_t expire_if_waiting_since =
  2184. approx_time() - get_nonprimary_guard_idle_timeout();
  2185. return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
  2186. && guard_state->state_set_at < expire_if_waiting_since);
  2187. }
  2188. /**
  2189. * Update all derived pieces of the guard selection state in <b>gs</b>.
  2190. * Return true iff we should stop using all previously generated circuits.
  2191. */
  2192. int
  2193. entry_guards_update_all(guard_selection_t *gs)
  2194. {
  2195. sampled_guards_update_from_consensus(gs);
  2196. entry_guards_update_filtered_sets(gs);
  2197. entry_guards_update_confirmed(gs);
  2198. entry_guards_update_primary(gs);
  2199. return 0;
  2200. }
  2201. /**
  2202. * Return a newly allocated string for encoding the persistent parts of
  2203. * <b>guard</b> to the state file.
  2204. */
  2205. STATIC char *
  2206. entry_guard_encode_for_state(entry_guard_t *guard)
  2207. {
  2208. /*
  2209. * The meta-format we use is K=V K=V K=V... where K can be any
  2210. * characters excepts space and =, and V can be any characters except
  2211. * space. The order of entries is not allowed to matter.
  2212. * Unrecognized K=V entries are persisted; recognized but erroneous
  2213. * entries are corrected.
  2214. */
  2215. smartlist_t *result = smartlist_new();
  2216. char tbuf[ISO_TIME_LEN+1];
  2217. tor_assert(guard);
  2218. smartlist_add_asprintf(result, "in=%s", guard->selection_name);
  2219. smartlist_add_asprintf(result, "rsa_id=%s",
  2220. hex_str(guard->identity, DIGEST_LEN));
  2221. if (guard->bridge_addr) {
  2222. smartlist_add_asprintf(result, "bridge_addr=%s:%d",
  2223. fmt_and_decorate_addr(&guard->bridge_addr->addr),
  2224. guard->bridge_addr->port);
  2225. }
  2226. if (strlen(guard->nickname) && is_legal_nickname(guard->nickname)) {
  2227. smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
  2228. }
  2229. format_iso_time_nospace(tbuf, guard->sampled_on_date);
  2230. smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
  2231. if (guard->sampled_by_version) {
  2232. smartlist_add_asprintf(result, "sampled_by=%s",
  2233. guard->sampled_by_version);
  2234. }
  2235. if (guard->unlisted_since_date > 0) {
  2236. format_iso_time_nospace(tbuf, guard->unlisted_since_date);
  2237. smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
  2238. }
  2239. smartlist_add_asprintf(result, "listed=%d",
  2240. (int)guard->currently_listed);
  2241. if (guard->confirmed_idx >= 0) {
  2242. format_iso_time_nospace(tbuf, guard->confirmed_on_date);
  2243. smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
  2244. smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
  2245. }
  2246. const double EPSILON = 1.0e-6;
  2247. /* Make a copy of the pathbias object, since we will want to update
  2248. some of them */
  2249. guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
  2250. pb->use_successes = pathbias_get_use_success_count(guard);
  2251. pb->successful_circuits_closed = pathbias_get_close_success_count(guard);
  2252. #define PB_FIELD(field) do { \
  2253. if (pb->field >= EPSILON) { \
  2254. smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
  2255. } \
  2256. } while (0)
  2257. PB_FIELD(use_attempts);
  2258. PB_FIELD(use_successes);
  2259. PB_FIELD(circ_attempts);
  2260. PB_FIELD(circ_successes);
  2261. PB_FIELD(successful_circuits_closed);
  2262. PB_FIELD(collapsed_circuits);
  2263. PB_FIELD(unusable_circuits);
  2264. PB_FIELD(timeouts);
  2265. tor_free(pb);
  2266. #undef PB_FIELD
  2267. if (guard->extra_state_fields)
  2268. smartlist_add_strdup(result, guard->extra_state_fields);
  2269. char *joined = smartlist_join_strings(result, " ", 0, NULL);
  2270. SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
  2271. smartlist_free(result);
  2272. return joined;
  2273. }
  2274. /**
  2275. * Given a string generated by entry_guard_encode_for_state(), parse it
  2276. * (if possible) and return an entry_guard_t object for it. Return NULL
  2277. * on complete failure.
  2278. */
  2279. STATIC entry_guard_t *
  2280. entry_guard_parse_from_state(const char *s)
  2281. {
  2282. /* Unrecognized entries get put in here. */
  2283. smartlist_t *extra = smartlist_new();
  2284. /* These fields get parsed from the string. */
  2285. char *in = NULL;
  2286. char *rsa_id = NULL;
  2287. char *nickname = NULL;
  2288. char *sampled_on = NULL;
  2289. char *sampled_by = NULL;
  2290. char *unlisted_since = NULL;
  2291. char *listed = NULL;
  2292. char *confirmed_on = NULL;
  2293. char *confirmed_idx = NULL;
  2294. char *bridge_addr = NULL;
  2295. // pathbias
  2296. char *pb_use_attempts = NULL;
  2297. char *pb_use_successes = NULL;
  2298. char *pb_circ_attempts = NULL;
  2299. char *pb_circ_successes = NULL;
  2300. char *pb_successful_circuits_closed = NULL;
  2301. char *pb_collapsed_circuits = NULL;
  2302. char *pb_unusable_circuits = NULL;
  2303. char *pb_timeouts = NULL;
  2304. /* Split up the entries. Put the ones we know about in strings and the
  2305. * rest in "extra". */
  2306. {
  2307. smartlist_t *entries = smartlist_new();
  2308. strmap_t *vals = strmap_new(); // Maps keyword to location
  2309. #define FIELD(f) \
  2310. strmap_set(vals, #f, &f);
  2311. FIELD(in);
  2312. FIELD(rsa_id);
  2313. FIELD(nickname);
  2314. FIELD(sampled_on);
  2315. FIELD(sampled_by);
  2316. FIELD(unlisted_since);
  2317. FIELD(listed);
  2318. FIELD(confirmed_on);
  2319. FIELD(confirmed_idx);
  2320. FIELD(bridge_addr);
  2321. FIELD(pb_use_attempts);
  2322. FIELD(pb_use_successes);
  2323. FIELD(pb_circ_attempts);
  2324. FIELD(pb_circ_successes);
  2325. FIELD(pb_successful_circuits_closed);
  2326. FIELD(pb_collapsed_circuits);
  2327. FIELD(pb_unusable_circuits);
  2328. FIELD(pb_timeouts);
  2329. #undef FIELD
  2330. smartlist_split_string(entries, s, " ",
  2331. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2332. SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
  2333. const char *eq = strchr(entry, '=');
  2334. if (!eq) {
  2335. smartlist_add(extra, entry);
  2336. continue;
  2337. }
  2338. char *key = tor_strndup(entry, eq-entry);
  2339. char **target = strmap_get(vals, key);
  2340. if (target == NULL || *target != NULL) {
  2341. /* unrecognized or already set */
  2342. smartlist_add(extra, entry);
  2343. tor_free(key);
  2344. continue;
  2345. }
  2346. *target = tor_strdup(eq+1);
  2347. tor_free(key);
  2348. tor_free(entry);
  2349. } SMARTLIST_FOREACH_END(entry);
  2350. smartlist_free(entries);
  2351. strmap_free(vals, NULL);
  2352. }
  2353. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  2354. guard->is_persistent = 1;
  2355. if (in == NULL) {
  2356. log_warn(LD_CIRC, "Guard missing 'in' field");
  2357. goto err;
  2358. }
  2359. guard->selection_name = in;
  2360. in = NULL;
  2361. if (rsa_id == NULL) {
  2362. log_warn(LD_CIRC, "Guard missing RSA ID field");
  2363. goto err;
  2364. }
  2365. /* Process the identity and nickname. */
  2366. if (base16_decode(guard->identity, sizeof(guard->identity),
  2367. rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
  2368. log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
  2369. goto err;
  2370. }
  2371. if (nickname) {
  2372. strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  2373. } else {
  2374. guard->nickname[0]='$';
  2375. base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
  2376. guard->identity, DIGEST_LEN);
  2377. }
  2378. if (bridge_addr) {
  2379. tor_addr_port_t res;
  2380. memset(&res, 0, sizeof(res));
  2381. int r = tor_addr_port_parse(LOG_WARN, bridge_addr,
  2382. &res.addr, &res.port, -1);
  2383. if (r == 0)
  2384. guard->bridge_addr = tor_memdup(&res, sizeof(res));
  2385. /* On error, we already warned. */
  2386. }
  2387. /* Process the various time fields. */
  2388. #define HANDLE_TIME(field) do { \
  2389. if (field) { \
  2390. int r = parse_iso_time_nospace(field, &field ## _time); \
  2391. if (r < 0) { \
  2392. log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
  2393. #field, escaped(field)); \
  2394. field##_time = -1; \
  2395. } \
  2396. } \
  2397. } while (0)
  2398. time_t sampled_on_time = 0;
  2399. time_t unlisted_since_time = 0;
  2400. time_t confirmed_on_time = 0;
  2401. HANDLE_TIME(sampled_on);
  2402. HANDLE_TIME(unlisted_since);
  2403. HANDLE_TIME(confirmed_on);
  2404. if (sampled_on_time <= 0)
  2405. sampled_on_time = approx_time();
  2406. if (unlisted_since_time < 0)
  2407. unlisted_since_time = 0;
  2408. if (confirmed_on_time < 0)
  2409. confirmed_on_time = 0;
  2410. #undef HANDLE_TIME
  2411. guard->sampled_on_date = sampled_on_time;
  2412. guard->unlisted_since_date = unlisted_since_time;
  2413. guard->confirmed_on_date = confirmed_on_time;
  2414. /* Take sampled_by_version verbatim. */
  2415. guard->sampled_by_version = sampled_by;
  2416. sampled_by = NULL; /* prevent free */
  2417. /* Listed is a boolean */
  2418. if (listed && strcmp(listed, "0"))
  2419. guard->currently_listed = 1;
  2420. /* The index is a nonnegative integer. */
  2421. guard->confirmed_idx = -1;
  2422. if (confirmed_idx) {
  2423. int ok=1;
  2424. long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
  2425. if (! ok) {
  2426. log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
  2427. escaped(confirmed_idx));
  2428. } else {
  2429. guard->confirmed_idx = (int)idx;
  2430. }
  2431. }
  2432. /* Anything we didn't recognize gets crammed together */
  2433. if (smartlist_len(extra) > 0) {
  2434. guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
  2435. }
  2436. /* initialize non-persistent fields */
  2437. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  2438. #define PB_FIELD(field) \
  2439. do { \
  2440. if (pb_ ## field) { \
  2441. int ok = 1; \
  2442. double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
  2443. if (! ok) { \
  2444. log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
  2445. #field, pb_ ## field); \
  2446. } else { \
  2447. guard->pb.field = r; \
  2448. } \
  2449. } \
  2450. } while (0)
  2451. PB_FIELD(use_attempts);
  2452. PB_FIELD(use_successes);
  2453. PB_FIELD(circ_attempts);
  2454. PB_FIELD(circ_successes);
  2455. PB_FIELD(successful_circuits_closed);
  2456. PB_FIELD(collapsed_circuits);
  2457. PB_FIELD(unusable_circuits);
  2458. PB_FIELD(timeouts);
  2459. #undef PB_FIELD
  2460. pathbias_check_use_success_count(guard);
  2461. pathbias_check_close_success_count(guard);
  2462. /* We update everything on this guard later, after we've parsed
  2463. * everything. */
  2464. goto done;
  2465. err:
  2466. // only consider it an error if the guard state was totally unparseable.
  2467. entry_guard_free(guard);
  2468. guard = NULL;
  2469. done:
  2470. tor_free(in);
  2471. tor_free(rsa_id);
  2472. tor_free(nickname);
  2473. tor_free(sampled_on);
  2474. tor_free(sampled_by);
  2475. tor_free(unlisted_since);
  2476. tor_free(listed);
  2477. tor_free(confirmed_on);
  2478. tor_free(confirmed_idx);
  2479. tor_free(bridge_addr);
  2480. tor_free(pb_use_attempts);
  2481. tor_free(pb_use_successes);
  2482. tor_free(pb_circ_attempts);
  2483. tor_free(pb_circ_successes);
  2484. tor_free(pb_successful_circuits_closed);
  2485. tor_free(pb_collapsed_circuits);
  2486. tor_free(pb_unusable_circuits);
  2487. tor_free(pb_timeouts);
  2488. SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
  2489. smartlist_free(extra);
  2490. return guard;
  2491. }
  2492. /**
  2493. * Replace the Guards entries in <b>state</b> with a list of all our sampled
  2494. * guards.
  2495. */
  2496. static void
  2497. entry_guards_update_guards_in_state(or_state_t *state)
  2498. {
  2499. if (!guard_contexts)
  2500. return;
  2501. config_line_t *lines = NULL;
  2502. config_line_t **nextline = &lines;
  2503. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2504. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  2505. if (guard->is_persistent == 0)
  2506. continue;
  2507. *nextline = tor_malloc_zero(sizeof(config_line_t));
  2508. (*nextline)->key = tor_strdup("Guard");
  2509. (*nextline)->value = entry_guard_encode_for_state(guard);
  2510. nextline = &(*nextline)->next;
  2511. } SMARTLIST_FOREACH_END(guard);
  2512. } SMARTLIST_FOREACH_END(gs);
  2513. config_free_lines(state->Guard);
  2514. state->Guard = lines;
  2515. }
  2516. /**
  2517. * Replace our sampled guards from the Guards entries in <b>state</b>. Return 0
  2518. * on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only
  2519. * check whether replacing would work.)
  2520. */
  2521. static int
  2522. entry_guards_load_guards_from_state(or_state_t *state, int set)
  2523. {
  2524. const config_line_t *line = state->Guard;
  2525. int n_errors = 0;
  2526. if (!guard_contexts)
  2527. guard_contexts = smartlist_new();
  2528. /* Wipe all our existing guard info. (we shouldn't have any, but
  2529. * let's be safe.) */
  2530. if (set) {
  2531. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2532. guard_selection_free(gs);
  2533. if (curr_guard_context == gs)
  2534. curr_guard_context = NULL;
  2535. SMARTLIST_DEL_CURRENT(guard_contexts, gs);
  2536. } SMARTLIST_FOREACH_END(gs);
  2537. }
  2538. for ( ; line != NULL; line = line->next) {
  2539. entry_guard_t *guard = entry_guard_parse_from_state(line->value);
  2540. if (guard == NULL) {
  2541. ++n_errors;
  2542. continue;
  2543. }
  2544. tor_assert(guard->selection_name);
  2545. if (!strcmp(guard->selection_name, "legacy")) {
  2546. ++n_errors;
  2547. entry_guard_free(guard);
  2548. continue;
  2549. }
  2550. if (set) {
  2551. guard_selection_t *gs;
  2552. gs = get_guard_selection_by_name(guard->selection_name,
  2553. GS_TYPE_INFER, 1);
  2554. tor_assert(gs);
  2555. smartlist_add(gs->sampled_entry_guards, guard);
  2556. guard->in_selection = gs;
  2557. } else {
  2558. entry_guard_free(guard);
  2559. }
  2560. }
  2561. if (set) {
  2562. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2563. entry_guards_update_all(gs);
  2564. } SMARTLIST_FOREACH_END(gs);
  2565. }
  2566. return n_errors ? -1 : 0;
  2567. }
  2568. /** If <b>digest</b> matches the identity of any node in the
  2569. * entry_guards list for the provided guard selection state,
  2570. return that node. Else return NULL. */
  2571. entry_guard_t *
  2572. entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
  2573. const char *digest)
  2574. {
  2575. tor_assert(gs != NULL);
  2576. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry,
  2577. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  2578. return entry;
  2579. );
  2580. return NULL;
  2581. }
  2582. /** Return the node_t associated with a single entry_guard_t. May
  2583. * return NULL if the guard is not currently in the consensus. */
  2584. const node_t *
  2585. entry_guard_find_node(const entry_guard_t *guard)
  2586. {
  2587. tor_assert(guard);
  2588. return node_get_by_id(guard->identity);
  2589. }
  2590. /** If <b>digest</b> matches the identity of any node in the
  2591. * entry_guards list for the default guard selection state,
  2592. return that node. Else return NULL. */
  2593. entry_guard_t *
  2594. entry_guard_get_by_id_digest(const char *digest)
  2595. {
  2596. return entry_guard_get_by_id_digest_for_guard_selection(
  2597. get_guard_selection_info(), digest);
  2598. }
  2599. /** Release all storage held by <b>e</b>. */
  2600. STATIC void
  2601. entry_guard_free(entry_guard_t *e)
  2602. {
  2603. if (!e)
  2604. return;
  2605. entry_guard_handles_clear(e);
  2606. tor_free(e->sampled_by_version);
  2607. tor_free(e->extra_state_fields);
  2608. tor_free(e->selection_name);
  2609. tor_free(e->bridge_addr);
  2610. tor_free(e);
  2611. }
  2612. /** Return 0 if we're fine adding arbitrary routers out of the
  2613. * directory to our entry guard list, or return 1 if we have a
  2614. * list already and we must stick to it.
  2615. */
  2616. int
  2617. entry_list_is_constrained(const or_options_t *options)
  2618. {
  2619. // XXXX prop271 look at the current selection.
  2620. if (options->EntryNodes)
  2621. return 1;
  2622. if (options->UseBridges)
  2623. return 1;
  2624. return 0;
  2625. }
  2626. /** Return the number of bridges that have descriptors that are marked with
  2627. * purpose 'bridge' and are running.
  2628. */
  2629. int
  2630. num_bridges_usable(void)
  2631. {
  2632. int n_options = 0;
  2633. /* XXXX prop271 Is this quite right? */
  2634. tor_assert(get_options()->UseBridges);
  2635. guard_selection_t *gs = get_guard_selection_info();
  2636. tor_assert(gs->type == GS_TYPE_BRIDGE);
  2637. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  2638. if (guard->is_reachable == GUARD_REACHABLE_NO)
  2639. continue;
  2640. if (tor_digest_is_zero(guard->identity))
  2641. continue;
  2642. const node_t *node = node_get_by_id(guard->identity);
  2643. if (node && node->ri)
  2644. ++n_options;
  2645. } SMARTLIST_FOREACH_END(guard);
  2646. return n_options;
  2647. }
  2648. /** Check the pathbias use success count of <b>node</b> and disable it if it
  2649. * goes over our thresholds. */
  2650. static void
  2651. pathbias_check_use_success_count(entry_guard_t *node)
  2652. {
  2653. const or_options_t *options = get_options();
  2654. const double EPSILON = 1.0e-9;
  2655. /* Note: We rely on the < comparison here to allow us to set a 0
  2656. * rate and disable the feature entirely. If refactoring, don't
  2657. * change to <= */
  2658. if (node->pb.use_attempts > EPSILON &&
  2659. pathbias_get_use_success_count(node)/node->pb.use_attempts
  2660. < pathbias_get_extreme_use_rate(options) &&
  2661. pathbias_get_dropguards(options)) {
  2662. node->pb.path_bias_disabled = 1;
  2663. log_info(LD_GENERAL,
  2664. "Path use bias is too high (%f/%f); disabling node %s",
  2665. node->pb.circ_successes, node->pb.circ_attempts,
  2666. node->nickname);
  2667. }
  2668. }
  2669. /** Check the pathbias close count of <b>node</b> and disable it if it goes
  2670. * over our thresholds. */
  2671. static void
  2672. pathbias_check_close_success_count(entry_guard_t *node)
  2673. {
  2674. const or_options_t *options = get_options();
  2675. const double EPSILON = 1.0e-9;
  2676. /* Note: We rely on the < comparison here to allow us to set a 0
  2677. * rate and disable the feature entirely. If refactoring, don't
  2678. * change to <= */
  2679. if (node->pb.circ_attempts > EPSILON &&
  2680. pathbias_get_close_success_count(node)/node->pb.circ_attempts
  2681. < pathbias_get_extreme_rate(options) &&
  2682. pathbias_get_dropguards(options)) {
  2683. node->pb.path_bias_disabled = 1;
  2684. log_info(LD_GENERAL,
  2685. "Path bias is too high (%f/%f); disabling node %s",
  2686. node->pb.circ_successes, node->pb.circ_attempts,
  2687. node->nickname);
  2688. }
  2689. }
  2690. /** Parse <b>state</b> and learn about the entry guards it describes.
  2691. * If <b>set</b> is true, and there are no errors, replace the guard
  2692. * list in the default guard selection context with what we find.
  2693. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  2694. * describing the error, and return -1.
  2695. */
  2696. int
  2697. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  2698. {
  2699. entry_guards_dirty = 0;
  2700. int r1 = entry_guards_load_guards_from_state(state, set);
  2701. entry_guards_dirty = 0;
  2702. if (r1 < 0) {
  2703. if (msg && *msg == NULL) {
  2704. *msg = tor_strdup("parsing error"); //xxxx prop271 should we try harder?
  2705. }
  2706. return -1;
  2707. }
  2708. return 0;
  2709. }
  2710. /** How long will we let a change in our guard nodes stay un-saved
  2711. * when we are trying to avoid disk writes? */
  2712. #define SLOW_GUARD_STATE_FLUSH_TIME 600
  2713. /** How long will we let a change in our guard nodes stay un-saved
  2714. * when we are not trying to avoid disk writes? */
  2715. #define FAST_GUARD_STATE_FLUSH_TIME 30
  2716. /** Our list of entry guards has changed for a particular guard selection
  2717. * context, or some element of one of our entry guards has changed for one.
  2718. * Write the changes to disk within the next few minutes.
  2719. */
  2720. void
  2721. entry_guards_changed_for_guard_selection(guard_selection_t *gs)
  2722. {
  2723. time_t when;
  2724. tor_assert(gs != NULL);
  2725. entry_guards_dirty = 1;
  2726. if (get_options()->AvoidDiskWrites)
  2727. when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
  2728. else
  2729. when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
  2730. /* or_state_save() will call entry_guards_update_state() and
  2731. entry_guards_update_guards_in_state()
  2732. */
  2733. or_state_mark_dirty(get_or_state(), when);
  2734. }
  2735. /** Our list of entry guards has changed for the default guard selection
  2736. * context, or some element of one of our entry guards has changed. Write
  2737. * the changes to disk within the next few minutes.
  2738. */
  2739. void
  2740. entry_guards_changed(void)
  2741. {
  2742. entry_guards_changed_for_guard_selection(get_guard_selection_info());
  2743. }
  2744. /** If the entry guard info has not changed, do nothing and return.
  2745. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  2746. * a new one out of the global entry_guards list, and then mark
  2747. * <b>state</b> dirty so it will get saved to disk.
  2748. */
  2749. void
  2750. entry_guards_update_state(or_state_t *state)
  2751. {
  2752. entry_guards_dirty = 0;
  2753. // Handles all guard info.
  2754. entry_guards_update_guards_in_state(state);
  2755. entry_guards_dirty = 0;
  2756. if (!get_options()->AvoidDiskWrites)
  2757. or_state_mark_dirty(get_or_state(), 0);
  2758. entry_guards_dirty = 0;
  2759. }
  2760. /**
  2761. * Format a single entry guard in the format expected by the controller.
  2762. * Return a newly allocated string.
  2763. */
  2764. STATIC char *
  2765. getinfo_helper_format_single_entry_guard(const entry_guard_t *e)
  2766. {
  2767. const char *status = NULL;
  2768. time_t when = 0;
  2769. const node_t *node;
  2770. char tbuf[ISO_TIME_LEN+1];
  2771. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  2772. /* This is going to be a bit tricky, since the status
  2773. * codes weren't really intended for prop271 guards.
  2774. *
  2775. * XXXX use a more appropriate format for exporting this information
  2776. */
  2777. if (e->confirmed_idx < 0) {
  2778. status = "never-connected";
  2779. } else if (! e->currently_listed) {
  2780. when = e->unlisted_since_date;
  2781. status = "unusable";
  2782. } else if (! e->is_filtered_guard) {
  2783. status = "unusable";
  2784. } else if (e->is_reachable == GUARD_REACHABLE_NO) {
  2785. when = e->failing_since;
  2786. status = "down";
  2787. } else {
  2788. status = "up";
  2789. }
  2790. node = entry_guard_find_node(e);
  2791. if (node) {
  2792. node_get_verbose_nickname(node, nbuf);
  2793. } else {
  2794. nbuf[0] = '$';
  2795. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  2796. /* e->nickname field is not very reliable if we don't know about
  2797. * this router any longer; don't include it. */
  2798. }
  2799. char *result = NULL;
  2800. if (when) {
  2801. format_iso_time(tbuf, when);
  2802. tor_asprintf(&result, "%s %s %s\n", nbuf, status, tbuf);
  2803. } else {
  2804. tor_asprintf(&result, "%s %s\n", nbuf, status);
  2805. }
  2806. return result;
  2807. }
  2808. /** If <b>question</b> is the string "entry-guards", then dump
  2809. * to *<b>answer</b> a newly allocated string describing all of
  2810. * the nodes in the global entry_guards list. See control-spec.txt
  2811. * for details.
  2812. * For backward compatibility, we also handle the string "helper-nodes".
  2813. *
  2814. * XXX this should be totally redesigned after prop 271 too, and that's
  2815. * going to take some control spec work.
  2816. * */
  2817. int
  2818. getinfo_helper_entry_guards(control_connection_t *conn,
  2819. const char *question, char **answer,
  2820. const char **errmsg)
  2821. {
  2822. guard_selection_t *gs = get_guard_selection_info();
  2823. tor_assert(gs != NULL);
  2824. (void) conn;
  2825. (void) errmsg;
  2826. if (!strcmp(question,"entry-guards") ||
  2827. !strcmp(question,"helper-nodes")) {
  2828. const smartlist_t *guards;
  2829. guards = gs->sampled_entry_guards;
  2830. smartlist_t *sl = smartlist_new();
  2831. SMARTLIST_FOREACH_BEGIN(guards, const entry_guard_t *, e) {
  2832. char *cp = getinfo_helper_format_single_entry_guard(e);
  2833. smartlist_add(sl, cp);
  2834. } SMARTLIST_FOREACH_END(e);
  2835. *answer = smartlist_join_strings(sl, "", 0, NULL);
  2836. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  2837. smartlist_free(sl);
  2838. }
  2839. return 0;
  2840. }
  2841. /* Given the original bandwidth of a guard and its guardfraction,
  2842. * calculate how much bandwidth the guard should have as a guard and
  2843. * as a non-guard.
  2844. *
  2845. * Quoting from proposal236:
  2846. *
  2847. * Let Wpf denote the weight from the 'bandwidth-weights' line a
  2848. * client would apply to N for position p if it had the guard
  2849. * flag, Wpn the weight if it did not have the guard flag, and B the
  2850. * measured bandwidth of N in the consensus. Then instead of choosing
  2851. * N for position p proportionally to Wpf*B or Wpn*B, clients should
  2852. * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
  2853. *
  2854. * This function fills the <b>guardfraction_bw</b> structure. It sets
  2855. * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
  2856. */
  2857. void
  2858. guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
  2859. int orig_bandwidth,
  2860. uint32_t guardfraction_percentage)
  2861. {
  2862. double guardfraction_fraction;
  2863. /* Turn the percentage into a fraction. */
  2864. tor_assert(guardfraction_percentage <= 100);
  2865. guardfraction_fraction = guardfraction_percentage / 100.0;
  2866. long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
  2867. tor_assert(guard_bw <= INT_MAX);
  2868. guardfraction_bw->guard_bw = (int) guard_bw;
  2869. guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
  2870. }
  2871. /** Helper: Update the status of all entry guards, in whatever algorithm
  2872. * is used. Return true if we should stop using all previously generated
  2873. * circuits, by calling circuit_mark_all_unused_circs() and
  2874. * circuit_mark_all_dirty_circs_as_unusable().
  2875. */
  2876. int
  2877. guards_update_all(void)
  2878. {
  2879. int mark_circuits = 0;
  2880. if (update_guard_selection_choice(get_options()))
  2881. mark_circuits = 1;
  2882. tor_assert(curr_guard_context);
  2883. if (entry_guards_update_all(curr_guard_context))
  2884. mark_circuits = 1;
  2885. return mark_circuits;
  2886. }
  2887. /** Helper: pick a guard for a circuit, with whatever algorithm is
  2888. used. */
  2889. const node_t *
  2890. guards_choose_guard(cpath_build_state_t *state,
  2891. circuit_guard_state_t **guard_state_out)
  2892. {
  2893. const node_t *r = NULL;
  2894. const uint8_t *exit_id = NULL;
  2895. entry_guard_restriction_t *rst = NULL;
  2896. if (state && (exit_id = build_state_get_exit_rsa_id(state))) {
  2897. /* We're building to a targeted exit node, so that node can't be
  2898. * chosen as our guard for this circuit. Remember that fact in a
  2899. * restriction. */
  2900. rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
  2901. memcpy(rst->exclude_id, exit_id, DIGEST_LEN);
  2902. }
  2903. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  2904. GUARD_USAGE_TRAFFIC,
  2905. rst,
  2906. &r,
  2907. guard_state_out) < 0) {
  2908. tor_assert(r == NULL);
  2909. }
  2910. return r;
  2911. }
  2912. /** Remove all currently listed entry guards for a given guard selection
  2913. * context. This frees and replaces <b>gs</b>, so don't use <b>gs</b>
  2914. * after calling this function. */
  2915. void
  2916. remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
  2917. {
  2918. // This function shouldn't exist. XXXX
  2919. tor_assert(gs != NULL);
  2920. char *old_name = tor_strdup(gs->name);
  2921. guard_selection_type_t old_type = gs->type;
  2922. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry, {
  2923. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2924. });
  2925. if (gs == curr_guard_context) {
  2926. curr_guard_context = NULL;
  2927. }
  2928. smartlist_remove(guard_contexts, gs);
  2929. guard_selection_free(gs);
  2930. gs = get_guard_selection_by_name(old_name, old_type, 1);
  2931. entry_guards_changed_for_guard_selection(gs);
  2932. tor_free(old_name);
  2933. }
  2934. /** Remove all currently listed entry guards. So new ones will be chosen. */
  2935. void
  2936. remove_all_entry_guards(void)
  2937. {
  2938. // XXXX prop271 this function shouldn't exist, in the new order.
  2939. // This function shouldn't exist.
  2940. remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
  2941. }
  2942. /** Helper: pick a directory guard, with whatever algorithm is used. */
  2943. const node_t *
  2944. guards_choose_dirguard(circuit_guard_state_t **guard_state_out)
  2945. {
  2946. const node_t *r = NULL;
  2947. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  2948. GUARD_USAGE_DIRGUARD,
  2949. NULL,
  2950. &r,
  2951. guard_state_out) < 0) {
  2952. tor_assert(r == NULL);
  2953. }
  2954. return r;
  2955. }
  2956. /**
  2957. * If we're running with a constrained guard set, then maybe mark our guards
  2958. * usable. Return 1 if we do; 0 if we don't.
  2959. */
  2960. int
  2961. guards_retry_optimistic(const or_options_t *options)
  2962. {
  2963. if (! entry_list_is_constrained(options))
  2964. return 0;
  2965. // XXXX prop271 -- is this correct?
  2966. mark_primary_guards_maybe_reachable(get_guard_selection_info());
  2967. return 1;
  2968. }
  2969. /**
  2970. * Return true iff we know enough directory information to construct
  2971. * circuits through all of the primary guards we'd currently use.
  2972. */
  2973. int
  2974. guard_selection_have_enough_dir_info_to_build_circuits(guard_selection_t *gs)
  2975. {
  2976. if (!gs->primary_guards_up_to_date)
  2977. entry_guards_update_primary(gs);
  2978. const int num_primary = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC);
  2979. int n_missing_descriptors = 0;
  2980. int n_considered = 0;
  2981. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  2982. entry_guard_consider_retry(guard);
  2983. if (guard->is_reachable == GUARD_REACHABLE_NO)
  2984. continue;
  2985. n_considered++;
  2986. if (!guard_has_descriptor(guard))
  2987. n_missing_descriptors++;
  2988. if (n_considered >= num_primary)
  2989. break;
  2990. } SMARTLIST_FOREACH_END(guard);
  2991. return n_missing_descriptors == 0;
  2992. }
  2993. /** As guard_selection_have_enough_dir_info_to_build_circuits, but uses
  2994. * the default guard selection. */
  2995. int
  2996. entry_guards_have_enough_dir_info_to_build_circuits(void)
  2997. {
  2998. return guard_selection_have_enough_dir_info_to_build_circuits(
  2999. get_guard_selection_info());
  3000. }
  3001. /** Free one guard selection context */
  3002. STATIC void
  3003. guard_selection_free(guard_selection_t *gs)
  3004. {
  3005. if (!gs) return;
  3006. tor_free(gs->name);
  3007. if (gs->sampled_entry_guards) {
  3008. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
  3009. entry_guard_free(e));
  3010. smartlist_free(gs->sampled_entry_guards);
  3011. gs->sampled_entry_guards = NULL;
  3012. }
  3013. smartlist_free(gs->confirmed_entry_guards);
  3014. smartlist_free(gs->primary_entry_guards);
  3015. tor_free(gs);
  3016. }
  3017. /** Release all storage held by the list of entry guards and related
  3018. * memory structs. */
  3019. void
  3020. entry_guards_free_all(void)
  3021. {
  3022. /* Null out the default */
  3023. curr_guard_context = NULL;
  3024. /* Free all the guard contexts */
  3025. if (guard_contexts != NULL) {
  3026. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  3027. guard_selection_free(gs);
  3028. } SMARTLIST_FOREACH_END(gs);
  3029. smartlist_free(guard_contexts);
  3030. guard_contexts = NULL;
  3031. }
  3032. circuit_build_times_free_timeouts(get_circuit_build_times_mutable());
  3033. }