entrynodes.c 124 KB

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