entrynodes.c 168 KB

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