entrynodes.c 170 KB

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