entrynodes.c 161 KB

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