entrynodes.c 111 KB

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