entrynodes.c 169 KB

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