entrynodes.c 161 KB

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