entrynodes.c 167 KB

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