entrynodes.c 119 KB

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