entrynodes.c 157 KB

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