entrynodes.c 120 KB

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