entrynodes.c 142 KB

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