entrynodes.c 155 KB

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