entrynodes.c 120 KB

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