entrynodes.c 112 KB

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