entrynodes.c 151 KB

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