entrynodes.c 171 KB

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