entrynodes.c 167 KB

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