entrynodes.c 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524
  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-2016, 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. * XXXX prop271 This module is in flux, since I'm currently in the middle of
  14. * implementation proposal 271. The module documentation here will describe
  15. * the new algorithm and data structures; the old ones should get removed as
  16. * proposal 271 is completed.
  17. *
  18. * In general, we use entry guards to prevent traffic-sampling attacks:
  19. * if we chose every circuit independently, an adversary controlling
  20. * some fraction of paths on the network would observe a sample of every
  21. * user's traffic. Using guards gives users a chance of not being
  22. * profiled.
  23. *
  24. * The current entry guard selection code is designed to try to avoid
  25. * _ever_ trying every guard on the network, to try to stick to guards
  26. * that we've used before, to handle hostile/broken networks, and
  27. * to behave sanely when the network goes up and down.
  28. *
  29. * Our algorithm works as follows: First, we maintain a SAMPLE of guards
  30. * we've seen in the networkstatus consensus. We maintain this sample
  31. * over time, and store it persistently; it is chosen without reference
  32. * to our configuration or firewall rules. Guards remain in the sample
  33. * as they enter and leave the consensus. We expand this sample as
  34. * needed, up to a maximum size.
  35. *
  36. * As a subset of the sample, we maintain a FILTERED SET of the guards
  37. * that we would be willing to use if we could connect to them. The
  38. * filter removes all the guards that we're excluding because they're
  39. * bridges (or not bridges), because we have restrictive firewall rules,
  40. * because of ExcludeNodes, because we of path bias restrictions,
  41. * because they're absent from the network at present, and so on.
  42. *
  43. * As a subset of the filtered set, we keep a REACHABLE FILTERED SET
  44. * (also called a "usable filtered set") of those guards that we call
  45. * "reachable" or "maybe reachable". A guard is reachable if we've
  46. * connected to it more recently than we've failed. A guard is "maybe
  47. * reachable" if we have never tried to connect to it, or if we
  48. * failed to connect to it so long ago that we no longer think our
  49. * failure means it's down.
  50. *
  51. * As a persistent ordered list whose elements are taken from the
  52. * sampled set, we track a CONFIRMED GUARDS LIST. A guard becomes
  53. * confirmed when we successfully build a circuit through it, and decide
  54. * to use that circuit. We order the guards on this list by the order
  55. * in which they became confirmed.
  56. *
  57. * And as a final group, we have an ordered list of PRIMARY GUARDS,
  58. * whose elements are taken from the filtered set. We prefer
  59. * confirmed guards to non-confirmed guards for this list, and place
  60. * other restrictions on it. The primary guards are the ones that we
  61. * connect to "when nothing is wrong" -- circuits through them can be used
  62. * immediately.
  63. *
  64. * To build circuits, we take a primary guard if possible -- or a
  65. * reachable filtered confirmed guard if no primary guard is possible --
  66. * or a random reachable filtered guard otherwise. If the guard is
  67. * primary, we can use the circuit immediately on success. Otherwise,
  68. * the guard is now "pending" -- we won't use its circuit unless all
  69. * of the circuits we're trying to build through better guards have
  70. * definitely failed.
  71. *
  72. * While we're building circuits, we track a little "guard state" for
  73. * each circuit. We use this to keep track of whether the circuit is
  74. * one that we can use as soon as its done, or whether it's one that
  75. * we should keep around to see if we can do better. In the latter case,
  76. * a periodic call to entry_guards_upgrade_waiting_circuits() will
  77. * eventually upgrade it.
  78. **/
  79. /* DOCDOC -- expand this.
  80. *
  81. * Information invariants:
  82. *
  83. * [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
  84. *
  85. * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
  86. * flag is set, set its usable_filtered flag.
  87. *
  88. * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
  89. *
  90. * [x] Whenever the configuration changes in a relevant way, update the
  91. * filtered/usable flags. (LATER.)
  92. *
  93. * [x] Whenever we add a guard to the sample, make sure its filtered/usable
  94. * flags are set as possible.
  95. *
  96. * [x] Whenever we remove a guard from the sample, remove it from the primary
  97. * and confirmed lists.
  98. *
  99. * [x] When we make a guard confirmed, update the primary list.
  100. *
  101. * [x] When we make a guard filtered or unfiltered, update the primary list.
  102. *
  103. * [x] When we are about to pick a guard, make sure that the primary list is
  104. * full.
  105. *
  106. * [x] Before calling sample_reachable_filtered_entry_guards(), make sure
  107. * that the filtered, primary, and confirmed flags are up-to-date.
  108. *
  109. * [x] Call entry_guard_consider_retry every time we are about to check
  110. * is_usable_filtered or is_reachable, and every time we set
  111. * is_filtered to 1.
  112. *
  113. * [x] Call entry_guards_changed_for_guard_selection() whenever we update
  114. * a persistent field.
  115. */
  116. #define ENTRYNODES_PRIVATE
  117. #include "or.h"
  118. #include "bridges.h"
  119. #include "circpathbias.h"
  120. #include "circuitbuild.h"
  121. #include "circuitlist.h"
  122. #include "circuitstats.h"
  123. #include "config.h"
  124. #include "confparse.h"
  125. #include "connection.h"
  126. #include "connection_or.h"
  127. #include "control.h"
  128. #include "directory.h"
  129. #include "entrynodes.h"
  130. #include "main.h"
  131. #include "microdesc.h"
  132. #include "networkstatus.h"
  133. #include "nodelist.h"
  134. #include "policies.h"
  135. #include "router.h"
  136. #include "routerlist.h"
  137. #include "routerparse.h"
  138. #include "routerset.h"
  139. #include "transports.h"
  140. #include "statefile.h"
  141. static smartlist_t *guard_contexts = NULL;
  142. static guard_selection_t *curr_guard_context = NULL;
  143. /** A value of 1 means that at least one context has changed,
  144. * and those changes need to be flushed to disk. */
  145. static int entry_guards_dirty = 0;
  146. static const node_t *choose_random_entry_impl(guard_selection_t *gs,
  147. cpath_build_state_t *state,
  148. int for_directory,
  149. dirinfo_type_t dirtype,
  150. int *n_options_out);
  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(guard_selection_t *gs, const node_t *node);
  157. static int node_passes_guard_filter(const or_options_t *options,
  158. guard_selection_t *gs,
  159. const node_t *node);
  160. /** Return 0 if we should apply guardfraction information found in the
  161. * consensus. A specific consensus can be specified with the
  162. * <b>ns</b> argument, if NULL the most recent one will be picked.*/
  163. int
  164. should_apply_guardfraction(const networkstatus_t *ns)
  165. {
  166. /* We need to check the corresponding torrc option and the consensus
  167. * parameter if we need to. */
  168. const or_options_t *options = get_options();
  169. /* If UseGuardFraction is 'auto' then check the same-named consensus
  170. * parameter. If the consensus parameter is not present, default to
  171. * "off". */
  172. if (options->UseGuardFraction == -1) {
  173. return networkstatus_get_param(ns, "UseGuardFraction",
  174. 0, /* default to "off" */
  175. 0, 1);
  176. }
  177. return options->UseGuardFraction;
  178. }
  179. /**
  180. * Allocate and return a new guard_selection_t, with the name <b>name</b>.
  181. */
  182. STATIC guard_selection_t *
  183. guard_selection_new(const char *name,
  184. guard_selection_type_t type)
  185. {
  186. guard_selection_t *gs;
  187. if (type == GS_TYPE_INFER) {
  188. if (!strcmp(name, "legacy"))
  189. type = GS_TYPE_LEGACY;
  190. else if (!strcmp(name, "bridges"))
  191. type = GS_TYPE_BRIDGE;
  192. else if (!strcmp(name, "restricted"))
  193. type = GS_TYPE_RESTRICTED;
  194. else
  195. type = GS_TYPE_NORMAL;
  196. }
  197. gs = tor_malloc_zero(sizeof(*gs));
  198. gs->name = tor_strdup(name);
  199. gs->type = type;
  200. gs->chosen_entry_guards = smartlist_new();
  201. gs->sampled_entry_guards = smartlist_new();
  202. gs->confirmed_entry_guards = smartlist_new();
  203. gs->primary_entry_guards = smartlist_new();
  204. return gs;
  205. }
  206. /**
  207. * Return the guard selection called <b>name</b>. If there is none, and
  208. * <b>create_if_absent</b> is true, then create and return it. If there
  209. * is none, and <b>create_if_absent</b> is false, then return NULL.
  210. */
  211. STATIC guard_selection_t *
  212. get_guard_selection_by_name(const char *name,
  213. guard_selection_type_t type,
  214. int create_if_absent)
  215. {
  216. if (!guard_contexts) {
  217. guard_contexts = smartlist_new();
  218. }
  219. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  220. if (!strcmp(gs->name, name))
  221. return gs;
  222. } SMARTLIST_FOREACH_END(gs);
  223. if (! create_if_absent)
  224. return NULL;
  225. log_debug(LD_GUARD, "Creating a guard selection called %s", name);
  226. guard_selection_t *new_selection = guard_selection_new(name, type);
  227. smartlist_add(guard_contexts, new_selection);
  228. return new_selection;
  229. }
  230. /**
  231. * Allocate the first guard context that we're planning to use,
  232. * and make it the current context.
  233. */
  234. static void
  235. create_initial_guard_context(void)
  236. {
  237. tor_assert(! curr_guard_context);
  238. if (!guard_contexts) {
  239. guard_contexts = smartlist_new();
  240. }
  241. guard_selection_type_t type = GS_TYPE_INFER;
  242. const char *name = choose_guard_selection(
  243. get_options(),
  244. networkstatus_get_live_consensus(approx_time()),
  245. NULL,
  246. &type);
  247. tor_assert(name); // "name" can only be NULL if we had an old name.
  248. tor_assert(type != GS_TYPE_INFER);
  249. log_notice(LD_GUARD, "Starting with guard context \"%s\"", name);
  250. curr_guard_context = get_guard_selection_by_name_and_type(name, type);
  251. }
  252. /** Get current default guard_selection_t, creating it if necessary */
  253. guard_selection_t *
  254. get_guard_selection_info(void)
  255. {
  256. if (!curr_guard_context) {
  257. create_initial_guard_context();
  258. }
  259. return curr_guard_context;
  260. }
  261. /** Return the list of entry guards for a guard_selection_t, creating it
  262. * if necessary. */
  263. const smartlist_t *
  264. get_entry_guards_for_guard_selection(guard_selection_t *gs)
  265. {
  266. tor_assert(gs != NULL);
  267. tor_assert(gs->chosen_entry_guards != NULL);
  268. return gs->chosen_entry_guards;
  269. }
  270. /** Return the list of entry guards for the default guard_selection_t,
  271. * creating it if necessary. */
  272. const smartlist_t *
  273. get_entry_guards(void)
  274. {
  275. return get_entry_guards_for_guard_selection(get_guard_selection_info());
  276. }
  277. /** Helper: mark an entry guard as not usable. */
  278. void
  279. entry_guard_mark_bad(entry_guard_t *guard)
  280. {
  281. guard->bad_since = approx_time();
  282. entry_guards_changed();
  283. }
  284. /** Return a statically allocated human-readable description of <b>guard</b>
  285. */
  286. const char *
  287. entry_guard_describe(const entry_guard_t *guard)
  288. {
  289. static char buf[256];
  290. tor_snprintf(buf, sizeof(buf),
  291. "%s ($%s)",
  292. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  293. return buf;
  294. }
  295. /** Return <b>guard</b>'s 20-byte RSA identity digest */
  296. const char *
  297. entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
  298. {
  299. return guard->identity;
  300. }
  301. /** Return the pathbias state associated with <b>guard</b>. */
  302. guard_pathbias_t *
  303. entry_guard_get_pathbias_state(entry_guard_t *guard)
  304. {
  305. return &guard->pb;
  306. }
  307. HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC)
  308. /** Return an interval betweeen 'now' and 'max_backdate' seconds in the past,
  309. * chosen uniformly at random. We use this before recording persistent
  310. * dates, so that we aren't leaking exactly when we recorded it.
  311. */
  312. MOCK_IMPL(STATIC time_t,
  313. randomize_time,(time_t now, time_t max_backdate))
  314. {
  315. tor_assert(max_backdate > 0);
  316. time_t earliest = now - max_backdate;
  317. time_t latest = now;
  318. if (earliest <= 0)
  319. earliest = 1;
  320. if (latest <= earliest)
  321. latest = earliest + 1;
  322. return crypto_rand_time_range(earliest, latest);
  323. }
  324. /**
  325. * @name parameters for networkstatus algorithm
  326. *
  327. * These parameters are taken from the consensus; some are overrideable in
  328. * the torrc.
  329. */
  330. /**@{*/
  331. /**
  332. * We never let our sampled guard set grow larger than this fraction
  333. * of the guards on the network.
  334. */
  335. STATIC double
  336. get_max_sample_threshold(void)
  337. {
  338. int32_t pct =
  339. networkstatus_get_param(NULL, "guard-max-sample-threshold-percent",
  340. DFLT_MAX_SAMPLE_THRESHOLD_PERCENT,
  341. 1, 100);
  342. return pct / 100.0;
  343. }
  344. /**
  345. * We always try to make our sample contain at least this many guards.
  346. *
  347. * XXXX prop271 There was a MIN_SAMPLE_THRESHOLD in the proposal, but I
  348. * removed it in favor of MIN_FILTERED_SAMPLE_SIZE. -NM
  349. */
  350. STATIC int
  351. get_min_filtered_sample_size(void)
  352. {
  353. return networkstatus_get_param(NULL, "guard-min-filtered-sample-size",
  354. DFLT_MIN_FILTERED_SAMPLE_SIZE,
  355. 1, INT32_MAX);
  356. }
  357. /**
  358. * If a guard is unlisted for this many days in a row, we remove it.
  359. */
  360. STATIC int
  361. get_remove_unlisted_guards_after_days(void)
  362. {
  363. return networkstatus_get_param(NULL,
  364. "guard-remove-unlisted-guards-after-days",
  365. DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS,
  366. 1, 365*10);
  367. }
  368. /**
  369. * We remove unconfirmed guards from the sample after this many days,
  370. * regardless of whether they are listed or unlisted.
  371. */
  372. STATIC int
  373. get_guard_lifetime_days(void)
  374. {
  375. return networkstatus_get_param(NULL,
  376. "guard-lifetime-days",
  377. DFLT_GUARD_LIFETIME_DAYS, 1, 365*10);
  378. }
  379. /**
  380. * We remove confirmed guards from the sample if they were sampled
  381. * GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
  382. */
  383. STATIC int
  384. get_guard_confirmed_min_lifetime_days(void)
  385. {
  386. return networkstatus_get_param(NULL, "guard-confirmed-min-lifetime-days",
  387. DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS,
  388. 1, 365*10);
  389. }
  390. /**
  391. * How many guards do we try to keep on our primary guard list?
  392. */
  393. STATIC int
  394. get_n_primary_guards(void)
  395. {
  396. return networkstatus_get_param(NULL, "guard-n-primary-guards",
  397. DFLT_N_PRIMARY_GUARDS, 1, INT32_MAX);
  398. }
  399. /**
  400. * If we haven't successfully built or used a circuit in this long, then
  401. * consider that the internet is probably down.
  402. */
  403. STATIC int
  404. get_internet_likely_down_interval(void)
  405. {
  406. return networkstatus_get_param(NULL, "guard-internet-likely-down-interval",
  407. DFLT_INTERNET_LIKELY_DOWN_INTERVAL,
  408. 1, INT32_MAX);
  409. }
  410. /**
  411. * If we're trying to connect to a nonprimary guard for at least this
  412. * many seconds, and we haven't gotten the connection to work, we will treat
  413. * lower-priority guards as usable.
  414. */
  415. STATIC int
  416. get_nonprimary_guard_connect_timeout(void)
  417. {
  418. return networkstatus_get_param(NULL,
  419. "guard-nonprimary-guard-connect-timeout",
  420. DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT,
  421. 1, INT32_MAX);
  422. }
  423. /**
  424. * If a circuit has been sitting around in 'waiting for better guard' state
  425. * for at least this long, we'll expire it.
  426. */
  427. STATIC int
  428. get_nonprimary_guard_idle_timeout(void)
  429. {
  430. return networkstatus_get_param(NULL,
  431. "guard-nonprimary-guard-idle-timeout",
  432. DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT,
  433. 1, INT32_MAX);
  434. }
  435. /**
  436. * If our configuration retains fewer than this fraction of guards from the
  437. * torrc, we are in a restricted setting.
  438. */
  439. STATIC double
  440. get_meaningful_restriction_threshold(void)
  441. {
  442. int32_t pct = networkstatus_get_param(NULL,
  443. "guard-meaningful-restriction-percent",
  444. DFLT_MEANINGFUL_RESTRICTION_PERCENT,
  445. 1, INT32_MAX);
  446. return pct / 100.0;
  447. }
  448. /**
  449. * If our configuration retains fewer than this fraction of guards from the
  450. * torrc, we are in an extremely restricted setting, and should warn.
  451. */
  452. STATIC double
  453. get_extreme_restriction_threshold(void)
  454. {
  455. int32_t pct = networkstatus_get_param(NULL,
  456. "guard-extreme-restriction-percent",
  457. DFLT_EXTREME_RESTRICTION_PERCENT,
  458. 1, INT32_MAX);
  459. return pct / 100.0;
  460. }
  461. /**@}*/
  462. /**
  463. * Given our options and our list of nodes, return the name of the
  464. * guard selection that we should use. Return NULL for "use the
  465. * same selection you were using before.
  466. */
  467. STATIC const char *
  468. choose_guard_selection(const or_options_t *options,
  469. const networkstatus_t *live_ns,
  470. const char *old_selection,
  471. guard_selection_type_t *type_out)
  472. {
  473. tor_assert(options);
  474. tor_assert(type_out);
  475. if (options->UseDeprecatedGuardAlgorithm) {
  476. *type_out = GS_TYPE_LEGACY;
  477. return "legacy";
  478. }
  479. if (options->UseBridges) {
  480. *type_out = GS_TYPE_BRIDGE;
  481. return "bridges";
  482. }
  483. if (! live_ns) {
  484. /* without a networkstatus, we can't tell any more than that. */
  485. *type_out = GS_TYPE_NORMAL;
  486. return "default";
  487. }
  488. const smartlist_t *nodes = nodelist_get_list();
  489. int n_guards = 0, n_passing_filter = 0;
  490. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  491. if (node_is_possible_guard(NULL, node)) {
  492. ++n_guards;
  493. if (node_passes_guard_filter(options, NULL, node)) {
  494. ++n_passing_filter;
  495. }
  496. }
  497. } SMARTLIST_FOREACH_END(node);
  498. /* XXXX prop271 spec deviation -- separate 'high' and 'low' thresholds
  499. * to prevent flapping */
  500. const int meaningful_threshold_high =
  501. (int)(n_guards * get_meaningful_restriction_threshold() * 1.05);
  502. const int meaningful_threshold_mid =
  503. (int)(n_guards * get_meaningful_restriction_threshold());
  504. const int meaningful_threshold_low =
  505. (int)(n_guards * get_meaningful_restriction_threshold() * .95);
  506. const int extreme_threshold =
  507. (int)(n_guards * get_extreme_restriction_threshold());
  508. /*
  509. If we have no previous selection, then we're "restricted" iff we are
  510. below the meaningful restriction threshold. That's easy enough.
  511. But if we _do_ have a previous selection, we make it a little
  512. "sticky": we only move from "restricted" to "default" when we find
  513. that we're above the threshold plus 5%, and we only move from
  514. "default" to "restricted" when we're below the threshold minus 5%.
  515. That should prevent us from flapping back and forth if we happen to
  516. be hovering very close to the default.
  517. The extreme threshold is for warning only.
  518. */
  519. static int have_warned_extreme_threshold = 0;
  520. if (n_passing_filter < extreme_threshold &&
  521. ! have_warned_extreme_threshold) {
  522. have_warned_extreme_threshold = 1;
  523. const double exclude_frac =
  524. (n_guards - n_passing_filter) / (double)n_guards;
  525. log_warn(LD_GUARD, "Your configuration excludes %d%% of all possible "
  526. "guards. That's likely to make you stand out from the "
  527. "rest of the world.", (int)(exclude_frac * 100));
  528. }
  529. /* Easy case: no previous selection */
  530. if (old_selection == NULL) {
  531. if (n_passing_filter >= meaningful_threshold_mid) {
  532. *type_out = GS_TYPE_NORMAL;
  533. return "default";
  534. } else {
  535. *type_out = GS_TYPE_RESTRICTED;
  536. return "restricted";
  537. }
  538. }
  539. /* Trickier case: we do have a previous selection */
  540. if (n_passing_filter >= meaningful_threshold_high) {
  541. *type_out = GS_TYPE_NORMAL;
  542. return "default";
  543. } else if (n_passing_filter < meaningful_threshold_low) {
  544. *type_out = GS_TYPE_RESTRICTED;
  545. return "restricted";
  546. } else {
  547. return NULL;
  548. }
  549. }
  550. /**
  551. * Check whether we should switch from our current guard selection to a
  552. * different one. If so, switch and return 1. Return 0 otherwise.
  553. *
  554. * On a 1 return, the caller should mark all currently live circuits
  555. * unusable for new streams.
  556. */
  557. int
  558. update_guard_selection_choice(const or_options_t *options)
  559. {
  560. if (!curr_guard_context) {
  561. create_initial_guard_context();
  562. return 1;
  563. }
  564. const char *cur_name = curr_guard_context->name;
  565. guard_selection_type_t type = GS_TYPE_INFER;
  566. const char *new_name = choose_guard_selection(
  567. options,
  568. networkstatus_get_live_consensus(approx_time()),
  569. cur_name,
  570. &type);
  571. tor_assert(new_name);
  572. tor_assert(type != GS_TYPE_INFER);
  573. if (! strcmp(cur_name, new_name)) {
  574. log_debug(LD_GUARD,
  575. "Staying with guard context \"%s\" (no change)", new_name);
  576. return 0; // No change
  577. }
  578. log_notice(LD_GUARD, "Switching to guard context \"%s\" (was using \"%s\")",
  579. new_name, cur_name);
  580. guard_selection_t *new_guard_context;
  581. new_guard_context = get_guard_selection_by_name(new_name, type, 1);
  582. tor_assert(new_guard_context);
  583. tor_assert(new_guard_context != curr_guard_context);
  584. curr_guard_context = new_guard_context;
  585. /*
  586. Be sure to call:
  587. circuit_mark_all_unused_circs();
  588. circuit_mark_all_dirty_circs_as_unusable();
  589. */
  590. return 1;
  591. }
  592. /**
  593. * Return true iff <b>node</b> has all the flags needed for us to consider it
  594. * a possible guard when sampling guards.
  595. */
  596. static int
  597. node_is_possible_guard(guard_selection_t *gs, const node_t *node)
  598. {
  599. /* The "GUARDS" set is all nodes in the nodelist for which this predicate
  600. * holds. */
  601. /* XXXX -- prop271 spec deviation. We require node_is_dir() here. */
  602. (void)gs; /* Remove this argument */
  603. tor_assert(node);
  604. return (node->is_possible_guard &&
  605. node->is_stable &&
  606. node->is_fast &&
  607. node->is_valid &&
  608. node_is_dir(node));
  609. }
  610. /**
  611. * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
  612. * NULL if we don't have one. */
  613. STATIC entry_guard_t *
  614. get_sampled_guard_with_id(guard_selection_t *gs,
  615. const uint8_t *rsa_id)
  616. {
  617. tor_assert(gs);
  618. tor_assert(rsa_id);
  619. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  620. if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN))
  621. return guard;
  622. } SMARTLIST_FOREACH_END(guard);
  623. return NULL;
  624. }
  625. /**
  626. * Return true iff we have a sampled guard with the RSA identity digest
  627. * <b>rsa_id</b>. */
  628. static inline int
  629. have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
  630. {
  631. return get_sampled_guard_with_id(gs, rsa_id) != NULL;
  632. }
  633. /**
  634. * Allocate a new entry_guard_t object for <b>node</b>, add it to the
  635. * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
  636. * not currently be a sampled guard in <b>gs</b>.
  637. */
  638. STATIC entry_guard_t *
  639. entry_guard_add_to_sample(guard_selection_t *gs,
  640. const node_t *node)
  641. {
  642. const int GUARD_LIFETIME = get_guard_lifetime_days() * 86400;
  643. tor_assert(gs);
  644. tor_assert(node);
  645. log_info(LD_GUARD, "Adding %s as to the entry guard sample set.",
  646. node_describe(node));
  647. // XXXX prop271 take ed25519 identity here too.
  648. /* make sure that the guard is not already sampled. */
  649. if (BUG(have_sampled_guard_with_id(gs, (uint8_t*)node->identity)))
  650. return NULL; // LCOV_EXCL_LINE
  651. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  652. /* persistent fields */
  653. guard->selection_name = tor_strdup(gs->name);
  654. memcpy(guard->identity, node->identity, DIGEST_LEN);
  655. strlcpy(guard->nickname, node_get_nickname(node), sizeof(guard->nickname));
  656. guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  657. tor_free(guard->sampled_by_version);
  658. guard->sampled_by_version = tor_strdup(VERSION);
  659. guard->currently_listed = 1;
  660. guard->confirmed_idx = -1;
  661. /* non-persistent fields */
  662. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  663. smartlist_add(gs->sampled_entry_guards, guard);
  664. entry_guard_set_filtered_flags(get_options(), gs, guard);
  665. entry_guards_changed_for_guard_selection(gs);
  666. return guard;
  667. }
  668. /**
  669. * Return the number of sampled guards in <b>gs</b> that are "filtered"
  670. * (that is, we're willing to connect to them) and that are "usable"
  671. * (that is, either "reachable" or "maybe reachable"). */
  672. STATIC int
  673. num_reachable_filtered_guards(guard_selection_t *gs)
  674. {
  675. int n_reachable_filtered_guards = 0;
  676. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  677. entry_guard_consider_retry(guard);
  678. if (guard->is_usable_filtered_guard)
  679. ++n_reachable_filtered_guards;
  680. } SMARTLIST_FOREACH_END(guard);
  681. return n_reachable_filtered_guards;
  682. }
  683. /**
  684. * Add new guards to the sampled guards in <b>gs</b> until there are
  685. * enough usable filtered guards, but never grow the sample beyond its
  686. * maximum size. Return the last guard added, or NULL if none were
  687. * added.
  688. */
  689. STATIC entry_guard_t *
  690. entry_guards_expand_sample(guard_selection_t *gs)
  691. {
  692. tor_assert(gs);
  693. int n_sampled = smartlist_len(gs->sampled_entry_guards);
  694. entry_guard_t *added_guard = NULL;
  695. const smartlist_t *nodes = nodelist_get_list();
  696. /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
  697. smartlist_t *eligible_guards = smartlist_new();
  698. int n_guards = 0; // total size of "GUARDS"
  699. int n_usable_filtered_guards = num_reachable_filtered_guards(gs);
  700. {
  701. /* Build a bloom filter of our current guards: let's keep this O(N). */
  702. digestset_t *sampled_guard_ids = digestset_new(n_sampled);
  703. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *,
  704. guard) {
  705. digestset_add(sampled_guard_ids, guard->identity);
  706. } SMARTLIST_FOREACH_END(guard);
  707. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  708. if (! node_is_possible_guard(gs, node))
  709. continue;
  710. ++n_guards;
  711. if (digestset_contains(sampled_guard_ids, node->identity))
  712. continue;
  713. smartlist_add(eligible_guards, (node_t*)node);
  714. } SMARTLIST_FOREACH_END(node);
  715. /* Now we can free that bloom filter. */
  716. digestset_free(sampled_guard_ids);
  717. }
  718. /* Is there at least one guard we haven't sampled? */
  719. if (! smartlist_len(eligible_guards))
  720. goto done;
  721. const int max_sample = (int)(n_guards * get_max_sample_threshold());
  722. const int min_filtered_sample = get_min_filtered_sample_size();
  723. log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
  724. "in the sample, and %d eligible guards to extend it with.",
  725. n_sampled, smartlist_len(eligible_guards));
  726. while (n_usable_filtered_guards < min_filtered_sample) {
  727. /* Has our sample grown too large to expand? */
  728. if (n_sampled >= max_sample) {
  729. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  730. "just hit the maximum sample threshold of %d",
  731. max_sample);
  732. goto done;
  733. }
  734. /* Did we run out of guards? */
  735. if (smartlist_len(eligible_guards) == 0) {
  736. /* LCOV_EXCL_START
  737. As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
  738. allow all guards to be sampled, this can't be reached.
  739. */
  740. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  741. "just ran out of eligible guards");
  742. goto done;
  743. /* LCOV_EXCL_STOP */
  744. }
  745. /* Otherwise we can add at least one new guard. */
  746. const node_t *node =
  747. node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD);
  748. if (BUG(! node))
  749. goto done; // LCOV_EXCL_LINE -- should be impossible.
  750. added_guard = entry_guard_add_to_sample(gs, node);
  751. if (!added_guard)
  752. goto done; // LCOV_EXCL_LINE -- only fails on BUG.
  753. ++n_sampled;
  754. if (added_guard->is_usable_filtered_guard)
  755. ++n_usable_filtered_guards;
  756. smartlist_remove(eligible_guards, node);
  757. }
  758. done:
  759. smartlist_free(eligible_guards);
  760. return added_guard;
  761. }
  762. /**
  763. * Helper: <b>guard</b> has just been removed from the sampled guards:
  764. * also remove it from primary and confirmed. */
  765. static void
  766. remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs,
  767. entry_guard_t *guard)
  768. {
  769. if (guard->is_primary) {
  770. guard->is_primary = 0;
  771. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  772. } else {
  773. if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
  774. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  775. }
  776. }
  777. if (guard->confirmed_idx >= 0) {
  778. entry_guard_t *found_guard = NULL;
  779. if (guard->confirmed_idx < smartlist_len(gs->confirmed_entry_guards))
  780. found_guard = smartlist_get(gs->confirmed_entry_guards,
  781. guard->confirmed_idx);
  782. if (BUG(guard != found_guard)) {
  783. // LCOV_EXCL_START
  784. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  785. // LCOV_EXCL_STOP
  786. } else {
  787. smartlist_del_keeporder(gs->confirmed_entry_guards,
  788. guard->confirmed_idx);
  789. }
  790. guard->confirmed_idx = -1;
  791. guard->confirmed_on_date = 0;
  792. } else {
  793. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
  794. // LCOV_EXCL_START
  795. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  796. // LCOV_EXCL_STOP
  797. }
  798. }
  799. }
  800. /**
  801. * Update the status of all sampled guards based on the arrival of a
  802. * new consensus networkstatus document. This will include marking
  803. * some guards as listed or unlisted, and removing expired guards. */
  804. STATIC void
  805. sampled_guards_update_from_consensus(guard_selection_t *gs)
  806. {
  807. tor_assert(gs);
  808. const int REMOVE_UNLISTED_GUARDS_AFTER =
  809. (get_remove_unlisted_guards_after_days() * 86400);
  810. const int unlisted_since_slop = REMOVE_UNLISTED_GUARDS_AFTER / 5;
  811. // It's important to use only a live consensus here; we don't want to
  812. // make changes based on anything expired or old.
  813. networkstatus_t *ns = networkstatus_get_live_consensus(approx_time());
  814. log_info(LD_GUARD, "Updating sampled guard status based on received "
  815. "consensus.");
  816. if (! ns || ns->valid_until < approx_time()) {
  817. log_info(LD_GUARD, "Hey, that consensus isn't still valid. Ignoring.");
  818. return;
  819. }
  820. int n_changes = 0;
  821. /* First: Update listed/unlisted. */
  822. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  823. /* XXXX prop271 handle bridges right? */
  824. /* XXXX prop271 check ed ID too */
  825. const node_t *node = node_get_by_id(guard->identity);
  826. const unsigned is_listed = node && node_is_possible_guard(gs, node);
  827. if (is_listed && ! guard->currently_listed) {
  828. ++n_changes;
  829. guard->currently_listed = 1;
  830. guard->unlisted_since_date = 0;
  831. log_info(LD_GUARD, "Sampled guard %s is now listed again.",
  832. entry_guard_describe(guard));
  833. } else if (!is_listed && guard->currently_listed) {
  834. ++n_changes;
  835. guard->currently_listed = 0;
  836. guard->unlisted_since_date = randomize_time(approx_time(),
  837. unlisted_since_slop);
  838. log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
  839. entry_guard_describe(guard));
  840. } else if (is_listed && guard->currently_listed) {
  841. log_debug(LD_GUARD, "Sampled guard %s is still listed.",
  842. entry_guard_describe(guard));
  843. } else {
  844. tor_assert(! is_listed && ! guard->currently_listed);
  845. log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
  846. entry_guard_describe(guard));
  847. }
  848. /* Clean up unlisted_since_date, just in case. */
  849. if (guard->currently_listed && guard->unlisted_since_date) {
  850. ++n_changes;
  851. guard->unlisted_since_date = 0;
  852. log_warn(LD_BUG, "Sampled guard %s was listed, but with "
  853. "unlisted_since_date set. Fixing.",
  854. entry_guard_describe(guard));
  855. } else if (!guard->currently_listed && ! guard->unlisted_since_date) {
  856. ++n_changes;
  857. guard->unlisted_since_date = randomize_time(approx_time(),
  858. unlisted_since_slop);
  859. log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
  860. "unlisted_since_date unset. Fixing.",
  861. entry_guard_describe(guard));
  862. }
  863. } SMARTLIST_FOREACH_END(guard);
  864. const time_t remove_if_unlisted_since =
  865. approx_time() - REMOVE_UNLISTED_GUARDS_AFTER;
  866. const time_t maybe_remove_if_sampled_before =
  867. approx_time() - (get_guard_lifetime_days() * 86400);
  868. const time_t remove_if_confirmed_before =
  869. approx_time() - (get_guard_confirmed_min_lifetime_days() * 86400);
  870. /* Then: remove the ones that have been junk for too long */
  871. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  872. /* XXXX prop271 handle bridges right? */
  873. int remove = 0;
  874. if (guard->currently_listed == 0 &&
  875. guard->unlisted_since_date < remove_if_unlisted_since) {
  876. /*
  877. "We have a live consensus, and {IS_LISTED} is false, and
  878. {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}
  879. days in the past."
  880. */
  881. log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
  882. "for over %d days", entry_guard_describe(guard),
  883. get_remove_unlisted_guards_after_days());
  884. remove = 1;
  885. } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
  886. /* We have a live consensus, and {ADDED_ON_DATE} is over
  887. {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
  888. "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
  889. */
  890. if (guard->confirmed_on_date == 0) {
  891. remove = 1;
  892. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  893. "over %d days ago, but never confirmed.",
  894. entry_guard_describe(guard),
  895. get_guard_lifetime_days());
  896. } else if (guard->confirmed_on_date < remove_if_confirmed_before) {
  897. remove = 1;
  898. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  899. "over %d days ago, and confirmed over %d days ago.",
  900. entry_guard_describe(guard),
  901. get_guard_lifetime_days(),
  902. get_guard_confirmed_min_lifetime_days());
  903. }
  904. }
  905. if (remove) {
  906. ++n_changes;
  907. SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard);
  908. remove_guard_from_confirmed_and_primary_lists(gs, guard);
  909. entry_guard_free(guard);
  910. }
  911. } SMARTLIST_FOREACH_END(guard);
  912. if (n_changes) {
  913. gs->primary_guards_up_to_date = 0;
  914. entry_guards_update_filtered_sets(gs);
  915. /* We don't need to rebuild the confirmed list right here -- we may have
  916. * removed confirmed guards above, but we can't have added any new
  917. * confirmed guards.
  918. */
  919. entry_guards_changed_for_guard_selection(gs);
  920. }
  921. }
  922. /**
  923. * Return true iff <b>node</b> is a Tor relay that we are configured to
  924. * be able to connect to. */
  925. static int
  926. node_passes_guard_filter(const or_options_t *options, guard_selection_t *gs,
  927. const node_t *node)
  928. {
  929. /* XXXX prop271 remote the gs option; it is unused, and sometimes NULL. */
  930. /* NOTE: Make sure that this function stays in sync with
  931. * options_transition_affects_entry_guards */
  932. (void)gs;
  933. if (routerset_contains_node(options->ExcludeNodes, node))
  934. return 0;
  935. /* XXXX -- prop271 spec deviation -- add entrynodes to spec. */
  936. if (options->EntryNodes &&
  937. !options->UseBridges &&
  938. !routerset_contains_node(options->EntryNodes, node))
  939. return 0;
  940. if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
  941. return 0;
  942. if (bool_neq(options->UseBridges, node_is_a_configured_bridge(node)))
  943. return 0;
  944. return 1;
  945. }
  946. /**
  947. * Return true iff <b>guard</b> is a Tor relay that we are configured to
  948. * be able to connect to, and we haven't disabled it for omission from
  949. * the consensus or path bias issues. */
  950. static int
  951. entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
  952. entry_guard_t *guard)
  953. {
  954. if (guard->currently_listed == 0)
  955. return 0;
  956. if (guard->pb.path_bias_disabled)
  957. return 0;
  958. const node_t *node = node_get_by_id(guard->identity);
  959. if (node == NULL) {
  960. // This can happen when currently_listed is true, and we're not updating
  961. // it because we don't have a live consensus.
  962. return 0;
  963. }
  964. return node_passes_guard_filter(options, gs, node);
  965. }
  966. /**
  967. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  968. * flags on <b>guard</b>. */
  969. void
  970. entry_guard_set_filtered_flags(const or_options_t *options,
  971. guard_selection_t *gs,
  972. entry_guard_t *guard)
  973. {
  974. unsigned was_filtered = guard->is_filtered_guard;
  975. guard->is_filtered_guard = 0;
  976. guard->is_usable_filtered_guard = 0;
  977. if (entry_guard_passes_filter(options, gs, guard)) {
  978. guard->is_filtered_guard = 1;
  979. if (guard->is_reachable != GUARD_REACHABLE_NO)
  980. guard->is_usable_filtered_guard = 1;
  981. entry_guard_consider_retry(guard);
  982. }
  983. log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
  984. "reachable_filtered=%d.", entry_guard_describe(guard),
  985. guard->is_filtered_guard, guard->is_usable_filtered_guard);
  986. if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
  987. /* This guard might now be primary or nonprimary. */
  988. gs->primary_guards_up_to_date = 0;
  989. }
  990. }
  991. /**
  992. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  993. * flag on every guard in <b>gs</b>. */
  994. STATIC void
  995. entry_guards_update_filtered_sets(guard_selection_t *gs)
  996. {
  997. const or_options_t *options = get_options();
  998. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  999. entry_guard_set_filtered_flags(options, gs, guard);
  1000. } SMARTLIST_FOREACH_END(guard);
  1001. }
  1002. /**
  1003. * Return a random guard from the reachable filtered sample guards
  1004. * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
  1005. * Return NULL if no such guard can be found.
  1006. *
  1007. * Make sure that the sample is big enough, and that all the filter flags
  1008. * are set correctly, before calling this function.
  1009. **/
  1010. STATIC entry_guard_t *
  1011. sample_reachable_filtered_entry_guards(guard_selection_t *gs,
  1012. unsigned flags)
  1013. {
  1014. tor_assert(gs);
  1015. entry_guard_t *result = NULL;
  1016. const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
  1017. const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
  1018. const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
  1019. const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
  1020. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1021. entry_guard_consider_retry(guard);
  1022. } SMARTLIST_FOREACH_END(guard);
  1023. const int n_reachable_filtered = num_reachable_filtered_guards(gs);
  1024. log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
  1025. "in the USABLE_FILTERED set.", n_reachable_filtered);
  1026. const int min_filtered_sample = get_min_filtered_sample_size();
  1027. if (n_reachable_filtered < min_filtered_sample) {
  1028. log_info(LD_GUARD, " (That isn't enough. Trying to expand the sample.)");
  1029. entry_guards_expand_sample(gs);
  1030. }
  1031. if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
  1032. entry_guards_update_primary(gs);
  1033. /* Build the set of reachable filtered guards. */
  1034. smartlist_t *reachable_filtered_sample = smartlist_new();
  1035. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1036. entry_guard_consider_retry(guard);// redundant, but cheap.
  1037. if (! guard->is_usable_filtered_guard)
  1038. continue;
  1039. if (exclude_confirmed && guard->confirmed_idx >= 0)
  1040. continue;
  1041. if (exclude_primary && guard->is_primary)
  1042. continue;
  1043. if (exclude_pending && guard->is_pending)
  1044. continue;
  1045. smartlist_add(reachable_filtered_sample, guard);
  1046. } SMARTLIST_FOREACH_END(guard);
  1047. log_info(LD_GUARD, " (After filters [%x], we have %d guards to consider.)",
  1048. flags, smartlist_len(reachable_filtered_sample));
  1049. if (smartlist_len(reachable_filtered_sample)) {
  1050. result = smartlist_choose(reachable_filtered_sample);
  1051. log_info(LD_GUARD, " (Selected %s.)",
  1052. result ? entry_guard_describe(result) : "<null>");
  1053. }
  1054. smartlist_free(reachable_filtered_sample);
  1055. return result;
  1056. }
  1057. /**
  1058. * Helper: compare two entry_guard_t by their confirmed_idx values.
  1059. * Used to sort the confirmed list.
  1060. */
  1061. static int
  1062. compare_guards_by_confirmed_idx(const void **a_, const void **b_)
  1063. {
  1064. const entry_guard_t *a = *a_, *b = *b_;
  1065. if (a->confirmed_idx < b->confirmed_idx)
  1066. return -1;
  1067. else if (a->confirmed_idx > b->confirmed_idx)
  1068. return 1;
  1069. else
  1070. return 0;
  1071. }
  1072. /**
  1073. * Find the confirmed guards from among the sampled guards in <b>gs</b>,
  1074. * and put them in confirmed_entry_guards in the correct
  1075. * order. Recalculate their indices.
  1076. */
  1077. STATIC void
  1078. entry_guards_update_confirmed(guard_selection_t *gs)
  1079. {
  1080. smartlist_clear(gs->confirmed_entry_guards);
  1081. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1082. if (guard->confirmed_idx >= 0)
  1083. smartlist_add(gs->confirmed_entry_guards, guard);
  1084. } SMARTLIST_FOREACH_END(guard);
  1085. smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
  1086. int any_changed = 0;
  1087. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1088. if (guard->confirmed_idx != guard_sl_idx) {
  1089. any_changed = 1;
  1090. guard->confirmed_idx = guard_sl_idx;
  1091. }
  1092. } SMARTLIST_FOREACH_END(guard);
  1093. gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
  1094. if (any_changed) {
  1095. entry_guards_changed_for_guard_selection(gs);
  1096. }
  1097. }
  1098. /**
  1099. * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
  1100. * connected to, and intend to use again.
  1101. */
  1102. STATIC void
  1103. make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
  1104. {
  1105. if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
  1106. return; // LCOV_EXCL_LINE
  1107. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
  1108. return; // LCOV_EXCL_LINE
  1109. const int GUARD_LIFETIME = get_guard_lifetime_days() * 86400;
  1110. guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  1111. log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
  1112. entry_guard_describe(guard),
  1113. gs->next_confirmed_idx);
  1114. guard->confirmed_idx = gs->next_confirmed_idx++;
  1115. smartlist_add(gs->confirmed_entry_guards, guard);
  1116. // This confirmed guard might kick something else out of the primary
  1117. // guards.
  1118. gs->primary_guards_up_to_date = 0;
  1119. entry_guards_changed_for_guard_selection(gs);
  1120. }
  1121. /**
  1122. * Recalculate the list of primary guards (the ones we'd prefer to use) from
  1123. * the filtered sample and the confirmed list.
  1124. */
  1125. STATIC void
  1126. entry_guards_update_primary(guard_selection_t *gs)
  1127. {
  1128. tor_assert(gs);
  1129. // prevent recursion. Recursion is potentially very bad here.
  1130. static int running = 0;
  1131. tor_assert(!running);
  1132. running = 1;
  1133. const int N_PRIMARY_GUARDS = get_n_primary_guards();
  1134. smartlist_t *new_primary_guards = smartlist_new();
  1135. smartlist_t *old_primary_guards = smartlist_new();
  1136. smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
  1137. /* Set this flag now, to prevent the calls below from recursing. */
  1138. gs->primary_guards_up_to_date = 1;
  1139. /* First, can we fill it up with confirmed guards? */
  1140. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1141. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  1142. break;
  1143. if (! guard->is_filtered_guard)
  1144. continue;
  1145. guard->is_primary = 1;
  1146. smartlist_add(new_primary_guards, guard);
  1147. } SMARTLIST_FOREACH_END(guard);
  1148. /* Can we keep any older primary guards? First remove all the ones
  1149. * that we already kept. */
  1150. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1151. if (smartlist_contains(new_primary_guards, guard)) {
  1152. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  1153. }
  1154. } SMARTLIST_FOREACH_END(guard);
  1155. /* Now add any that are still good. */
  1156. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1157. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  1158. break;
  1159. if (! guard->is_filtered_guard)
  1160. continue;
  1161. guard->is_primary = 1;
  1162. smartlist_add(new_primary_guards, guard);
  1163. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  1164. } SMARTLIST_FOREACH_END(guard);
  1165. /* Mark the remaining previous primary guards as non-primary */
  1166. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1167. guard->is_primary = 0;
  1168. } SMARTLIST_FOREACH_END(guard);
  1169. /* Finally, fill out the list with sampled guards. */
  1170. while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
  1171. entry_guard_t *guard = sample_reachable_filtered_entry_guards(gs,
  1172. SAMPLE_EXCLUDE_CONFIRMED|
  1173. SAMPLE_EXCLUDE_PRIMARY|
  1174. SAMPLE_NO_UPDATE_PRIMARY);
  1175. if (!guard)
  1176. break;
  1177. guard->is_primary = 1;
  1178. smartlist_add(new_primary_guards, guard);
  1179. }
  1180. #if 1
  1181. /* Debugging. */
  1182. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
  1183. tor_assert_nonfatal(
  1184. bool_eq(guard->is_primary,
  1185. smartlist_contains(new_primary_guards, guard)));
  1186. });
  1187. #endif
  1188. int any_change = 0;
  1189. if (smartlist_len(gs->primary_entry_guards) !=
  1190. smartlist_len(new_primary_guards)) {
  1191. any_change = 1;
  1192. } else {
  1193. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, g) {
  1194. if (g != smartlist_get(new_primary_guards, g_sl_idx)) {
  1195. any_change = 1;
  1196. }
  1197. } SMARTLIST_FOREACH_END(g);
  1198. }
  1199. if (any_change) {
  1200. log_info(LD_GUARD, "Primary entry guards have changed. "
  1201. "New primary guard list is: ");
  1202. int n = smartlist_len(new_primary_guards);
  1203. SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
  1204. log_info(LD_GUARD, " %d/%d: %s%s%s",
  1205. g_sl_idx+1, n, entry_guard_describe(g),
  1206. g->confirmed_idx >= 0 ? " (confirmed)" : "",
  1207. g->is_filtered_guard ? "" : " (excluded by filter)");
  1208. } SMARTLIST_FOREACH_END(g);
  1209. }
  1210. smartlist_free(old_primary_guards);
  1211. smartlist_free(gs->primary_entry_guards);
  1212. gs->primary_entry_guards = new_primary_guards;
  1213. gs->primary_guards_up_to_date = 1;
  1214. running = 0;
  1215. }
  1216. /**
  1217. * Return the number of seconds after the last attempt at which we should
  1218. * retry a guard that has been failing since <b>failing_since</b>.
  1219. */
  1220. static unsigned
  1221. get_retry_schedule(time_t failing_since, time_t now,
  1222. int is_primary)
  1223. {
  1224. const unsigned SIX_HOURS = 6 * 3600;
  1225. const unsigned FOUR_DAYS = 4 * 86400;
  1226. const unsigned SEVEN_DAYS = 7 * 86400;
  1227. time_t tdiff;
  1228. if (now > failing_since) {
  1229. tdiff = now - failing_since;
  1230. } else {
  1231. tdiff = 0;
  1232. }
  1233. const struct {
  1234. time_t maximum; int primary_delay; int nonprimary_delay;
  1235. } delays[] = {
  1236. { SIX_HOURS, 30*60, 1*60*60 },
  1237. { FOUR_DAYS, 2*60*60, 4*60*60 },
  1238. { SEVEN_DAYS, 4*60*60, 18*60*60 },
  1239. { TIME_MAX, 9*60*60, 36*60*60 }
  1240. };
  1241. unsigned i;
  1242. for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
  1243. if (tdiff <= delays[i].maximum) {
  1244. return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
  1245. }
  1246. }
  1247. /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
  1248. tor_assert_nonfatal_unreached();
  1249. return 36*60*60;
  1250. /* LCOV_EXCL_STOP */
  1251. }
  1252. /**
  1253. * If <b>guard</b> is unreachable, consider whether enough time has passed
  1254. * to consider it maybe-reachable again.
  1255. */
  1256. STATIC void
  1257. entry_guard_consider_retry(entry_guard_t *guard)
  1258. {
  1259. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1260. return; /* No retry needed. */
  1261. const time_t now = approx_time();
  1262. const unsigned delay =
  1263. get_retry_schedule(guard->failing_since, now, guard->is_primary);
  1264. const time_t last_attempt = guard->last_tried_to_connect;
  1265. if (BUG(last_attempt == 0) ||
  1266. now >= last_attempt + delay) {
  1267. /* We should mark this retriable. */
  1268. char tbuf[ISO_TIME_LEN+1];
  1269. format_local_iso_time(tbuf, last_attempt);
  1270. log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
  1271. "haven't tried to use it since %s.",
  1272. guard->is_primary?"primary ":"",
  1273. guard->confirmed_idx>=0?"confirmed ":"",
  1274. entry_guard_describe(guard),
  1275. tbuf);
  1276. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  1277. if (guard->is_filtered_guard)
  1278. guard->is_usable_filtered_guard = 1;
  1279. }
  1280. }
  1281. /** Tell the entry guards subsystem that we have confirmed that as of
  1282. * just now, we're on the internet. */
  1283. void
  1284. entry_guards_note_internet_connectivity(guard_selection_t *gs)
  1285. {
  1286. gs->last_time_on_internet = approx_time();
  1287. }
  1288. /**
  1289. * Get a guard for use with a circuit. Prefer to pick a running primary
  1290. * guard; then a non-pending running filtered confirmed guard; then a
  1291. * non-pending runnable filtered guard. Update the
  1292. * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
  1293. * guard as appropriate. Set <b>state_out</b> to the new guard-state
  1294. * of the circuit.
  1295. */
  1296. STATIC entry_guard_t *
  1297. select_entry_guard_for_circuit(guard_selection_t *gs, unsigned *state_out)
  1298. {
  1299. tor_assert(gs);
  1300. tor_assert(state_out);
  1301. if (!gs->primary_guards_up_to_date)
  1302. entry_guards_update_primary(gs);
  1303. /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
  1304. <maybe> or <yes>, return the first such guard." */
  1305. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1306. entry_guard_consider_retry(guard);
  1307. if (guard->is_reachable != GUARD_REACHABLE_NO) {
  1308. *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
  1309. guard->last_tried_to_connect = approx_time();
  1310. log_info(LD_GUARD, "Selected primary guard %s for circuit.",
  1311. entry_guard_describe(guard));
  1312. return guard;
  1313. }
  1314. } SMARTLIST_FOREACH_END(guard);
  1315. /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
  1316. and {USABLE_FILTERED_GUARDS} is nonempty, return the first
  1317. entry in that intersection that has {is_pending} set to
  1318. false." */
  1319. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1320. if (guard->is_primary)
  1321. continue; /* we already considered this one. */
  1322. entry_guard_consider_retry(guard);
  1323. if (guard->is_usable_filtered_guard && ! guard->is_pending) {
  1324. guard->is_pending = 1;
  1325. guard->last_tried_to_connect = approx_time();
  1326. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1327. log_info(LD_GUARD, "No primary guards available. Selected confirmed "
  1328. "guard %s for circuit. Will try other guards before using "
  1329. "this circuit.",
  1330. entry_guard_describe(guard));
  1331. return guard;
  1332. }
  1333. } SMARTLIST_FOREACH_END(guard);
  1334. /* "Otherwise, if there is no such entry, select a member at
  1335. random from {USABLE_FILTERED_GUARDS}." */
  1336. {
  1337. entry_guard_t *guard;
  1338. guard = sample_reachable_filtered_entry_guards(gs,
  1339. SAMPLE_EXCLUDE_CONFIRMED |
  1340. SAMPLE_EXCLUDE_PRIMARY |
  1341. SAMPLE_EXCLUDE_PENDING);
  1342. if (guard == NULL) {
  1343. log_info(LD_GUARD, "Absolutely no sampled guards were available.");
  1344. return NULL;
  1345. }
  1346. guard->is_pending = 1;
  1347. guard->last_tried_to_connect = approx_time();
  1348. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1349. log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
  1350. "random guard %s for circuit. Will try other guards before "
  1351. "using this circuit.",
  1352. entry_guard_describe(guard));
  1353. return guard;
  1354. }
  1355. }
  1356. /**
  1357. * Note that we failed to connect to or build circuits through <b>guard</b>.
  1358. * Use with a guard returned by select_entry_guards_for_circuit().
  1359. */
  1360. STATIC void
  1361. entry_guards_note_guard_failure(guard_selection_t *gs,
  1362. entry_guard_t *guard)
  1363. {
  1364. tor_assert(gs);
  1365. guard->is_reachable = GUARD_REACHABLE_NO;
  1366. guard->is_usable_filtered_guard = 0;
  1367. guard->is_pending = 0;
  1368. if (guard->failing_since == 0)
  1369. guard->failing_since = approx_time();
  1370. log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
  1371. guard->is_primary?"primary ":"",
  1372. guard->confirmed_idx>=0?"confirmed ":"",
  1373. entry_guard_describe(guard));
  1374. }
  1375. /**
  1376. * Called when the network comes up after having seemed to be down for
  1377. * a while: Mark the primary guards as maybe-reachable so that we'll
  1378. * try them again.
  1379. */
  1380. STATIC void
  1381. mark_primary_guards_maybe_reachable(guard_selection_t *gs)
  1382. {
  1383. if (!gs->primary_guards_up_to_date)
  1384. entry_guards_update_primary(gs);
  1385. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1386. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1387. continue;
  1388. /* Note that we do not clear failing_since: this guard is now only
  1389. * _maybe-reachable_. */
  1390. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  1391. if (guard->is_filtered_guard)
  1392. guard->is_usable_filtered_guard = 1;
  1393. } SMARTLIST_FOREACH_END(guard);
  1394. }
  1395. /**
  1396. * Note that we successfully connected to, and built a circuit through
  1397. * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
  1398. * return the new guard-state of the circuit.
  1399. *
  1400. * Be aware: the circuit is only usable when its guard-state becomes
  1401. * GUARD_CIRC_STATE_COMPLETE.
  1402. **/
  1403. STATIC unsigned
  1404. entry_guards_note_guard_success(guard_selection_t *gs,
  1405. entry_guard_t *guard,
  1406. unsigned old_state)
  1407. {
  1408. tor_assert(gs);
  1409. /* Save this, since we're about to overwrite it. */
  1410. const time_t last_time_on_internet = gs->last_time_on_internet;
  1411. gs->last_time_on_internet = approx_time();
  1412. guard->is_reachable = GUARD_REACHABLE_YES;
  1413. guard->failing_since = 0;
  1414. guard->is_pending = 0;
  1415. if (guard->is_filtered_guard)
  1416. guard->is_usable_filtered_guard = 1;
  1417. if (guard->confirmed_idx < 0) {
  1418. make_guard_confirmed(gs, guard);
  1419. if (!gs->primary_guards_up_to_date)
  1420. entry_guards_update_primary(gs);
  1421. }
  1422. unsigned new_state;
  1423. if (old_state == GUARD_CIRC_STATE_USABLE_ON_COMPLETION) {
  1424. new_state = GUARD_CIRC_STATE_COMPLETE;
  1425. } else {
  1426. tor_assert_nonfatal(
  1427. old_state == GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
  1428. if (guard->is_primary) {
  1429. /* XXXX prop271 -- I don't actually like this logic. It seems to make us
  1430. * a little more susceptible to evil-ISP attacks. The mitigations I'm
  1431. * thinking of, however, aren't local to this point, so I'll leave it
  1432. * alone. */
  1433. /* This guard may have become primary by virtue of being confirmed.
  1434. If so, the circuit for it is now complete.
  1435. */
  1436. new_state = GUARD_CIRC_STATE_COMPLETE;
  1437. } else {
  1438. new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
  1439. }
  1440. if (last_time_on_internet + get_internet_likely_down_interval()
  1441. < approx_time()) {
  1442. mark_primary_guards_maybe_reachable(gs);
  1443. }
  1444. }
  1445. log_info(LD_GUARD, "Recorded success for %s%sguard %s",
  1446. guard->is_primary?"primary ":"",
  1447. guard->confirmed_idx>=0?"confirmed ":"",
  1448. entry_guard_describe(guard));
  1449. return new_state;
  1450. }
  1451. /**
  1452. * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
  1453. */
  1454. STATIC int
  1455. entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
  1456. {
  1457. tor_assert(a && b);
  1458. if (a == b)
  1459. return 0;
  1460. /* Confirmed is always better than unconfirmed; lower index better
  1461. than higher */
  1462. if (a->confirmed_idx < 0) {
  1463. if (b->confirmed_idx >= 0)
  1464. return 0;
  1465. } else {
  1466. if (b->confirmed_idx < 0)
  1467. return 1;
  1468. /* Lower confirmed_idx is better than higher. */
  1469. return (a->confirmed_idx < b->confirmed_idx);
  1470. }
  1471. /* If we reach this point, both are unconfirmed. If one is pending, it
  1472. * has higher priority. */
  1473. if (a->is_pending) {
  1474. if (! b->is_pending)
  1475. return 1;
  1476. /* Both are pending: earlier last_tried_connect wins. */
  1477. return a->last_tried_to_connect < b->last_tried_to_connect;
  1478. } else {
  1479. if (b->is_pending)
  1480. return 0;
  1481. /* Neither is pending: priorities are equal. */
  1482. return 0; // XXXX prop271 return a tristate instead?
  1483. }
  1484. }
  1485. /**
  1486. * Release all storage held in <b>state</b>.
  1487. */
  1488. void
  1489. circuit_guard_state_free(circuit_guard_state_t *state)
  1490. {
  1491. /* XXXX prop271 -- do we want to inline this structure? */
  1492. if (!state)
  1493. return;
  1494. entry_guard_handle_free(state->guard);
  1495. tor_free(state);
  1496. }
  1497. /**
  1498. * Pick a suitable entry guard for a circuit in, and place that guard
  1499. * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
  1500. * state object that will record whether the circuit is ready to be used
  1501. * or not. Return 0 on success; on failure, return -1.
  1502. */
  1503. int
  1504. entry_guard_pick_for_circuit(guard_selection_t *gs,
  1505. const node_t **chosen_node_out,
  1506. circuit_guard_state_t **guard_state_out)
  1507. {
  1508. tor_assert(gs);
  1509. tor_assert(chosen_node_out);
  1510. tor_assert(guard_state_out);
  1511. *chosen_node_out = NULL;
  1512. *guard_state_out = NULL;
  1513. unsigned state = 0;
  1514. entry_guard_t *guard = select_entry_guard_for_circuit(gs, &state);
  1515. if (! guard)
  1516. return -1;
  1517. if (BUG(state == 0))
  1518. return -1;
  1519. const node_t *node = node_get_by_id(guard->identity);
  1520. // XXXX prop271 check Ed ID.
  1521. if (! node)
  1522. return -1;
  1523. *chosen_node_out = node;
  1524. *guard_state_out = tor_malloc_zero(sizeof(circuit_guard_state_t));
  1525. (*guard_state_out)->guard = entry_guard_handle_new(guard);
  1526. (*guard_state_out)->state = state;
  1527. (*guard_state_out)->state_set_at = approx_time();
  1528. return 0;
  1529. }
  1530. /**
  1531. * Called by the circuit building module when a circuit has succeeded:
  1532. * informs the guards code that the guard in *<b>guard_state_p</b> is
  1533. * working, and advances the state of the guard module. On a -1 return
  1534. * value, the circuit is broken and should not be used. On a 1 return
  1535. * value, the circuit is ready to use. On a 0 return value, the circuit
  1536. * should not be used until we find out whether preferred guards will
  1537. * work for us.
  1538. *
  1539. * XXXXX prop271 tristates are ugly; reconsider that interface.
  1540. */
  1541. int
  1542. entry_guard_succeeded(guard_selection_t *gs,
  1543. circuit_guard_state_t **guard_state_p)
  1544. {
  1545. if (get_options()->UseDeprecatedGuardAlgorithm)
  1546. return 1;
  1547. if (BUG(*guard_state_p == NULL))
  1548. return -1;
  1549. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1550. if (! guard)
  1551. return -1;
  1552. unsigned newstate =
  1553. entry_guards_note_guard_success(gs, guard, (*guard_state_p)->state);
  1554. (*guard_state_p)->state = newstate;
  1555. (*guard_state_p)->state_set_at = approx_time();
  1556. if (newstate == GUARD_CIRC_STATE_COMPLETE) {
  1557. return 1;
  1558. } else {
  1559. return 0;
  1560. }
  1561. }
  1562. /** Cancel the selection of *<b>guard_state_p</b> without declaring
  1563. * success or failure. It is safe to call this function if success or
  1564. * failure _has_ already been declared. */
  1565. void
  1566. entry_guard_cancel(guard_selection_t *gs,
  1567. circuit_guard_state_t **guard_state_p)
  1568. {
  1569. (void) gs;
  1570. if (get_options()->UseDeprecatedGuardAlgorithm)
  1571. return;
  1572. if (BUG(*guard_state_p == NULL))
  1573. return;
  1574. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1575. if (! guard)
  1576. return;
  1577. /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
  1578. * function will only get called in "bug" cases anyway. */
  1579. guard->is_pending = 0;
  1580. circuit_guard_state_free(*guard_state_p);
  1581. *guard_state_p = NULL;
  1582. }
  1583. /**
  1584. * Called by the circuit building module when a circuit has succeeded:
  1585. * informs the guards code that the guard in *<b>guard_state_p</b> is
  1586. * not working, and advances the state of the guard module.
  1587. */
  1588. void
  1589. entry_guard_failed(guard_selection_t *gs,
  1590. circuit_guard_state_t **guard_state_p)
  1591. {
  1592. if (get_options()->UseDeprecatedGuardAlgorithm)
  1593. return;
  1594. if (BUG(*guard_state_p == NULL))
  1595. return;
  1596. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1597. if (! guard)
  1598. return;
  1599. entry_guards_note_guard_failure(gs, guard);
  1600. (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
  1601. (*guard_state_p)->state_set_at = approx_time();
  1602. }
  1603. /**
  1604. * Run the entry_guard_failed() function on every circuit that is
  1605. * pending on <b>chan</b>.
  1606. */
  1607. void
  1608. entry_guard_chan_failed(guard_selection_t *gs,
  1609. channel_t *chan)
  1610. {
  1611. tor_assert(gs);
  1612. if (!chan)
  1613. return;
  1614. if (get_options()->UseDeprecatedGuardAlgorithm)
  1615. return;
  1616. smartlist_t *pending = smartlist_new();
  1617. circuit_get_all_pending_on_channel(pending, chan);
  1618. SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
  1619. if (!CIRCUIT_IS_ORIGIN(circ))
  1620. continue;
  1621. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1622. entry_guard_failed(gs, &origin_circ->guard_state);
  1623. } SMARTLIST_FOREACH_END(circ);
  1624. smartlist_free(pending);
  1625. }
  1626. /**
  1627. * Return true iff every primary guard in <b>gs</b> is believed to
  1628. * be unreachable.
  1629. */
  1630. STATIC int
  1631. entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
  1632. {
  1633. tor_assert(gs);
  1634. if (!gs->primary_guards_up_to_date)
  1635. entry_guards_update_primary(gs);
  1636. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1637. entry_guard_consider_retry(guard);
  1638. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1639. return 0;
  1640. } SMARTLIST_FOREACH_END(guard);
  1641. return 1;
  1642. }
  1643. /** Wrapper for entry_guard_has_higher_priority that compares the
  1644. * guard-priorities of a pair of circuits. */
  1645. static int
  1646. circ_state_has_higher_priority(origin_circuit_t *a,
  1647. origin_circuit_t *b)
  1648. {
  1649. circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
  1650. circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);
  1651. tor_assert(state_a);
  1652. tor_assert(state_b);
  1653. entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
  1654. entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);
  1655. if (! guard_a) {
  1656. /* Unknown guard -- never higher priority. */
  1657. return 0;
  1658. } else if (! guard_b) {
  1659. /* Known guard -- higher priority than any unknown guard. */
  1660. return 1;
  1661. } else {
  1662. /* Both known -- compare.*/
  1663. return entry_guard_has_higher_priority(guard_a, guard_b);
  1664. }
  1665. }
  1666. /**
  1667. * Look at all of the origin_circuit_t * objects in <b>all_circuits</b>,
  1668. * and see if any of them that were previously not ready to use for
  1669. * guard-related reasons are now ready to use. Place those circuits
  1670. * in <b>newly_complete_out</b>, and mark them COMPLETE.
  1671. *
  1672. * Return 1 if we upgraded any circuits, and 0 otherwise.
  1673. */
  1674. int
  1675. entry_guards_upgrade_waiting_circuits(guard_selection_t *gs,
  1676. const smartlist_t *all_circuits,
  1677. smartlist_t *newly_complete_out)
  1678. {
  1679. tor_assert(gs);
  1680. tor_assert(all_circuits);
  1681. tor_assert(newly_complete_out);
  1682. if (! entry_guards_all_primary_guards_are_down(gs)) {
  1683. /* We only upgrade a waiting circuit if the primary guards are all
  1684. * down. */
  1685. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  1686. "but not all primary guards were definitely down.");
  1687. return 0;
  1688. }
  1689. int n_waiting = 0;
  1690. int n_complete = 0;
  1691. origin_circuit_t *best_waiting_circuit = NULL;
  1692. origin_circuit_t *best_complete_circuit = NULL;
  1693. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  1694. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  1695. if (state == NULL)
  1696. continue;
  1697. if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
  1698. ++n_waiting;
  1699. if (! best_waiting_circuit ||
  1700. circ_state_has_higher_priority(circ, best_waiting_circuit)) {
  1701. best_waiting_circuit = circ;
  1702. }
  1703. } else if (state->state == GUARD_CIRC_STATE_COMPLETE) {
  1704. ++n_complete;
  1705. if (! best_complete_circuit ||
  1706. circ_state_has_higher_priority(circ, best_complete_circuit)) {
  1707. best_complete_circuit = circ;
  1708. }
  1709. }
  1710. } SMARTLIST_FOREACH_END(circ);
  1711. if (! best_waiting_circuit) {
  1712. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  1713. "but didn't find any.");
  1714. return 0;
  1715. }
  1716. if (best_complete_circuit) {
  1717. if (circ_state_has_higher_priority(best_complete_circuit,
  1718. best_waiting_circuit)) {
  1719. /* "If any circuit is <complete>, then do not use any
  1720. <waiting_for_better_guard> or <usable_if_no_better_guard> circuits
  1721. circuits whose guards have lower priority." */
  1722. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  1723. "%d complete and %d guard-stalled. At least one complete "
  1724. "circuit had higher priority, so not upgrading.",
  1725. n_complete, n_waiting);
  1726. return 0;
  1727. }
  1728. }
  1729. /* "If any circuit is <waiting_for_better_guard>, and every currently
  1730. {is_pending} circuit whose guard has higher priority has been in
  1731. state <usable_if_no_better_guard> for at least
  1732. {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds, and all primary guards
  1733. have reachable status of <no>, then call that circuit <complete>."
  1734. XXXX --- prop271 deviation. there's no such thing in the spec as
  1735. an {is_pending circuit}; fix the spec.
  1736. */
  1737. int n_blockers_found = 0;
  1738. const time_t state_set_at_cutoff =
  1739. approx_time() - get_nonprimary_guard_connect_timeout();
  1740. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  1741. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  1742. if (state == NULL)
  1743. continue;
  1744. if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
  1745. continue;
  1746. if (state->state_set_at > state_set_at_cutoff &&
  1747. circ_state_has_higher_priority(circ, best_waiting_circuit))
  1748. ++n_blockers_found;
  1749. } SMARTLIST_FOREACH_END(circ);
  1750. if (n_blockers_found) {
  1751. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  1752. "%d guard-stalled, but %d pending circuit(s) had higher "
  1753. "guard priority, so not upgrading.",
  1754. n_waiting, n_blockers_found);
  1755. return 0;
  1756. }
  1757. /* Okay. We have a best waiting circuit, and we aren't waiting for
  1758. anything better. Add all circuits with that priority to the
  1759. list, and call them COMPLETE. */
  1760. int n_succeeded = 0;
  1761. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  1762. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  1763. if (state == NULL)
  1764. continue;
  1765. if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
  1766. continue;
  1767. if (circ_state_has_higher_priority(best_waiting_circuit, circ))
  1768. continue;
  1769. state->state = GUARD_CIRC_STATE_COMPLETE;
  1770. state->state_set_at = approx_time();
  1771. smartlist_add(newly_complete_out, circ);
  1772. ++n_succeeded;
  1773. } SMARTLIST_FOREACH_END(circ);
  1774. log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  1775. "%d guard-stalled, %d complete. %d of the guard-stalled "
  1776. "circuit(s) had high enough priority to upgrade.",
  1777. n_waiting, n_complete, n_succeeded);
  1778. tor_assert_nonfatal(n_succeeded >= 1);
  1779. return 1;
  1780. }
  1781. /**
  1782. * Return true iff the circuit whose state is <b>guard_state</b> should
  1783. * expire.
  1784. */
  1785. int
  1786. entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
  1787. {
  1788. if (guard_state == NULL)
  1789. return 0;
  1790. const time_t expire_if_waiting_since =
  1791. approx_time() - get_nonprimary_guard_idle_timeout();
  1792. return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
  1793. && guard_state->state_set_at < expire_if_waiting_since);
  1794. }
  1795. /**
  1796. * Update all derived pieces of the guard selection state in <b>gs</b>.
  1797. * Return true iff we should stop using all previously generated circuits.
  1798. */
  1799. int
  1800. entry_guards_update_all(guard_selection_t *gs)
  1801. {
  1802. sampled_guards_update_from_consensus(gs);
  1803. entry_guards_update_filtered_sets(gs);
  1804. entry_guards_update_confirmed(gs);
  1805. entry_guards_update_primary(gs);
  1806. return 0;
  1807. }
  1808. /**
  1809. * Return a newly allocated string for encoding the persistent parts of
  1810. * <b>guard</b> to the state file.
  1811. */
  1812. STATIC char *
  1813. entry_guard_encode_for_state(entry_guard_t *guard)
  1814. {
  1815. /*
  1816. * The meta-format we use is K=V K=V K=V... where K can be any
  1817. * characters excepts space and =, and V can be any characters except
  1818. * space. The order of entries is not allowed to matter.
  1819. * Unrecognized K=V entries are persisted; recognized but erroneous
  1820. * entries are corrected.
  1821. */
  1822. smartlist_t *result = smartlist_new();
  1823. char tbuf[ISO_TIME_LEN+1];
  1824. tor_assert(guard);
  1825. smartlist_add_asprintf(result, "in=%s", guard->selection_name);
  1826. smartlist_add_asprintf(result, "rsa_id=%s",
  1827. hex_str(guard->identity, DIGEST_LEN));
  1828. if (strlen(guard->nickname)) {
  1829. smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
  1830. }
  1831. format_iso_time_nospace(tbuf, guard->sampled_on_date);
  1832. smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
  1833. if (guard->sampled_by_version) {
  1834. smartlist_add_asprintf(result, "sampled_by=%s",
  1835. guard->sampled_by_version);
  1836. }
  1837. if (guard->unlisted_since_date > 0) {
  1838. format_iso_time_nospace(tbuf, guard->unlisted_since_date);
  1839. smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
  1840. }
  1841. smartlist_add_asprintf(result, "listed=%d",
  1842. (int)guard->currently_listed);
  1843. if (guard->confirmed_idx >= 0) {
  1844. format_iso_time_nospace(tbuf, guard->confirmed_on_date);
  1845. smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
  1846. smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
  1847. }
  1848. const double EPSILON = 1.0e-6;
  1849. /* Make a copy of the pathbias object, since we will want to update
  1850. some of them */
  1851. guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
  1852. pb->use_successes = pathbias_get_use_success_count(guard);
  1853. pb->successful_circuits_closed = pathbias_get_close_success_count(guard);
  1854. #define PB_FIELD(field) do { \
  1855. if (pb->field >= EPSILON) { \
  1856. smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
  1857. } \
  1858. } while (0)
  1859. PB_FIELD(use_attempts);
  1860. PB_FIELD(use_successes);
  1861. PB_FIELD(circ_attempts);
  1862. PB_FIELD(circ_successes);
  1863. PB_FIELD(successful_circuits_closed);
  1864. PB_FIELD(collapsed_circuits);
  1865. PB_FIELD(unusable_circuits);
  1866. PB_FIELD(timeouts);
  1867. tor_free(pb);
  1868. #undef PB_FIELD
  1869. if (guard->extra_state_fields)
  1870. smartlist_add_strdup(result, guard->extra_state_fields);
  1871. char *joined = smartlist_join_strings(result, " ", 0, NULL);
  1872. SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
  1873. smartlist_free(result);
  1874. return joined;
  1875. }
  1876. /**
  1877. * Given a string generated by entry_guard_encode_for_state(), parse it
  1878. * (if possible) and return an entry_guard_t object for it. Return NULL
  1879. * on complete failure.
  1880. */
  1881. STATIC entry_guard_t *
  1882. entry_guard_parse_from_state(const char *s)
  1883. {
  1884. /* Unrecognized entries get put in here. */
  1885. smartlist_t *extra = smartlist_new();
  1886. /* These fields get parsed from the string. */
  1887. char *in = NULL;
  1888. char *rsa_id = NULL;
  1889. char *nickname = NULL;
  1890. char *sampled_on = NULL;
  1891. char *sampled_by = NULL;
  1892. char *unlisted_since = NULL;
  1893. char *listed = NULL;
  1894. char *confirmed_on = NULL;
  1895. char *confirmed_idx = NULL;
  1896. // pathbias
  1897. char *pb_use_attempts = NULL;
  1898. char *pb_use_successes = NULL;
  1899. char *pb_circ_attempts = NULL;
  1900. char *pb_circ_successes = NULL;
  1901. char *pb_successful_circuits_closed = NULL;
  1902. char *pb_collapsed_circuits = NULL;
  1903. char *pb_unusable_circuits = NULL;
  1904. char *pb_timeouts = NULL;
  1905. /* Split up the entries. Put the ones we know about in strings and the
  1906. * rest in "extra". */
  1907. {
  1908. smartlist_t *entries = smartlist_new();
  1909. strmap_t *vals = strmap_new(); // Maps keyword to location
  1910. #define FIELD(f) \
  1911. strmap_set(vals, #f, &f);
  1912. FIELD(in);
  1913. FIELD(rsa_id);
  1914. FIELD(nickname);
  1915. FIELD(sampled_on);
  1916. FIELD(sampled_by);
  1917. FIELD(unlisted_since);
  1918. FIELD(listed);
  1919. FIELD(confirmed_on);
  1920. FIELD(confirmed_idx);
  1921. FIELD(pb_use_attempts);
  1922. FIELD(pb_use_successes);
  1923. FIELD(pb_circ_attempts);
  1924. FIELD(pb_circ_successes);
  1925. FIELD(pb_successful_circuits_closed);
  1926. FIELD(pb_collapsed_circuits);
  1927. FIELD(pb_unusable_circuits);
  1928. FIELD(pb_timeouts);
  1929. #undef FIELD
  1930. smartlist_split_string(entries, s, " ",
  1931. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1932. SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
  1933. const char *eq = strchr(entry, '=');
  1934. if (!eq) {
  1935. smartlist_add(extra, entry);
  1936. continue;
  1937. }
  1938. char *key = tor_strndup(entry, eq-entry);
  1939. char **target = strmap_get(vals, key);
  1940. if (target == NULL || *target != NULL) {
  1941. /* unrecognized or already set */
  1942. smartlist_add(extra, entry);
  1943. tor_free(key);
  1944. continue;
  1945. }
  1946. *target = tor_strdup(eq+1);
  1947. tor_free(key);
  1948. tor_free(entry);
  1949. } SMARTLIST_FOREACH_END(entry);
  1950. smartlist_free(entries);
  1951. strmap_free(vals, NULL);
  1952. }
  1953. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  1954. if (in == NULL) {
  1955. log_warn(LD_CIRC, "Guard missing 'in' field");
  1956. goto err;
  1957. }
  1958. guard->selection_name = in;
  1959. in = NULL;
  1960. if (rsa_id == NULL) {
  1961. log_warn(LD_CIRC, "Guard missing RSA ID field");
  1962. goto err;
  1963. }
  1964. /* Process the identity and nickname. */
  1965. if (base16_decode(guard->identity, sizeof(guard->identity),
  1966. rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
  1967. log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
  1968. goto err;
  1969. }
  1970. if (nickname) {
  1971. strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  1972. } else {
  1973. guard->nickname[0]='$';
  1974. base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
  1975. guard->identity, DIGEST_LEN);
  1976. }
  1977. /* Process the various time fields. */
  1978. #define HANDLE_TIME(field) do { \
  1979. if (field) { \
  1980. int r = parse_iso_time_nospace(field, &field ## _time); \
  1981. if (r < 0) { \
  1982. log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
  1983. #field, escaped(field)); \
  1984. field##_time = -1; \
  1985. } \
  1986. } \
  1987. } while (0)
  1988. time_t sampled_on_time = 0;
  1989. time_t unlisted_since_time = 0;
  1990. time_t confirmed_on_time = 0;
  1991. HANDLE_TIME(sampled_on);
  1992. HANDLE_TIME(unlisted_since);
  1993. HANDLE_TIME(confirmed_on);
  1994. if (sampled_on_time <= 0)
  1995. sampled_on_time = approx_time();
  1996. if (unlisted_since_time < 0)
  1997. unlisted_since_time = 0;
  1998. if (confirmed_on_time < 0)
  1999. confirmed_on_time = 0;
  2000. #undef HANDLE_TIME
  2001. guard->sampled_on_date = sampled_on_time;
  2002. guard->unlisted_since_date = unlisted_since_time;
  2003. guard->confirmed_on_date = confirmed_on_time;
  2004. /* Take sampled_by_version verbatim. */
  2005. guard->sampled_by_version = sampled_by;
  2006. sampled_by = NULL; /* prevent free */
  2007. // XXXX -- prop271 spec deviation -- we do not require sampled_by_version
  2008. /* Listed is a boolean */
  2009. if (listed && strcmp(listed, "0"))
  2010. guard->currently_listed = 1;
  2011. /* The index is a nonnegative integer. */
  2012. guard->confirmed_idx = -1;
  2013. if (confirmed_idx) {
  2014. int ok=1;
  2015. long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
  2016. if (! ok) {
  2017. log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
  2018. escaped(confirmed_idx));
  2019. } else {
  2020. guard->confirmed_idx = (int)idx;
  2021. }
  2022. }
  2023. /* Anything we didn't recognize gets crammed together */
  2024. if (smartlist_len(extra) > 0) {
  2025. guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
  2026. }
  2027. /* initialize non-persistent fields */
  2028. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  2029. #define PB_FIELD(field) \
  2030. do { \
  2031. if (pb_ ## field) { \
  2032. int ok = 1; \
  2033. double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
  2034. if (! ok) { \
  2035. log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
  2036. #field, pb_ ## field); \
  2037. } else { \
  2038. guard->pb.field = r; \
  2039. } \
  2040. } \
  2041. } while (0)
  2042. PB_FIELD(use_attempts);
  2043. PB_FIELD(use_successes);
  2044. PB_FIELD(circ_attempts);
  2045. PB_FIELD(circ_successes);
  2046. PB_FIELD(successful_circuits_closed);
  2047. PB_FIELD(collapsed_circuits);
  2048. PB_FIELD(unusable_circuits);
  2049. PB_FIELD(timeouts);
  2050. #undef PB_FIELD
  2051. pathbias_check_use_success_count(guard);
  2052. pathbias_check_close_success_count(guard);
  2053. /* We update everything on this guard later, after we've parsed
  2054. * everything. */
  2055. goto done;
  2056. err:
  2057. // only consider it an error if the guard state was totally unparseable.
  2058. entry_guard_free(guard);
  2059. guard = NULL;
  2060. done:
  2061. tor_free(in);
  2062. tor_free(rsa_id);
  2063. tor_free(nickname);
  2064. tor_free(sampled_on);
  2065. tor_free(sampled_by);
  2066. tor_free(unlisted_since);
  2067. tor_free(listed);
  2068. tor_free(confirmed_on);
  2069. tor_free(confirmed_idx);
  2070. tor_free(pb_use_attempts);
  2071. tor_free(pb_use_successes);
  2072. tor_free(pb_circ_attempts);
  2073. tor_free(pb_circ_successes);
  2074. tor_free(pb_successful_circuits_closed);
  2075. tor_free(pb_collapsed_circuits);
  2076. tor_free(pb_unusable_circuits);
  2077. tor_free(pb_timeouts);
  2078. SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
  2079. smartlist_free(extra);
  2080. return guard;
  2081. }
  2082. /**
  2083. * Replace the Guards entries in <b>state</b> with a list of all our
  2084. * non-legacy sampled guards.
  2085. */
  2086. static void
  2087. entry_guards_update_guards_in_state(or_state_t *state)
  2088. {
  2089. if (!guard_contexts)
  2090. return;
  2091. config_line_t *lines = NULL;
  2092. config_line_t **nextline = &lines;
  2093. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2094. if (!strcmp(gs->name, "legacy"))
  2095. continue; /* This is encoded differently. */
  2096. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  2097. *nextline = tor_malloc_zero(sizeof(config_line_t));
  2098. (*nextline)->key = tor_strdup("Guard");
  2099. (*nextline)->value = entry_guard_encode_for_state(guard);
  2100. nextline = &(*nextline)->next;
  2101. } SMARTLIST_FOREACH_END(guard);
  2102. } SMARTLIST_FOREACH_END(gs);
  2103. config_free_lines(state->Guard);
  2104. state->Guard = lines;
  2105. }
  2106. /**
  2107. * Replace our non-legacy sampled guards from the Guards entries in
  2108. * <b>state</b>. Return 0 on success, -1 on failure. (If <b>set</b> is
  2109. * true, replace nothing -- only check whether replacing would work.)
  2110. */
  2111. static int
  2112. entry_guards_load_guards_from_state(or_state_t *state, int set)
  2113. {
  2114. const config_line_t *line = state->Guard;
  2115. int n_errors = 0;
  2116. if (!guard_contexts)
  2117. guard_contexts = smartlist_new();
  2118. /* Wipe all our existing guard info. (we shouldn't have any, but
  2119. * let's be safe.) */
  2120. if (set) {
  2121. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2122. if (!strcmp(gs->name, "legacy"))
  2123. continue;
  2124. guard_selection_free(gs);
  2125. if (curr_guard_context == gs)
  2126. curr_guard_context = NULL;
  2127. SMARTLIST_DEL_CURRENT(guard_contexts, gs);
  2128. } SMARTLIST_FOREACH_END(gs);
  2129. }
  2130. for ( ; line != NULL; line = line->next) {
  2131. entry_guard_t *guard = entry_guard_parse_from_state(line->value);
  2132. if (guard == NULL) {
  2133. ++n_errors;
  2134. continue;
  2135. }
  2136. tor_assert(guard->selection_name);
  2137. if (!strcmp(guard->selection_name, "legacy")) {
  2138. ++n_errors;
  2139. entry_guard_free(guard);
  2140. continue;
  2141. }
  2142. if (set) {
  2143. guard_selection_t *gs;
  2144. gs = get_guard_selection_by_name(guard->selection_name,
  2145. GS_TYPE_INFER, 1);
  2146. tor_assert(gs);
  2147. smartlist_add(gs->sampled_entry_guards, guard);
  2148. } else {
  2149. entry_guard_free(guard);
  2150. }
  2151. }
  2152. if (set) {
  2153. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2154. if (!strcmp(gs->name, "legacy"))
  2155. continue;
  2156. entry_guards_update_all(gs);
  2157. } SMARTLIST_FOREACH_END(gs);
  2158. }
  2159. return n_errors ? -1 : 0;
  2160. }
  2161. /* XXXXX ----------------------------------------------- */
  2162. /* XXXXX prop271 ----- end of new-for-prop271 code ----- */
  2163. /* XXXXX ----------------------------------------------- */
  2164. /**
  2165. * @name Constants for old (pre-prop271) guard selection algorithm.
  2166. */
  2167. /**@{*/
  2168. /* Default number of entry guards in the case where the NumEntryGuards
  2169. * consensus parameter is not set */
  2170. #define DEFAULT_N_GUARDS 1
  2171. /* Minimum and maximum number of entry guards (in case the NumEntryGuards
  2172. * consensus parameter is set). */
  2173. #define MIN_N_GUARDS 1
  2174. #define MAX_N_GUARDS 10
  2175. /** Largest amount that we'll backdate chosen_on_date */
  2176. #define CHOSEN_ON_DATE_SLOP (30*86400)
  2177. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  2178. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  2179. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  2180. /**}@*/
  2181. /**
  2182. * @name Networkstatus parameters for old (pre-prop271) guard selection
  2183. */
  2184. /**@}*/
  2185. /** Choose how many entry guards or directory guards we'll use. If
  2186. * <b>for_directory</b> is true, we return how many directory guards to
  2187. * use; else we return how many entry guards to use. */
  2188. STATIC int
  2189. decide_num_guards(const or_options_t *options, int for_directory)
  2190. {
  2191. if (for_directory) {
  2192. int answer;
  2193. if (options->NumDirectoryGuards != 0)
  2194. return options->NumDirectoryGuards;
  2195. answer = networkstatus_get_param(NULL, "NumDirectoryGuards", 0, 0, 10);
  2196. if (answer) /* non-zero means use the consensus value */
  2197. return answer;
  2198. }
  2199. if (options->NumEntryGuards)
  2200. return options->NumEntryGuards;
  2201. /* Use the value from the consensus, or 3 if no guidance. */
  2202. return networkstatus_get_param(NULL, "NumEntryGuards", DEFAULT_N_GUARDS,
  2203. MIN_N_GUARDS, MAX_N_GUARDS);
  2204. }
  2205. /** Check whether the entry guard <b>e</b> is usable, given the directory
  2206. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  2207. * configuration (in <b>options</b>). Set <b>e</b>->bad_since
  2208. * accordingly. Return true iff the entry guard's status changes.
  2209. *
  2210. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  2211. */
  2212. static int
  2213. entry_guard_set_status(entry_guard_t *e, const node_t *node,
  2214. time_t now, const or_options_t *options,
  2215. const char **reason)
  2216. {
  2217. char buf[HEX_DIGEST_LEN+1];
  2218. int changed = 0;
  2219. *reason = NULL;
  2220. /* Do we want to mark this guard as bad? */
  2221. if (!node)
  2222. *reason = "unlisted";
  2223. else if (!node->is_running)
  2224. *reason = "down";
  2225. else if (options->UseBridges && (!node->ri ||
  2226. node->ri->purpose != ROUTER_PURPOSE_BRIDGE))
  2227. *reason = "not a bridge";
  2228. else if (options->UseBridges && !node_is_a_configured_bridge(node))
  2229. *reason = "not a configured bridge";
  2230. else if (!options->UseBridges && !node->is_possible_guard &&
  2231. !routerset_contains_node(options->EntryNodes,node))
  2232. *reason = "not recommended as a guard";
  2233. else if (routerset_contains_node(options->ExcludeNodes, node))
  2234. *reason = "excluded";
  2235. /* We only care about OR connection connectivity for entry guards. */
  2236. else if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
  2237. *reason = "unreachable by config";
  2238. else if (e->pb.path_bias_disabled)
  2239. *reason = "path-biased";
  2240. if (*reason && ! e->bad_since) {
  2241. /* Router is newly bad. */
  2242. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  2243. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  2244. e->nickname, buf, *reason);
  2245. e->bad_since = now;
  2246. control_event_guard(e->nickname, e->identity, "BAD");
  2247. changed = 1;
  2248. } else if (!*reason && e->bad_since) {
  2249. /* There's nothing wrong with the router any more. */
  2250. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  2251. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  2252. "marking as ok.", e->nickname, buf);
  2253. e->bad_since = 0;
  2254. control_event_guard(e->nickname, e->identity, "GOOD");
  2255. changed = 1;
  2256. }
  2257. if (node) {
  2258. int is_dir = node_is_dir(node);
  2259. if (options->UseBridges && node_is_a_configured_bridge(node))
  2260. is_dir = 1;
  2261. if (e->is_dir_cache != is_dir) {
  2262. e->is_dir_cache = is_dir;
  2263. changed = 1;
  2264. }
  2265. }
  2266. return changed;
  2267. }
  2268. /** Return true iff enough time has passed since we last tried to connect
  2269. * to the unreachable guard <b>e</b> that we're willing to try again. */
  2270. STATIC int
  2271. entry_is_time_to_retry(const entry_guard_t *e, time_t now)
  2272. {
  2273. struct guard_retry_period_s {
  2274. time_t period_duration;
  2275. time_t interval_during_period;
  2276. };
  2277. struct guard_retry_period_s periods[] = {
  2278. { 6*60*60, 60*60 }, /* For first 6 hrs., retry hourly; */
  2279. { 3*24*60*60, 4*60*60 }, /* Then retry every 4 hrs. until the
  2280. 3-day mark; */
  2281. { 7*24*60*60, 18*60*60 }, /* After 3 days, retry every 18 hours until
  2282. 1 week mark. */
  2283. { TIME_MAX, 36*60*60 } /* After 1 week, retry every 36 hours. */
  2284. };
  2285. time_t ith_deadline_for_retry;
  2286. time_t unreachable_for;
  2287. unsigned i;
  2288. if (e->last_attempted < e->unreachable_since)
  2289. return 1;
  2290. unreachable_for = now - e->unreachable_since;
  2291. for (i = 0; i < ARRAY_LENGTH(periods); i++) {
  2292. if (unreachable_for <= periods[i].period_duration) {
  2293. ith_deadline_for_retry = e->last_attempted +
  2294. periods[i].interval_during_period;
  2295. return (now > ith_deadline_for_retry);
  2296. }
  2297. }
  2298. return 0;
  2299. }
  2300. /** Return the node corresponding to <b>e</b>, if <b>e</b> is
  2301. * working well enough that we are willing to use it as an entry
  2302. * right now. (Else return NULL.) In particular, it must be
  2303. * - Listed as either up or never yet contacted;
  2304. * - Present in the routerlist;
  2305. * - Listed as 'stable' or 'fast' by the current dirserver consensus,
  2306. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
  2307. * (unless it's a configured EntryNode);
  2308. * - Allowed by our current ReachableORAddresses config option; and
  2309. * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
  2310. * is true).
  2311. *
  2312. * If the answer is no, set *<b>msg</b> to an explanation of why.
  2313. *
  2314. * If need_descriptor is true, only return the node if we currently have
  2315. * a descriptor (routerinfo or microdesc) for it.
  2316. */
  2317. STATIC const node_t *
  2318. entry_is_live(const entry_guard_t *e, entry_is_live_flags_t flags,
  2319. const char **msg)
  2320. {
  2321. const node_t *node;
  2322. const or_options_t *options = get_options();
  2323. int need_uptime = (flags & ENTRY_NEED_UPTIME) != 0;
  2324. int need_capacity = (flags & ENTRY_NEED_CAPACITY) != 0;
  2325. const int assume_reachable = (flags & ENTRY_ASSUME_REACHABLE) != 0;
  2326. const int need_descriptor = (flags & ENTRY_NEED_DESCRIPTOR) != 0;
  2327. tor_assert(msg);
  2328. if (e->pb.path_bias_disabled) {
  2329. *msg = "path-biased";
  2330. return NULL;
  2331. }
  2332. if (e->bad_since) {
  2333. *msg = "bad";
  2334. return NULL;
  2335. }
  2336. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  2337. if (!assume_reachable && !e->can_retry &&
  2338. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
  2339. *msg = "unreachable";
  2340. return NULL;
  2341. }
  2342. node = node_get_by_id(e->identity);
  2343. if (!node) {
  2344. *msg = "no node info";
  2345. return NULL;
  2346. }
  2347. if (need_descriptor && !node_has_descriptor(node)) {
  2348. *msg = "no descriptor";
  2349. return NULL;
  2350. }
  2351. if (get_options()->UseBridges) {
  2352. if (node_get_purpose(node) != ROUTER_PURPOSE_BRIDGE) {
  2353. *msg = "not a bridge";
  2354. return NULL;
  2355. }
  2356. if (!node_is_a_configured_bridge(node)) {
  2357. *msg = "not a configured bridge";
  2358. return NULL;
  2359. }
  2360. } else { /* !get_options()->UseBridges */
  2361. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  2362. *msg = "not general-purpose";
  2363. return NULL;
  2364. }
  2365. }
  2366. if (routerset_contains_node(options->EntryNodes, node)) {
  2367. /* they asked for it, they get it */
  2368. need_uptime = need_capacity = 0;
  2369. }
  2370. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  2371. *msg = "not fast/stable";
  2372. return NULL;
  2373. }
  2374. if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0)) {
  2375. *msg = "unreachable by config";
  2376. return NULL;
  2377. }
  2378. return node;
  2379. }
  2380. /** Return the number of entry guards that we think are usable, in the
  2381. * context of the given guard_selection_t */
  2382. int
  2383. num_live_entry_guards_for_guard_selection(guard_selection_t *gs,
  2384. int for_directory)
  2385. {
  2386. int n = 0;
  2387. const char *msg;
  2388. tor_assert(gs != NULL);
  2389. /* Set the entry node attributes we are interested in. */
  2390. entry_is_live_flags_t entry_flags = ENTRY_NEED_CAPACITY;
  2391. if (!for_directory) {
  2392. entry_flags |= ENTRY_NEED_DESCRIPTOR;
  2393. }
  2394. if (!(gs->chosen_entry_guards)) {
  2395. return 0;
  2396. }
  2397. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, entry) {
  2398. if (for_directory && !entry->is_dir_cache)
  2399. continue;
  2400. if (entry_is_live(entry, entry_flags, &msg))
  2401. ++n;
  2402. } SMARTLIST_FOREACH_END(entry);
  2403. return n;
  2404. }
  2405. /** Return the number of entry guards that we think are usable, for the
  2406. * default guard selection */
  2407. int
  2408. num_live_entry_guards(int for_directory)
  2409. {
  2410. return num_live_entry_guards_for_guard_selection(
  2411. get_guard_selection_info(), for_directory);
  2412. }
  2413. /** If <b>digest</b> matches the identity of any node in the
  2414. * entry_guards list for the provided guard selection state,
  2415. return that node. Else return NULL. */
  2416. entry_guard_t *
  2417. entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
  2418. const char *digest)
  2419. {
  2420. tor_assert(gs != NULL);
  2421. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry,
  2422. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  2423. return entry;
  2424. );
  2425. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, entry,
  2426. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  2427. return entry;
  2428. );
  2429. return NULL;
  2430. }
  2431. /** Return the node_t associated with a single entry_guard_t. May
  2432. * return NULL if the guard is not currently in the consensus. */
  2433. const node_t *
  2434. entry_guard_find_node(const entry_guard_t *guard)
  2435. {
  2436. tor_assert(guard);
  2437. return node_get_by_id(guard->identity);
  2438. }
  2439. /** If <b>digest</b> matches the identity of any node in the
  2440. * entry_guards list for the default guard selection state,
  2441. return that node. Else return NULL. */
  2442. entry_guard_t *
  2443. entry_guard_get_by_id_digest(const char *digest)
  2444. {
  2445. return entry_guard_get_by_id_digest_for_guard_selection(
  2446. get_guard_selection_info(), digest);
  2447. }
  2448. /** Dump a description of our list of entry guards in the given guard
  2449. * selection context to the log at level <b>severity</b>. */
  2450. static void
  2451. log_entry_guards_for_guard_selection(guard_selection_t *gs, int severity)
  2452. {
  2453. smartlist_t *elements = smartlist_new();
  2454. char *s;
  2455. /*
  2456. * TODO this should probably log more info about prop-271 state too
  2457. * when it's implemented.
  2458. */
  2459. tor_assert(gs != NULL);
  2460. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e)
  2461. {
  2462. const char *msg = NULL;
  2463. if (entry_is_live(e, ENTRY_NEED_CAPACITY, &msg))
  2464. smartlist_add_asprintf(elements, "%s [%s] (up %s)",
  2465. e->nickname,
  2466. hex_str(e->identity, DIGEST_LEN),
  2467. e->made_contact ? "made-contact" : "never-contacted");
  2468. else
  2469. smartlist_add_asprintf(elements, "%s [%s] (%s, %s)",
  2470. e->nickname,
  2471. hex_str(e->identity, DIGEST_LEN),
  2472. msg,
  2473. e->made_contact ? "made-contact" : "never-contacted");
  2474. }
  2475. SMARTLIST_FOREACH_END(e);
  2476. s = smartlist_join_strings(elements, ",", 0, NULL);
  2477. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  2478. smartlist_free(elements);
  2479. log_fn(severity,LD_CIRC,"%s",s);
  2480. tor_free(s);
  2481. }
  2482. /** Called when one or more guards that we would previously have used for some
  2483. * purpose are no longer in use because a higher-priority guard has become
  2484. * usable again. */
  2485. static void
  2486. control_event_guard_deferred(void)
  2487. {
  2488. /* XXXX We don't actually have a good way to figure out _how many_ entries
  2489. * are live for some purpose. We need an entry_is_even_slightly_live()
  2490. * function for this to work right. NumEntryGuards isn't reliable: if we
  2491. * need guards with weird properties, we can have more than that number
  2492. * live.
  2493. **/
  2494. #if 0
  2495. int n = 0;
  2496. const char *msg;
  2497. const or_options_t *options = get_options();
  2498. if (!entry_guards)
  2499. return;
  2500. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2501. {
  2502. if (entry_is_live(entry, 0, 1, 0, &msg)) {
  2503. if (n++ == options->NumEntryGuards) {
  2504. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  2505. return;
  2506. }
  2507. }
  2508. });
  2509. #endif
  2510. }
  2511. /** Add a new (preferably stable and fast) router to our chosen_entry_guards
  2512. * list for the supplied guard selection. Return a pointer to the router if
  2513. * we succeed, or NULL if we can't find any more suitable entries.
  2514. *
  2515. * If <b>chosen</b> is defined, use that one, and if it's not
  2516. * already in our entry_guards list, put it at the *beginning*.
  2517. * Else, put the one we pick at the end of the list. */
  2518. STATIC const node_t *
  2519. add_an_entry_guard(guard_selection_t *gs,
  2520. const node_t *chosen, int reset_status, int prepend,
  2521. int for_discovery, int for_directory)
  2522. {
  2523. const node_t *node;
  2524. entry_guard_t *entry;
  2525. tor_assert(gs != NULL);
  2526. tor_assert(gs->chosen_entry_guards != NULL);
  2527. if (chosen) {
  2528. node = chosen;
  2529. entry = entry_guard_get_by_id_digest_for_guard_selection(gs,
  2530. node->identity);
  2531. if (entry) {
  2532. if (reset_status) {
  2533. entry->bad_since = 0;
  2534. entry->can_retry = 1;
  2535. }
  2536. entry->is_dir_cache = node_is_dir(node);
  2537. if (get_options()->UseBridges && node_is_a_configured_bridge(node))
  2538. entry->is_dir_cache = 1;
  2539. return NULL;
  2540. }
  2541. } else if (!for_directory) {
  2542. node = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL, NULL);
  2543. if (!node)
  2544. return NULL;
  2545. } else {
  2546. const routerstatus_t *rs;
  2547. rs = router_pick_directory_server(MICRODESC_DIRINFO|V3_DIRINFO,
  2548. PDS_FOR_GUARD);
  2549. if (!rs)
  2550. return NULL;
  2551. node = node_get_by_id(rs->identity_digest);
  2552. if (!node)
  2553. return NULL;
  2554. }
  2555. if (entry_guard_get_by_id_digest_for_guard_selection(gs, node->identity)
  2556. != NULL) {
  2557. log_info(LD_CIRC, "I was about to add a duplicate entry guard.");
  2558. /* This can happen if we choose a guard, then the node goes away, then
  2559. * comes back. */
  2560. return NULL;
  2561. }
  2562. entry = tor_malloc_zero(sizeof(entry_guard_t));
  2563. log_info(LD_CIRC, "Chose %s as new entry guard.",
  2564. node_describe(node));
  2565. strlcpy(entry->nickname, node_get_nickname(node), sizeof(entry->nickname));
  2566. memcpy(entry->identity, node->identity, DIGEST_LEN);
  2567. entry->is_dir_cache = node_is_dir(node);
  2568. if (get_options()->UseBridges && node_is_a_configured_bridge(node))
  2569. entry->is_dir_cache = 1;
  2570. /* Choose expiry time smudged over the past month. The goal here
  2571. * is to a) spread out when Tor clients rotate their guards, so they
  2572. * don't all select them on the same day, and b) avoid leaving a
  2573. * precise timestamp in the state file about when we first picked
  2574. * this guard. For details, see the Jan 2010 or-dev thread. */
  2575. time_t now = time(NULL);
  2576. entry->chosen_on_date = crypto_rand_time_range(now - 3600*24*30, now);
  2577. entry->chosen_by_version = tor_strdup(VERSION);
  2578. /* Are we picking this guard because all of our current guards are
  2579. * down so we need another one (for_discovery is 1), or because we
  2580. * decided we need more variety in our guard list (for_discovery is 0)?
  2581. *
  2582. * Currently we hack this behavior into place by setting "made_contact"
  2583. * for guards of the latter variety, so we'll be willing to use any of
  2584. * them right off the bat.
  2585. */
  2586. if (!for_discovery)
  2587. entry->made_contact = 1;
  2588. if (prepend)
  2589. smartlist_insert(gs->chosen_entry_guards, 0, entry);
  2590. else
  2591. smartlist_add(gs->chosen_entry_guards, entry);
  2592. control_event_guard(entry->nickname, entry->identity, "NEW");
  2593. control_event_guard_deferred();
  2594. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2595. return node;
  2596. }
  2597. /** Entry point for bridges.c to add a bridge as guard.
  2598. *
  2599. * XXXX prop271 refactor.*/
  2600. void
  2601. add_bridge_as_entry_guard(guard_selection_t *gs,
  2602. const node_t *chosen)
  2603. {
  2604. add_an_entry_guard(gs, chosen, 1, 1, 0, 0);
  2605. }
  2606. /**
  2607. * Return the minimum lifetime of working entry guard, in seconds,
  2608. * as given in the consensus networkstatus. (Plus CHOSEN_ON_DATE_SLOP,
  2609. * so that we can do the chosen_on_date randomization while achieving the
  2610. * desired minimum lifetime.)
  2611. */
  2612. static int32_t
  2613. guards_get_lifetime(void)
  2614. {
  2615. const or_options_t *options = get_options();
  2616. #define DFLT_GUARD_LIFETIME (86400 * 60) /* Two months. */
  2617. #define MIN_GUARD_LIFETIME (86400 * 30) /* One months. */
  2618. #define MAX_GUARD_LIFETIME (86400 * 1826) /* Five years. */
  2619. if (options->GuardLifetime >= 1) {
  2620. return CLAMP(MIN_GUARD_LIFETIME,
  2621. options->GuardLifetime,
  2622. MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
  2623. }
  2624. return networkstatus_get_param(NULL, "GuardLifetime",
  2625. DFLT_GUARD_LIFETIME,
  2626. MIN_GUARD_LIFETIME,
  2627. MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
  2628. }
  2629. /** If the use of entry guards is configured, choose more entry guards
  2630. * until we have enough in the list. */
  2631. static void
  2632. pick_entry_guards(guard_selection_t *gs,
  2633. const or_options_t *options,
  2634. int for_directory)
  2635. {
  2636. int changed = 0;
  2637. const int num_needed = decide_num_guards(options, for_directory);
  2638. tor_assert(gs != NULL);
  2639. tor_assert(gs->chosen_entry_guards != NULL);
  2640. while (num_live_entry_guards_for_guard_selection(gs, for_directory)
  2641. < num_needed) {
  2642. if (!add_an_entry_guard(gs, NULL, 0, 0, 0, for_directory))
  2643. break;
  2644. changed = 1;
  2645. }
  2646. if (changed)
  2647. entry_guards_changed_for_guard_selection(gs);
  2648. }
  2649. /** Release all storage held by <b>e</b>. */
  2650. STATIC void
  2651. entry_guard_free(entry_guard_t *e)
  2652. {
  2653. if (!e)
  2654. return;
  2655. entry_guard_handles_clear(e);
  2656. tor_free(e->chosen_by_version);
  2657. tor_free(e->sampled_by_version);
  2658. tor_free(e->extra_state_fields);
  2659. tor_free(e->selection_name);
  2660. tor_free(e);
  2661. }
  2662. /** Remove from a guard selection context any entry guard which was selected
  2663. * by an unknown version of Tor, or which was selected by a version of Tor
  2664. * that's known to select entry guards badly, or which was selected more 2
  2665. * months ago. */
  2666. /* XXXX The "obsolete guards" and "chosen long ago guards" things should
  2667. * probably be different functions. */
  2668. static int
  2669. remove_obsolete_entry_guards(guard_selection_t *gs, time_t now)
  2670. {
  2671. int changed = 0, i;
  2672. int32_t guard_lifetime = guards_get_lifetime();
  2673. tor_assert(gs != NULL);
  2674. if (!(gs->chosen_entry_guards)) goto done;
  2675. for (i = 0; i < smartlist_len(gs->chosen_entry_guards); ++i) {
  2676. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, i);
  2677. const char *ver = entry->chosen_by_version;
  2678. const char *msg = NULL;
  2679. tor_version_t v;
  2680. int version_is_bad = 0, date_is_bad = 0;
  2681. if (!ver) {
  2682. msg = "does not say what version of Tor it was selected by";
  2683. version_is_bad = 1;
  2684. } else if (tor_version_parse(ver, &v)) {
  2685. msg = "does not seem to be from any recognized version of Tor";
  2686. version_is_bad = 1;
  2687. }
  2688. if (!version_is_bad && entry->chosen_on_date + guard_lifetime < now) {
  2689. /* It's been too long since the date listed in our state file. */
  2690. msg = "was selected several months ago";
  2691. date_is_bad = 1;
  2692. }
  2693. if (version_is_bad || date_is_bad) { /* we need to drop it */
  2694. char dbuf[HEX_DIGEST_LEN+1];
  2695. tor_assert(msg);
  2696. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2697. log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
  2698. "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
  2699. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  2700. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2701. entry_guard_free(entry);
  2702. smartlist_del_keeporder(gs->chosen_entry_guards, i--);
  2703. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2704. changed = 1;
  2705. }
  2706. }
  2707. done:
  2708. return changed ? 1 : 0;
  2709. }
  2710. /** Remove all entry guards from this guard selection context that have
  2711. * been down or unlisted for so long that we don't think they'll come up
  2712. * again. Return 1 if we removed any, or 0 if we did nothing. */
  2713. static int
  2714. remove_dead_entry_guards(guard_selection_t *gs, time_t now)
  2715. {
  2716. char dbuf[HEX_DIGEST_LEN+1];
  2717. char tbuf[ISO_TIME_LEN+1];
  2718. int i;
  2719. int changed = 0;
  2720. tor_assert(gs != NULL);
  2721. if (!(gs->chosen_entry_guards)) goto done;
  2722. for (i = 0; i < smartlist_len(gs->chosen_entry_guards); ) {
  2723. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, i);
  2724. if (entry->bad_since &&
  2725. ! entry->pb.path_bias_disabled &&
  2726. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  2727. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2728. format_local_iso_time(tbuf, entry->bad_since);
  2729. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  2730. "since %s local time; removing.",
  2731. entry->nickname, dbuf, tbuf);
  2732. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2733. entry_guard_free(entry);
  2734. smartlist_del_keeporder(gs->chosen_entry_guards, i);
  2735. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2736. changed = 1;
  2737. } else
  2738. ++i;
  2739. }
  2740. done:
  2741. return changed ? 1 : 0;
  2742. }
  2743. /** Remove all currently listed entry guards for a given guard selection
  2744. * context */
  2745. void
  2746. remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
  2747. {
  2748. char dbuf[HEX_DIGEST_LEN+1];
  2749. tor_assert(gs != NULL);
  2750. if (gs->chosen_entry_guards) {
  2751. while (smartlist_len(gs->chosen_entry_guards)) {
  2752. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, 0);
  2753. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2754. log_info(LD_CIRC, "Entry guard '%s' (%s) has been dropped.",
  2755. entry->nickname, dbuf);
  2756. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2757. entry_guard_free(entry);
  2758. smartlist_del(gs->chosen_entry_guards, 0);
  2759. }
  2760. }
  2761. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2762. entry_guards_changed_for_guard_selection(gs);
  2763. }
  2764. /** Remove all currently listed entry guards. So new ones will be chosen. */
  2765. void
  2766. remove_all_entry_guards(void)
  2767. {
  2768. remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
  2769. }
  2770. /** A new directory or router-status has arrived; update the down/listed
  2771. * status of the entry guards.
  2772. *
  2773. * An entry is 'down' if the directory lists it as nonrunning.
  2774. * An entry is 'unlisted' if the directory doesn't include it.
  2775. *
  2776. * Don't call this on startup; only on a fresh download. Otherwise we'll
  2777. * think that things are unlisted.
  2778. */
  2779. void
  2780. entry_guards_compute_status_for_guard_selection(guard_selection_t *gs,
  2781. const or_options_t *options,
  2782. time_t now)
  2783. {
  2784. int changed = 0;
  2785. digestmap_t *reasons;
  2786. if ((!gs) || !(gs->chosen_entry_guards))
  2787. return;
  2788. if (!get_options()->UseDeprecatedGuardAlgorithm)
  2789. return;
  2790. if (options->EntryNodes) /* reshuffle the entry guard list if needed */
  2791. entry_nodes_should_be_added();
  2792. reasons = digestmap_new();
  2793. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, entry)
  2794. {
  2795. const node_t *r = node_get_by_id(entry->identity);
  2796. const char *reason = NULL;
  2797. if (entry_guard_set_status(entry, r, now, options, &reason))
  2798. changed = 1;
  2799. if (entry->bad_since)
  2800. tor_assert(reason);
  2801. if (reason)
  2802. digestmap_set(reasons, entry->identity, (char*)reason);
  2803. }
  2804. SMARTLIST_FOREACH_END(entry);
  2805. if (remove_dead_entry_guards(gs, now))
  2806. changed = 1;
  2807. if (remove_obsolete_entry_guards(gs, now))
  2808. changed = 1;
  2809. if (changed) {
  2810. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *,
  2811. entry) {
  2812. const char *reason = digestmap_get(reasons, entry->identity);
  2813. const char *live_msg = "";
  2814. const node_t *r = entry_is_live(entry, ENTRY_NEED_CAPACITY, &live_msg);
  2815. log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
  2816. entry->nickname,
  2817. hex_str(entry->identity, DIGEST_LEN),
  2818. entry->unreachable_since ? "unreachable" : "reachable",
  2819. entry->bad_since ? "unusable" : "usable",
  2820. reason ? ", ": "",
  2821. reason ? reason : "",
  2822. r ? "live" : "not live / ",
  2823. r ? "" : live_msg);
  2824. } SMARTLIST_FOREACH_END(entry);
  2825. log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
  2826. num_live_entry_guards_for_guard_selection(gs, 0),
  2827. smartlist_len(gs->chosen_entry_guards));
  2828. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2829. entry_guards_changed_for_guard_selection(gs);
  2830. }
  2831. digestmap_free(reasons, NULL);
  2832. }
  2833. /** A new directory or router-status has arrived; update the down/listed
  2834. * status of the entry guards.
  2835. *
  2836. * An entry is 'down' if the directory lists it as nonrunning.
  2837. * An entry is 'unlisted' if the directory doesn't include it.
  2838. *
  2839. * Don't call this on startup; only on a fresh download. Otherwise we'll
  2840. * think that things are unlisted.
  2841. */
  2842. void
  2843. entry_guards_compute_status(const or_options_t *options, time_t now)
  2844. {
  2845. entry_guards_compute_status_for_guard_selection(get_guard_selection_info(),
  2846. options, now);
  2847. }
  2848. /** Called when a connection to an OR with the identity digest <b>digest</b>
  2849. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  2850. * If the OR is an entry, change that entry's up/down status.
  2851. * Return 0 normally, or -1 if we want to tear down the new connection.
  2852. *
  2853. * If <b>mark_relay_status</b>, also call router_set_status() on this
  2854. * relay.
  2855. */
  2856. /* XXX We could change succeeded and mark_relay_status into 'int flags'.
  2857. * Too many boolean arguments is a recipe for confusion.
  2858. */
  2859. int
  2860. entry_guard_register_connect_status_for_guard_selection(
  2861. guard_selection_t *gs, const char *digest, int succeeded,
  2862. int mark_relay_status, time_t now)
  2863. {
  2864. int changed = 0;
  2865. int refuse_conn = 0;
  2866. int first_contact = 0;
  2867. entry_guard_t *entry = NULL;
  2868. int idx = -1;
  2869. char buf[HEX_DIGEST_LEN+1];
  2870. if (!(gs) || !(gs->chosen_entry_guards)) {
  2871. return 0;
  2872. }
  2873. if (! get_options()->UseDeprecatedGuardAlgorithm) {
  2874. return 0;
  2875. }
  2876. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  2877. tor_assert(e);
  2878. if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
  2879. entry = e;
  2880. idx = e_sl_idx;
  2881. break;
  2882. }
  2883. } SMARTLIST_FOREACH_END(e);
  2884. if (!entry)
  2885. return 0;
  2886. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  2887. if (succeeded) {
  2888. if (entry->unreachable_since) {
  2889. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  2890. entry->nickname, buf);
  2891. entry->can_retry = 0;
  2892. entry->unreachable_since = 0;
  2893. entry->last_attempted = now;
  2894. control_event_guard(entry->nickname, entry->identity, "UP");
  2895. changed = 1;
  2896. }
  2897. if (!entry->made_contact) {
  2898. entry->made_contact = 1;
  2899. first_contact = changed = 1;
  2900. }
  2901. } else { /* ! succeeded */
  2902. if (!entry->made_contact) {
  2903. /* We've never connected to this one. */
  2904. log_info(LD_CIRC,
  2905. "Connection to never-contacted entry guard '%s' (%s) failed. "
  2906. "Removing from the list. %d/%d entry guards usable/new.",
  2907. entry->nickname, buf,
  2908. num_live_entry_guards_for_guard_selection(gs, 0) - 1,
  2909. smartlist_len(gs->chosen_entry_guards)-1);
  2910. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2911. entry_guard_free(entry);
  2912. smartlist_del_keeporder(gs->chosen_entry_guards, idx);
  2913. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2914. changed = 1;
  2915. } else if (!entry->unreachable_since) {
  2916. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  2917. "Marking as unreachable.", entry->nickname, buf);
  2918. entry->unreachable_since = entry->last_attempted = now;
  2919. control_event_guard(entry->nickname, entry->identity, "DOWN");
  2920. changed = 1;
  2921. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2922. } else {
  2923. char tbuf[ISO_TIME_LEN+1];
  2924. format_iso_time(tbuf, entry->unreachable_since);
  2925. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  2926. "'%s' (%s). It has been unreachable since %s.",
  2927. entry->nickname, buf, tbuf);
  2928. entry->last_attempted = now;
  2929. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2930. }
  2931. }
  2932. /* if the caller asked us to, also update the is_running flags for this
  2933. * relay */
  2934. if (mark_relay_status)
  2935. router_set_status(digest, succeeded);
  2936. if (first_contact) {
  2937. /* We've just added a new long-term entry guard. Perhaps the network just
  2938. * came back? We should give our earlier entries another try too,
  2939. * and close this connection so we don't use it before we've given
  2940. * the others a shot. */
  2941. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  2942. if (e == entry)
  2943. break;
  2944. if (e->made_contact) {
  2945. const char *msg;
  2946. const node_t *r = entry_is_live(e,
  2947. ENTRY_NEED_CAPACITY | ENTRY_ASSUME_REACHABLE,
  2948. &msg);
  2949. if (r && e->unreachable_since) {
  2950. refuse_conn = 1;
  2951. e->can_retry = 1;
  2952. }
  2953. }
  2954. } SMARTLIST_FOREACH_END(e);
  2955. if (refuse_conn) {
  2956. log_info(LD_CIRC,
  2957. "Connected to new entry guard '%s' (%s). Marking earlier "
  2958. "entry guards up. %d/%d entry guards usable/new.",
  2959. entry->nickname, buf,
  2960. num_live_entry_guards_for_guard_selection(gs, 0),
  2961. smartlist_len(gs->chosen_entry_guards));
  2962. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2963. changed = 1;
  2964. }
  2965. }
  2966. if (changed)
  2967. entry_guards_changed_for_guard_selection(gs);
  2968. return refuse_conn ? -1 : 0;
  2969. }
  2970. /** Called when a connection to an OR with the identity digest <b>digest</b>
  2971. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  2972. * If the OR is an entry, change that entry's up/down status in the default
  2973. * guard selection context.
  2974. * Return 0 normally, or -1 if we want to tear down the new connection.
  2975. *
  2976. * If <b>mark_relay_status</b>, also call router_set_status() on this
  2977. * relay.
  2978. */
  2979. int
  2980. entry_guard_register_connect_status(const char *digest, int succeeded,
  2981. int mark_relay_status, time_t now)
  2982. {
  2983. return entry_guard_register_connect_status_for_guard_selection(
  2984. get_guard_selection_info(), digest, succeeded, mark_relay_status, now);
  2985. }
  2986. /** Called when the value of EntryNodes changes in our configuration. */
  2987. void
  2988. entry_nodes_should_be_added_for_guard_selection(guard_selection_t *gs)
  2989. {
  2990. tor_assert(gs != NULL);
  2991. log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
  2992. "relays at the front of the entry guard list.");
  2993. gs->should_add_entry_nodes = 1;
  2994. }
  2995. /** Called when the value of EntryNodes changes in our configuration. */
  2996. void
  2997. entry_nodes_should_be_added(void)
  2998. {
  2999. entry_nodes_should_be_added_for_guard_selection(
  3000. get_guard_selection_info());
  3001. }
  3002. /** Adjust the entry guards list so that it only contains entries from
  3003. * EntryNodes, adding new entries from EntryNodes to the list as needed. */
  3004. STATIC void
  3005. entry_guards_set_from_config(guard_selection_t *gs,
  3006. const or_options_t *options)
  3007. {
  3008. smartlist_t *entry_nodes, *worse_entry_nodes, *entry_fps;
  3009. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  3010. const int numentryguards = decide_num_guards(options, 0);
  3011. tor_assert(gs != NULL);
  3012. tor_assert(gs->chosen_entry_guards != NULL);
  3013. gs->should_add_entry_nodes = 0;
  3014. if (!options->EntryNodes) {
  3015. /* It's possible that a controller set EntryNodes, thus making
  3016. * should_add_entry_nodes set, then cleared it again, all before the
  3017. * call to choose_random_entry() that triggered us. If so, just return.
  3018. */
  3019. return;
  3020. }
  3021. {
  3022. char *string = routerset_to_string(options->EntryNodes);
  3023. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
  3024. tor_free(string);
  3025. }
  3026. entry_nodes = smartlist_new();
  3027. worse_entry_nodes = smartlist_new();
  3028. entry_fps = smartlist_new();
  3029. old_entry_guards_on_list = smartlist_new();
  3030. old_entry_guards_not_on_list = smartlist_new();
  3031. /* Split entry guards into those on the list and those not. */
  3032. routerset_get_all_nodes(entry_nodes, options->EntryNodes,
  3033. options->ExcludeNodes, 0);
  3034. SMARTLIST_FOREACH(entry_nodes, const node_t *,node,
  3035. smartlist_add(entry_fps, (void*)node->identity));
  3036. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e, {
  3037. if (smartlist_contains_digest(entry_fps, e->identity))
  3038. smartlist_add(old_entry_guards_on_list, e);
  3039. else
  3040. smartlist_add(old_entry_guards_not_on_list, e);
  3041. });
  3042. /* Remove all currently configured guard nodes, excluded nodes, unreachable
  3043. * nodes, or non-Guard nodes from entry_nodes. */
  3044. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  3045. if (entry_guard_get_by_id_digest_for_guard_selection(gs,
  3046. node->identity)) {
  3047. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3048. continue;
  3049. } else if (routerset_contains_node(options->ExcludeNodes, node)) {
  3050. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3051. continue;
  3052. } else if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION,
  3053. 0)) {
  3054. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3055. continue;
  3056. } else if (! node->is_possible_guard) {
  3057. smartlist_add(worse_entry_nodes, (node_t*)node);
  3058. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3059. }
  3060. } SMARTLIST_FOREACH_END(node);
  3061. /* Now build the new entry_guards list. */
  3062. smartlist_clear(gs->chosen_entry_guards);
  3063. /* First, the previously configured guards that are in EntryNodes. */
  3064. smartlist_add_all(gs->chosen_entry_guards, old_entry_guards_on_list);
  3065. /* Next, scramble the rest of EntryNodes, putting the guards first. */
  3066. smartlist_shuffle(entry_nodes);
  3067. smartlist_shuffle(worse_entry_nodes);
  3068. smartlist_add_all(entry_nodes, worse_entry_nodes);
  3069. /* Next, the rest of EntryNodes */
  3070. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  3071. add_an_entry_guard(gs, node, 0, 0, 1, 0);
  3072. if (smartlist_len(gs->chosen_entry_guards) > numentryguards * 10)
  3073. break;
  3074. } SMARTLIST_FOREACH_END(node);
  3075. log_notice(LD_GENERAL, "%d entries in guards",
  3076. smartlist_len(gs->chosen_entry_guards));
  3077. /* Finally, free the remaining previously configured guards that are not in
  3078. * EntryNodes. */
  3079. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  3080. entry_guard_free(e));
  3081. smartlist_free(entry_nodes);
  3082. smartlist_free(worse_entry_nodes);
  3083. smartlist_free(entry_fps);
  3084. smartlist_free(old_entry_guards_on_list);
  3085. smartlist_free(old_entry_guards_not_on_list);
  3086. entry_guards_changed_for_guard_selection(gs);
  3087. }
  3088. /** Return 0 if we're fine adding arbitrary routers out of the
  3089. * directory to our entry guard list, or return 1 if we have a
  3090. * list already and we must stick to it.
  3091. */
  3092. int
  3093. entry_list_is_constrained(const or_options_t *options)
  3094. {
  3095. if (options->EntryNodes)
  3096. return 1;
  3097. if (options->UseBridges)
  3098. return 1;
  3099. return 0;
  3100. }
  3101. /** Pick a live (up and listed) entry guard from entry_guards. If
  3102. * <b>state</b> is non-NULL, this is for a specific circuit --
  3103. * make sure not to pick this circuit's exit or any node in the
  3104. * exit's family. If <b>state</b> is NULL, we're looking for a random
  3105. * guard (likely a bridge). If <b>dirinfo</b> is not NO_DIRINFO (zero),
  3106. * then only select from nodes that know how to answer directory questions
  3107. * of that type. */
  3108. const node_t *
  3109. choose_random_entry(cpath_build_state_t *state)
  3110. {
  3111. tor_assert(get_options()->UseDeprecatedGuardAlgorithm);
  3112. return choose_random_entry_impl(get_guard_selection_info(),
  3113. state, 0, NO_DIRINFO, NULL);
  3114. }
  3115. /** Pick a live (up and listed) directory guard from entry_guards for
  3116. * downloading information of type <b>type</b>. */
  3117. const node_t *
  3118. choose_random_dirguard(dirinfo_type_t type)
  3119. {
  3120. tor_assert(get_options()->UseDeprecatedGuardAlgorithm);
  3121. return choose_random_entry_impl(get_guard_selection_info(),
  3122. NULL, 1, type, NULL);
  3123. }
  3124. /** Return the number of bridges that have descriptors that are marked with
  3125. * purpose 'bridge' and are running.
  3126. */
  3127. int
  3128. num_bridges_usable(void)
  3129. {
  3130. tor_assert(get_options()->UseDeprecatedGuardAlgorithm);
  3131. int n_options = 0;
  3132. tor_assert(get_options()->UseBridges);
  3133. (void) choose_random_entry_impl(get_guard_selection_info(),
  3134. NULL, 0, 0, &n_options);
  3135. return n_options;
  3136. }
  3137. /** Filter <b>all_entry_guards</b> for usable entry guards and put them
  3138. * in <b>live_entry_guards</b>. We filter based on whether the node is
  3139. * currently alive, and on whether it satisfies the restrictions
  3140. * imposed by the other arguments of this function.
  3141. *
  3142. * We don't place more guards than NumEntryGuards in <b>live_entry_guards</b>.
  3143. *
  3144. * If <b>chosen_exit</b> is set, it contains the exit node of this
  3145. * circuit. Make sure to not use it or its family as an entry guard.
  3146. *
  3147. * If <b>need_uptime</b> is set, we are looking for a stable entry guard.
  3148. * if <b>need_capacity</b> is set, we are looking for a fast entry guard.
  3149. *
  3150. * The rest of the arguments are the same as in choose_random_entry_impl().
  3151. *
  3152. * Return 1 if we should choose a guard right away. Return 0 if we
  3153. * should try to add more nodes to our list before deciding on a
  3154. * guard.
  3155. */
  3156. STATIC int
  3157. populate_live_entry_guards(smartlist_t *live_entry_guards,
  3158. const smartlist_t *all_entry_guards,
  3159. const node_t *chosen_exit,
  3160. dirinfo_type_t dirinfo_type,
  3161. int for_directory,
  3162. int need_uptime, int need_capacity)
  3163. {
  3164. const or_options_t *options = get_options();
  3165. const node_t *node = NULL;
  3166. const int num_needed = decide_num_guards(options, for_directory);
  3167. smartlist_t *exit_family = smartlist_new();
  3168. int retval = 0;
  3169. entry_is_live_flags_t entry_flags = 0;
  3170. (void) dirinfo_type;
  3171. { /* Set the flags we want our entry node to have */
  3172. if (need_uptime) {
  3173. entry_flags |= ENTRY_NEED_UPTIME;
  3174. }
  3175. if (need_capacity) {
  3176. entry_flags |= ENTRY_NEED_CAPACITY;
  3177. }
  3178. if (!for_directory) {
  3179. entry_flags |= ENTRY_NEED_DESCRIPTOR;
  3180. }
  3181. }
  3182. tor_assert(all_entry_guards);
  3183. if (chosen_exit) {
  3184. nodelist_add_node_and_family(exit_family, chosen_exit);
  3185. }
  3186. SMARTLIST_FOREACH_BEGIN(all_entry_guards, const entry_guard_t *, entry) {
  3187. const char *msg;
  3188. node = entry_is_live(entry, entry_flags, &msg);
  3189. if (!node)
  3190. continue; /* down, no point */
  3191. if (for_directory) {
  3192. if (!entry->is_dir_cache)
  3193. continue; /* We need a directory and didn't get one. */
  3194. }
  3195. if (node == chosen_exit)
  3196. continue; /* don't pick the same node for entry and exit */
  3197. if (smartlist_contains(exit_family, node))
  3198. continue; /* avoid relays that are family members of our exit */
  3199. smartlist_add(live_entry_guards, (void*)node);
  3200. if (!entry->made_contact) {
  3201. /* Always start with the first not-yet-contacted entry
  3202. * guard. Otherwise we might add several new ones, pick
  3203. * the second new one, and now we've expanded our entry
  3204. * guard list without needing to. */
  3205. retval = 1;
  3206. goto done;
  3207. }
  3208. if (smartlist_len(live_entry_guards) >= num_needed) {
  3209. retval = 1;
  3210. goto done; /* We picked enough entry guards. Done! */
  3211. }
  3212. } SMARTLIST_FOREACH_END(entry);
  3213. done:
  3214. smartlist_free(exit_family);
  3215. return retval;
  3216. }
  3217. /** Pick a node to be used as the entry guard of a circuit, relative to
  3218. * a supplied guard selection context.
  3219. *
  3220. * If <b>state</b> is set, it contains the information we know about
  3221. * the upcoming circuit.
  3222. *
  3223. * If <b>for_directory</b> is set, we are looking for a directory guard.
  3224. *
  3225. * <b>dirinfo_type</b> contains the kind of directory information we
  3226. * are looking for in our node, or NO_DIRINFO (zero) if we are not
  3227. * looking for any particular directory information (when set to
  3228. * NO_DIRINFO, the <b>dirinfo_type</b> filter is ignored).
  3229. *
  3230. * If <b>n_options_out</b> is set, we set it to the number of
  3231. * candidate guard nodes we had before picking a specific guard node.
  3232. *
  3233. * On success, return the node that should be used as the entry guard
  3234. * of the circuit. Return NULL if no such node could be found.
  3235. *
  3236. * Helper for choose_random{entry,dirguard}.
  3237. */
  3238. static const node_t *
  3239. choose_random_entry_impl(guard_selection_t *gs,
  3240. cpath_build_state_t *state, int for_directory,
  3241. dirinfo_type_t dirinfo_type, int *n_options_out)
  3242. {
  3243. const or_options_t *options = get_options();
  3244. smartlist_t *live_entry_guards = smartlist_new();
  3245. const node_t *chosen_exit =
  3246. state?build_state_get_exit_node(state) : NULL;
  3247. const node_t *node = NULL;
  3248. int need_uptime = state ? state->need_uptime : 0;
  3249. int need_capacity = state ? state->need_capacity : 0;
  3250. int preferred_min = 0;
  3251. const int num_needed = decide_num_guards(options, for_directory);
  3252. int retval = 0;
  3253. tor_assert(gs != NULL);
  3254. tor_assert(gs->chosen_entry_guards != NULL);
  3255. if (n_options_out)
  3256. *n_options_out = 0;
  3257. if (gs->should_add_entry_nodes)
  3258. entry_guards_set_from_config(gs, options);
  3259. if (!entry_list_is_constrained(options) &&
  3260. smartlist_len(gs->chosen_entry_guards) < num_needed)
  3261. pick_entry_guards(gs, options, for_directory);
  3262. retry:
  3263. smartlist_clear(live_entry_guards);
  3264. /* Populate the list of live entry guards so that we pick one of
  3265. them. */
  3266. retval = populate_live_entry_guards(live_entry_guards,
  3267. gs->chosen_entry_guards,
  3268. chosen_exit,
  3269. dirinfo_type,
  3270. for_directory,
  3271. need_uptime, need_capacity);
  3272. if (retval == 1) { /* We should choose a guard right now. */
  3273. goto choose_and_finish;
  3274. }
  3275. if (entry_list_is_constrained(options)) {
  3276. /* If we prefer the entry nodes we've got, and we have at least
  3277. * one choice, that's great. Use it. */
  3278. preferred_min = 1;
  3279. } else {
  3280. /* Try to have at least 2 choices available. This way we don't
  3281. * get stuck with a single live-but-crummy entry and just keep
  3282. * using it.
  3283. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  3284. preferred_min = 2;
  3285. }
  3286. if (smartlist_len(live_entry_guards) < preferred_min) {
  3287. if (!entry_list_is_constrained(options)) {
  3288. /* still no? try adding a new entry then */
  3289. /* XXX if guard doesn't imply fast and stable, then we need
  3290. * to tell add_an_entry_guard below what we want, or it might
  3291. * be a long time til we get it. -RD */
  3292. node = add_an_entry_guard(gs, NULL, 0, 0, 1, for_directory);
  3293. if (node) {
  3294. entry_guards_changed_for_guard_selection(gs);
  3295. /* XXX we start over here in case the new node we added shares
  3296. * a family with our exit node. There's a chance that we'll just
  3297. * load up on entry guards here, if the network we're using is
  3298. * one big family. Perhaps we should teach add_an_entry_guard()
  3299. * to understand nodes-to-avoid-if-possible? -RD */
  3300. goto retry;
  3301. }
  3302. }
  3303. if (!node && need_uptime) {
  3304. need_uptime = 0; /* try without that requirement */
  3305. goto retry;
  3306. }
  3307. if (!node && need_capacity) {
  3308. /* still no? last attempt, try without requiring capacity */
  3309. need_capacity = 0;
  3310. goto retry;
  3311. }
  3312. /* live_entry_guards may be empty below. Oh well, we tried. */
  3313. }
  3314. choose_and_finish:
  3315. if (entry_list_is_constrained(options)) {
  3316. /* We need to weight by bandwidth, because our bridges or entryguards
  3317. * were not already selected proportional to their bandwidth. */
  3318. node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  3319. } else {
  3320. /* We choose uniformly at random here, because choose_good_entry_server()
  3321. * already weights its choices by bandwidth, so we don't want to
  3322. * *double*-weight our guard selection. */
  3323. node = smartlist_choose(live_entry_guards);
  3324. }
  3325. if (n_options_out)
  3326. *n_options_out = smartlist_len(live_entry_guards);
  3327. smartlist_free(live_entry_guards);
  3328. return node;
  3329. }
  3330. static void
  3331. pathbias_check_use_success_count(entry_guard_t *node)
  3332. {
  3333. const or_options_t *options = get_options();
  3334. const double EPSILON = 1.0e-9;
  3335. /* Note: We rely on the < comparison here to allow us to set a 0
  3336. * rate and disable the feature entirely. If refactoring, don't
  3337. * change to <= */
  3338. if (node->pb.use_attempts > EPSILON &&
  3339. pathbias_get_use_success_count(node)/node->pb.use_attempts
  3340. < pathbias_get_extreme_use_rate(options) &&
  3341. pathbias_get_dropguards(options)) {
  3342. node->pb.path_bias_disabled = 1;
  3343. log_info(LD_GENERAL,
  3344. "Path use bias is too high (%f/%f); disabling node %s",
  3345. node->pb.circ_successes, node->pb.circ_attempts,
  3346. node->nickname);
  3347. }
  3348. }
  3349. static void
  3350. pathbias_check_close_success_count(entry_guard_t *node)
  3351. {
  3352. const or_options_t *options = get_options();
  3353. const double EPSILON = 1.0e-9;
  3354. /* Note: We rely on the < comparison here to allow us to set a 0
  3355. * rate and disable the feature entirely. If refactoring, don't
  3356. * change to <= */
  3357. if (node->pb.circ_attempts > EPSILON &&
  3358. pathbias_get_close_success_count(node)/node->pb.circ_attempts
  3359. < pathbias_get_extreme_rate(options) &&
  3360. pathbias_get_dropguards(options)) {
  3361. node->pb.path_bias_disabled = 1;
  3362. log_info(LD_GENERAL,
  3363. "Path bias is too high (%f/%f); disabling node %s",
  3364. node->pb.circ_successes, node->pb.circ_attempts,
  3365. node->nickname);
  3366. }
  3367. }
  3368. /** Parse <b>state</b> and learn about the entry guards it describes.
  3369. * If <b>set</b> is true, and there are no errors, replace the guard
  3370. * list in the provided guard selection context with what we find.
  3371. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  3372. * describing the error, and return -1.
  3373. */
  3374. int
  3375. entry_guards_parse_state_for_guard_selection(
  3376. guard_selection_t *gs,
  3377. or_state_t *state, int set, char **msg)
  3378. {
  3379. entry_guard_t *node = NULL;
  3380. smartlist_t *new_entry_guards = smartlist_new();
  3381. config_line_t *line;
  3382. time_t now = time(NULL);
  3383. const char *state_version = state->TorVersion;
  3384. digestmap_t *added_by = digestmap_new();
  3385. tor_assert(gs != NULL);
  3386. *msg = NULL;
  3387. for (line = state->EntryGuards; line; line = line->next) {
  3388. if (!strcasecmp(line->key, "EntryGuard")) {
  3389. smartlist_t *args = smartlist_new();
  3390. node = tor_malloc_zero(sizeof(entry_guard_t));
  3391. /* all entry guards on disk have been contacted */
  3392. node->made_contact = 1;
  3393. smartlist_add(new_entry_guards, node);
  3394. smartlist_split_string(args, line->value, " ",
  3395. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3396. if (smartlist_len(args)<2) {
  3397. *msg = tor_strdup("Unable to parse entry nodes: "
  3398. "Too few arguments to EntryGuard");
  3399. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  3400. *msg = tor_strdup("Unable to parse entry nodes: "
  3401. "Bad nickname for EntryGuard");
  3402. } else {
  3403. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  3404. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  3405. strlen(smartlist_get(args,1))) != DIGEST_LEN) {
  3406. *msg = tor_strdup("Unable to parse entry nodes: "
  3407. "Bad hex digest for EntryGuard");
  3408. }
  3409. }
  3410. if (smartlist_len(args) >= 3) {
  3411. const char *is_cache = smartlist_get(args, 2);
  3412. if (!strcasecmp(is_cache, "DirCache")) {
  3413. node->is_dir_cache = 1;
  3414. } else if (!strcasecmp(is_cache, "NoDirCache")) {
  3415. node->is_dir_cache = 0;
  3416. } else {
  3417. log_warn(LD_CONFIG, "Bogus third argument to EntryGuard line: %s",
  3418. escaped(is_cache));
  3419. }
  3420. }
  3421. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  3422. smartlist_free(args);
  3423. if (*msg)
  3424. break;
  3425. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  3426. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  3427. time_t when;
  3428. time_t last_try = 0;
  3429. if (!node) {
  3430. *msg = tor_strdup("Unable to parse entry nodes: "
  3431. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  3432. break;
  3433. }
  3434. if (parse_iso_time_(line->value, &when, 0, 0)<0) {
  3435. *msg = tor_strdup("Unable to parse entry nodes: "
  3436. "Bad time in EntryGuardDownSince/UnlistedSince");
  3437. break;
  3438. }
  3439. if (when > now) {
  3440. /* It's a bad idea to believe info in the future: you can wind
  3441. * up with timeouts that aren't allowed to happen for years. */
  3442. continue;
  3443. }
  3444. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  3445. /* ignore failure */
  3446. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  3447. }
  3448. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  3449. node->unreachable_since = when;
  3450. node->last_attempted = last_try;
  3451. } else {
  3452. node->bad_since = when;
  3453. }
  3454. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  3455. char d[DIGEST_LEN];
  3456. /* format is digest version date */
  3457. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  3458. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  3459. continue;
  3460. }
  3461. if (base16_decode(d, sizeof(d),
  3462. line->value, HEX_DIGEST_LEN) != sizeof(d) ||
  3463. line->value[HEX_DIGEST_LEN] != ' ') {
  3464. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  3465. "hex digest", escaped(line->value));
  3466. continue;
  3467. }
  3468. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  3469. } else if (!strcasecmp(line->key, "EntryGuardPathUseBias")) {
  3470. double use_cnt, success_cnt;
  3471. if (!node) {
  3472. *msg = tor_strdup("Unable to parse entry nodes: "
  3473. "EntryGuardPathUseBias without EntryGuard");
  3474. break;
  3475. }
  3476. if (tor_sscanf(line->value, "%lf %lf",
  3477. &use_cnt, &success_cnt) != 2) {
  3478. log_info(LD_GENERAL, "Malformed path use bias line for node %s",
  3479. node->nickname);
  3480. continue;
  3481. }
  3482. if (use_cnt < success_cnt) {
  3483. int severity = LOG_INFO;
  3484. /* If this state file was written by a Tor that would have
  3485. * already fixed it, then the overcounting bug is still there.. */
  3486. if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
  3487. severity = LOG_NOTICE;
  3488. }
  3489. log_fn(severity, LD_BUG,
  3490. "State file contains unexpectedly high usage success "
  3491. "counts %lf/%lf for Guard %s ($%s)",
  3492. success_cnt, use_cnt,
  3493. node->nickname, hex_str(node->identity, DIGEST_LEN));
  3494. success_cnt = use_cnt;
  3495. }
  3496. node->pb.use_attempts = use_cnt;
  3497. node->pb.use_successes = success_cnt;
  3498. log_info(LD_GENERAL, "Read %f/%f path use bias for node %s",
  3499. node->pb.use_successes, node->pb.use_attempts, node->nickname);
  3500. pathbias_check_use_success_count(node);
  3501. } else if (!strcasecmp(line->key, "EntryGuardPathBias")) {
  3502. double hop_cnt, success_cnt, timeouts, collapsed, successful_closed,
  3503. unusable;
  3504. if (!node) {
  3505. *msg = tor_strdup("Unable to parse entry nodes: "
  3506. "EntryGuardPathBias without EntryGuard");
  3507. break;
  3508. }
  3509. /* First try 3 params, then 2. */
  3510. /* In the long run: circuit_success ~= successful_circuit_close +
  3511. * collapsed_circuits +
  3512. * unusable_circuits */
  3513. if (tor_sscanf(line->value, "%lf %lf %lf %lf %lf %lf",
  3514. &hop_cnt, &success_cnt, &successful_closed,
  3515. &collapsed, &unusable, &timeouts) != 6) {
  3516. int old_success, old_hops;
  3517. if (tor_sscanf(line->value, "%u %u", &old_success, &old_hops) != 2) {
  3518. continue;
  3519. }
  3520. log_info(LD_GENERAL, "Reading old-style EntryGuardPathBias %s",
  3521. escaped(line->value));
  3522. success_cnt = old_success;
  3523. successful_closed = old_success;
  3524. hop_cnt = old_hops;
  3525. timeouts = 0;
  3526. collapsed = 0;
  3527. unusable = 0;
  3528. }
  3529. if (hop_cnt < success_cnt) {
  3530. int severity = LOG_INFO;
  3531. /* If this state file was written by a Tor that would have
  3532. * already fixed it, then the overcounting bug is still there.. */
  3533. if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
  3534. severity = LOG_NOTICE;
  3535. }
  3536. log_fn(severity, LD_BUG,
  3537. "State file contains unexpectedly high success counts "
  3538. "%lf/%lf for Guard %s ($%s)",
  3539. success_cnt, hop_cnt,
  3540. node->nickname, hex_str(node->identity, DIGEST_LEN));
  3541. success_cnt = hop_cnt;
  3542. }
  3543. node->pb.circ_attempts = hop_cnt;
  3544. node->pb.circ_successes = success_cnt;
  3545. node->pb.successful_circuits_closed = successful_closed;
  3546. node->pb.timeouts = timeouts;
  3547. node->pb.collapsed_circuits = collapsed;
  3548. node->pb.unusable_circuits = unusable;
  3549. log_info(LD_GENERAL, "Read %f/%f path bias for node %s",
  3550. node->pb.circ_successes, node->pb.circ_attempts,
  3551. node->nickname);
  3552. pathbias_check_close_success_count(node);
  3553. } else {
  3554. log_warn(LD_BUG, "Unexpected key %s", line->key);
  3555. }
  3556. }
  3557. SMARTLIST_FOREACH_BEGIN(new_entry_guards, entry_guard_t *, e) {
  3558. char *sp;
  3559. char *val = digestmap_get(added_by, e->identity);
  3560. if (val && (sp = strchr(val, ' '))) {
  3561. time_t when;
  3562. *sp++ = '\0';
  3563. if (parse_iso_time(sp, &when)<0) {
  3564. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  3565. } else {
  3566. e->chosen_by_version = tor_strdup(val);
  3567. e->chosen_on_date = when;
  3568. }
  3569. } else {
  3570. if (state_version) {
  3571. e->chosen_on_date = crypto_rand_time_range(now - 3600*24*30, now);
  3572. e->chosen_by_version = tor_strdup(state_version);
  3573. }
  3574. }
  3575. if (e->pb.path_bias_disabled && !e->bad_since)
  3576. e->bad_since = time(NULL);
  3577. }
  3578. SMARTLIST_FOREACH_END(e);
  3579. if (*msg || !set) {
  3580. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  3581. entry_guard_free(e));
  3582. smartlist_free(new_entry_guards);
  3583. } else { /* !err && set */
  3584. if (gs->chosen_entry_guards) {
  3585. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e,
  3586. entry_guard_free(e));
  3587. smartlist_free(gs->chosen_entry_guards);
  3588. }
  3589. gs->chosen_entry_guards = new_entry_guards;
  3590. /* XXX hand new_entry_guards to this func, and move it up a
  3591. * few lines, so we don't have to re-dirty it */
  3592. if (remove_obsolete_entry_guards(gs, now))
  3593. entry_guards_dirty = 1;
  3594. }
  3595. digestmap_free(added_by, tor_free_);
  3596. return *msg ? -1 : 0;
  3597. }
  3598. /** Parse <b>state</b> and learn about the entry guards it describes.
  3599. * If <b>set</b> is true, and there are no errors, replace the guard
  3600. * list in the default guard selection context with what we find.
  3601. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  3602. * describing the error, and return -1.
  3603. */
  3604. int
  3605. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  3606. {
  3607. entry_guards_dirty = 0;
  3608. int r1 = entry_guards_load_guards_from_state(state, set);
  3609. int r2 = entry_guards_parse_state_for_guard_selection(
  3610. get_guard_selection_by_name("legacy", GS_TYPE_LEGACY, 1),
  3611. state, set, msg);
  3612. entry_guards_dirty = 0;
  3613. if (r1 < 0 || r2 < 0) {
  3614. if (msg && *msg == NULL) {
  3615. *msg = tor_strdup("parsing error"); //xxxx prop271 should we try harder?
  3616. }
  3617. return -1;
  3618. }
  3619. return 0;
  3620. }
  3621. /** How long will we let a change in our guard nodes stay un-saved
  3622. * when we are trying to avoid disk writes? */
  3623. #define SLOW_GUARD_STATE_FLUSH_TIME 600
  3624. /** How long will we let a change in our guard nodes stay un-saved
  3625. * when we are not trying to avoid disk writes? */
  3626. #define FAST_GUARD_STATE_FLUSH_TIME 30
  3627. /** Our list of entry guards has changed for a particular guard selection
  3628. * context, or some element of one of our entry guards has changed for one.
  3629. * Write the changes to disk within the next few minutes.
  3630. */
  3631. void
  3632. entry_guards_changed_for_guard_selection(guard_selection_t *gs)
  3633. {
  3634. time_t when;
  3635. tor_assert(gs != NULL);
  3636. entry_guards_dirty = 1;
  3637. if (get_options()->AvoidDiskWrites)
  3638. when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
  3639. else
  3640. when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
  3641. /* or_state_save() will call entry_guards_update_state() and
  3642. entry_guards_update_guards_in_state()
  3643. */
  3644. or_state_mark_dirty(get_or_state(), when);
  3645. }
  3646. /** Our list of entry guards has changed for the default guard selection
  3647. * context, or some element of one of our entry guards has changed. Write
  3648. * the changes to disk within the next few minutes.
  3649. */
  3650. void
  3651. entry_guards_changed(void)
  3652. {
  3653. entry_guards_changed_for_guard_selection(get_guard_selection_info());
  3654. }
  3655. /** If the entry guard info has not changed, do nothing and return.
  3656. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  3657. * a new one out of the global entry_guards list, and then mark
  3658. * <b>state</b> dirty so it will get saved to disk.
  3659. */
  3660. void
  3661. entry_guards_update_state(or_state_t *state)
  3662. {
  3663. config_line_t **next, *line;
  3664. entry_guards_dirty = 0;
  3665. // Handles all non-legacy guard info.
  3666. entry_guards_update_guards_in_state(state);
  3667. entry_guards_dirty = 0;
  3668. guard_selection_t *gs;
  3669. gs = get_guard_selection_by_name("legacy", GS_TYPE_LEGACY, 0);
  3670. if (!gs)
  3671. return; // nothign to save.
  3672. tor_assert(gs->chosen_entry_guards != NULL);
  3673. config_free_lines(state->EntryGuards);
  3674. next = &state->EntryGuards;
  3675. *next = NULL;
  3676. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3677. char dbuf[HEX_DIGEST_LEN+1];
  3678. if (!e->made_contact)
  3679. continue; /* don't write this one to disk */
  3680. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3681. line->key = tor_strdup("EntryGuard");
  3682. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  3683. tor_asprintf(&line->value, "%s %s %sDirCache", e->nickname, dbuf,
  3684. e->is_dir_cache ? "" : "No");
  3685. next = &(line->next);
  3686. if (e->unreachable_since) {
  3687. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3688. line->key = tor_strdup("EntryGuardDownSince");
  3689. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  3690. format_iso_time(line->value, e->unreachable_since);
  3691. if (e->last_attempted) {
  3692. line->value[ISO_TIME_LEN] = ' ';
  3693. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  3694. }
  3695. next = &(line->next);
  3696. }
  3697. if (e->bad_since) {
  3698. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3699. line->key = tor_strdup("EntryGuardUnlistedSince");
  3700. line->value = tor_malloc(ISO_TIME_LEN+1);
  3701. format_iso_time(line->value, e->bad_since);
  3702. next = &(line->next);
  3703. }
  3704. if (e->chosen_on_date && e->chosen_by_version &&
  3705. !strchr(e->chosen_by_version, ' ')) {
  3706. char d[HEX_DIGEST_LEN+1];
  3707. char t[ISO_TIME_LEN+1];
  3708. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3709. line->key = tor_strdup("EntryGuardAddedBy");
  3710. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  3711. format_iso_time(t, e->chosen_on_date);
  3712. tor_asprintf(&line->value, "%s %s %s",
  3713. d, e->chosen_by_version, t);
  3714. next = &(line->next);
  3715. }
  3716. if (e->pb.circ_attempts > 0) {
  3717. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3718. line->key = tor_strdup("EntryGuardPathBias");
  3719. /* In the long run: circuit_success ~= successful_circuit_close +
  3720. * collapsed_circuits +
  3721. * unusable_circuits */
  3722. tor_asprintf(&line->value, "%f %f %f %f %f %f",
  3723. e->pb.circ_attempts, e->pb.circ_successes,
  3724. pathbias_get_close_success_count(e),
  3725. e->pb.collapsed_circuits,
  3726. e->pb.unusable_circuits, e->pb.timeouts);
  3727. next = &(line->next);
  3728. }
  3729. if (e->pb.use_attempts > 0) {
  3730. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3731. line->key = tor_strdup("EntryGuardPathUseBias");
  3732. tor_asprintf(&line->value, "%f %f",
  3733. e->pb.use_attempts,
  3734. pathbias_get_use_success_count(e));
  3735. next = &(line->next);
  3736. }
  3737. } SMARTLIST_FOREACH_END(e);
  3738. if (!get_options()->AvoidDiskWrites)
  3739. or_state_mark_dirty(get_or_state(), 0);
  3740. entry_guards_dirty = 0;
  3741. }
  3742. /** If <b>question</b> is the string "entry-guards", then dump
  3743. * to *<b>answer</b> a newly allocated string describing all of
  3744. * the nodes in the global entry_guards list. See control-spec.txt
  3745. * for details.
  3746. * For backward compatibility, we also handle the string "helper-nodes".
  3747. *
  3748. * XXX this should be totally redesigned after prop 271 too, and that's
  3749. * going to take some control spec work.
  3750. * */
  3751. int
  3752. getinfo_helper_entry_guards(control_connection_t *conn,
  3753. const char *question, char **answer,
  3754. const char **errmsg)
  3755. {
  3756. guard_selection_t *gs = get_guard_selection_info();
  3757. tor_assert(gs != NULL);
  3758. tor_assert(gs->chosen_entry_guards != NULL);
  3759. (void) conn;
  3760. (void) errmsg;
  3761. if (!strcmp(question,"entry-guards") ||
  3762. !strcmp(question,"helper-nodes")) {
  3763. smartlist_t *sl = smartlist_new();
  3764. char tbuf[ISO_TIME_LEN+1];
  3765. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  3766. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3767. const char *status = NULL;
  3768. time_t when = 0;
  3769. const node_t *node;
  3770. if (!e->made_contact) {
  3771. status = "never-connected";
  3772. } else if (e->bad_since) {
  3773. when = e->bad_since;
  3774. status = "unusable";
  3775. } else if (e->unreachable_since) {
  3776. when = e->unreachable_since;
  3777. status = "down";
  3778. } else {
  3779. status = "up";
  3780. }
  3781. node = node_get_by_id(e->identity);
  3782. if (node) {
  3783. node_get_verbose_nickname(node, nbuf);
  3784. } else {
  3785. nbuf[0] = '$';
  3786. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  3787. /* e->nickname field is not very reliable if we don't know about
  3788. * this router any longer; don't include it. */
  3789. }
  3790. if (when) {
  3791. format_iso_time(tbuf, when);
  3792. smartlist_add_asprintf(sl, "%s %s %s\n", nbuf, status, tbuf);
  3793. } else {
  3794. smartlist_add_asprintf(sl, "%s %s\n", nbuf, status);
  3795. }
  3796. } SMARTLIST_FOREACH_END(e);
  3797. *answer = smartlist_join_strings(sl, "", 0, NULL);
  3798. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  3799. smartlist_free(sl);
  3800. }
  3801. return 0;
  3802. }
  3803. /* Given the original bandwidth of a guard and its guardfraction,
  3804. * calculate how much bandwidth the guard should have as a guard and
  3805. * as a non-guard.
  3806. *
  3807. * Quoting from proposal236:
  3808. *
  3809. * Let Wpf denote the weight from the 'bandwidth-weights' line a
  3810. * client would apply to N for position p if it had the guard
  3811. * flag, Wpn the weight if it did not have the guard flag, and B the
  3812. * measured bandwidth of N in the consensus. Then instead of choosing
  3813. * N for position p proportionally to Wpf*B or Wpn*B, clients should
  3814. * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
  3815. *
  3816. * This function fills the <b>guardfraction_bw</b> structure. It sets
  3817. * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
  3818. */
  3819. void
  3820. guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
  3821. int orig_bandwidth,
  3822. uint32_t guardfraction_percentage)
  3823. {
  3824. double guardfraction_fraction;
  3825. /* Turn the percentage into a fraction. */
  3826. tor_assert(guardfraction_percentage <= 100);
  3827. guardfraction_fraction = guardfraction_percentage / 100.0;
  3828. long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
  3829. tor_assert(guard_bw <= INT_MAX);
  3830. guardfraction_bw->guard_bw = (int) guard_bw;
  3831. guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
  3832. }
  3833. /** Returns true iff the node is used as a guard in the specified guard
  3834. * context */
  3835. int
  3836. is_node_used_as_guard_for_guard_selection(guard_selection_t *gs,
  3837. const node_t *node)
  3838. {
  3839. int res = 0;
  3840. /*
  3841. * We used to have a using_as_guard flag in node_t, but it had to go away
  3842. * to allow for multiple guard selection contexts. Instead, search the
  3843. * guard list for a matching digest.
  3844. */
  3845. tor_assert(gs != NULL);
  3846. tor_assert(node != NULL);
  3847. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3848. if (tor_memeq(e->identity, node->identity, DIGEST_LEN)) {
  3849. res = 1;
  3850. break;
  3851. }
  3852. } SMARTLIST_FOREACH_END(e);
  3853. return res;
  3854. }
  3855. /** Returns true iff the node is used as a guard in the default guard
  3856. * context */
  3857. MOCK_IMPL(int,
  3858. is_node_used_as_guard, (const node_t *node))
  3859. {
  3860. return is_node_used_as_guard_for_guard_selection(
  3861. get_guard_selection_info(), node);
  3862. }
  3863. /** Return 1 if we have at least one descriptor for an entry guard
  3864. * (bridge or member of EntryNodes) and all descriptors we know are
  3865. * down. Else return 0. If <b>act</b> is 1, then mark the down guards
  3866. * up; else just observe and report. */
  3867. static int
  3868. entries_retry_helper(const or_options_t *options, int act)
  3869. {
  3870. const node_t *node;
  3871. int any_known = 0;
  3872. int any_running = 0;
  3873. int need_bridges = options->UseBridges != 0;
  3874. guard_selection_t *gs = get_guard_selection_info();
  3875. tor_assert(gs != NULL);
  3876. tor_assert(gs->chosen_entry_guards != NULL);
  3877. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3878. node = node_get_by_id(e->identity);
  3879. if (node && node_has_descriptor(node) &&
  3880. node_is_bridge(node) == need_bridges &&
  3881. (!need_bridges || (!e->bad_since &&
  3882. node_is_a_configured_bridge(node)))) {
  3883. any_known = 1;
  3884. if (node->is_running)
  3885. any_running = 1; /* some entry is both known and running */
  3886. else if (act) {
  3887. /* Mark all current connections to this OR as unhealthy, since
  3888. * otherwise there could be one that started 30 seconds
  3889. * ago, and in 30 seconds it will time out, causing us to mark
  3890. * the node down and undermine the retry attempt. We mark even
  3891. * the established conns, since if the network just came back
  3892. * we'll want to attach circuits to fresh conns. */
  3893. connection_or_set_bad_connections(node->identity, 1);
  3894. /* mark this entry node for retry */
  3895. router_set_status(node->identity, 1);
  3896. e->can_retry = 1;
  3897. e->bad_since = 0;
  3898. }
  3899. }
  3900. } SMARTLIST_FOREACH_END(e);
  3901. log_debug(LD_DIR, "%d: any_known %d, any_running %d",
  3902. act, any_known, any_running);
  3903. return any_known && !any_running;
  3904. }
  3905. /** Do we know any descriptors for our bridges / entrynodes, and are
  3906. * all the ones we have descriptors for down? */
  3907. int
  3908. entries_known_but_down(const or_options_t *options)
  3909. {
  3910. tor_assert(entry_list_is_constrained(options));
  3911. return entries_retry_helper(options, 0);
  3912. }
  3913. /** Mark all down known bridges / entrynodes up. */
  3914. void
  3915. entries_retry_all(const or_options_t *options)
  3916. {
  3917. tor_assert(entry_list_is_constrained(options));
  3918. entries_retry_helper(options, 1);
  3919. }
  3920. /** Helper: Update the status of all entry guards, in whatever algorithm
  3921. * is used. Return true if we should stop using all previously generated
  3922. * circuits. */
  3923. int
  3924. guards_update_all(void)
  3925. {
  3926. int mark_circuits = 0;
  3927. if (update_guard_selection_choice(get_options()))
  3928. mark_circuits = 1;
  3929. tor_assert(curr_guard_context);
  3930. if (curr_guard_context->type == GS_TYPE_LEGACY) {
  3931. entry_guards_compute_status(get_options(), approx_time());
  3932. } else {
  3933. if (entry_guards_update_all(get_guard_selection_info()))
  3934. mark_circuits = 1;
  3935. }
  3936. return mark_circuits;
  3937. }
  3938. /** Helper: pick a guard for a circuit, with whatever algorithm is
  3939. used. */
  3940. const node_t *
  3941. guards_choose_guard(cpath_build_state_t *state,
  3942. circuit_guard_state_t **guard_state_out)
  3943. {
  3944. if (get_options()->UseDeprecatedGuardAlgorithm) {
  3945. return choose_random_entry(state);
  3946. } else {
  3947. // XXXX prop271 we need to look at the chosen exit node if any, and
  3948. // not duplicate it.
  3949. const node_t *r = NULL;
  3950. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  3951. &r,
  3952. guard_state_out) < 0) {
  3953. tor_assert(r == NULL);
  3954. }
  3955. return r;
  3956. }
  3957. }
  3958. /** Helper: pick a directory guard, with whatever algorithm is used. */
  3959. const node_t *
  3960. guards_choose_dirguard(dirinfo_type_t info,
  3961. circuit_guard_state_t **guard_state_out)
  3962. {
  3963. if (get_options()->UseDeprecatedGuardAlgorithm) {
  3964. return choose_random_dirguard(info);
  3965. } else {
  3966. // XXXX prop271 look at info?
  3967. const node_t *r = NULL;
  3968. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  3969. &r,
  3970. guard_state_out) < 0) {
  3971. tor_assert(r == NULL);
  3972. }
  3973. return r;
  3974. }
  3975. }
  3976. /** Free one guard selection context */
  3977. STATIC void
  3978. guard_selection_free(guard_selection_t *gs)
  3979. {
  3980. if (!gs) return;
  3981. tor_free(gs->name);
  3982. if (gs->chosen_entry_guards) {
  3983. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e,
  3984. entry_guard_free(e));
  3985. smartlist_free(gs->chosen_entry_guards);
  3986. gs->chosen_entry_guards = NULL;
  3987. }
  3988. if (gs->sampled_entry_guards) {
  3989. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
  3990. entry_guard_free(e));
  3991. smartlist_free(gs->sampled_entry_guards);
  3992. gs->sampled_entry_guards = NULL;
  3993. }
  3994. smartlist_free(gs->confirmed_entry_guards);
  3995. smartlist_free(gs->primary_entry_guards);
  3996. tor_free(gs);
  3997. }
  3998. /** Release all storage held by the list of entry guards and related
  3999. * memory structs. */
  4000. void
  4001. entry_guards_free_all(void)
  4002. {
  4003. /* Null out the default */
  4004. curr_guard_context = NULL;
  4005. /* Free all the guard contexts */
  4006. if (guard_contexts != NULL) {
  4007. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  4008. guard_selection_free(gs);
  4009. } SMARTLIST_FOREACH_END(gs);
  4010. smartlist_free(guard_contexts);
  4011. guard_contexts = NULL;
  4012. }
  4013. circuit_build_times_free_timeouts(get_circuit_build_times_mutable());
  4014. }