entrynodes.c 168 KB

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