entrynodes.c 161 KB

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