entrynodes.c 160 KB

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