entrynodes.c 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448
  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. * In general, we use entry guards to prevent traffic-sampling attacks:
  14. * if we chose every circuit independently, an adversary controlling
  15. * some fraction of paths on the network would observe a sample of every
  16. * user's traffic. Using guards gives users a chance of not being
  17. * profiled.
  18. *
  19. * The current entry guard selection code is designed to try to avoid
  20. * _ever_ trying every guard on the network, to try to stick to guards
  21. * that we've used before, to handle hostile/broken networks, and
  22. * to behave sanely when the network goes up and down.
  23. *
  24. * Our algorithm works as follows: First, we maintain a SAMPLE of guards
  25. * we've seen in the networkstatus consensus. We maintain this sample
  26. * over time, and store it persistently; it is chosen without reference
  27. * to our configuration or firewall rules. Guards remain in the sample
  28. * as they enter and leave the consensus. We expand this sample as
  29. * needed, up to a maximum size.
  30. *
  31. * As a subset of the sample, we maintain a FILTERED SET of the guards
  32. * that we would be willing to use if we could connect to them. The
  33. * filter removes all the guards that we're excluding because they're
  34. * bridges (or not bridges), because we have restrictive firewall rules,
  35. * because of ExcludeNodes, because we of path bias restrictions,
  36. * because they're absent from the network at present, and so on.
  37. *
  38. * As a subset of the filtered set, we keep a REACHABLE FILTERED SET
  39. * (also called a "usable filtered set") of those guards that we call
  40. * "reachable" or "maybe reachable". A guard is reachable if we've
  41. * connected to it more recently than we've failed. A guard is "maybe
  42. * reachable" if we have never tried to connect to it, or if we
  43. * failed to connect to it so long ago that we no longer think our
  44. * failure means it's down.
  45. *
  46. * As a persistent ordered list whose elements are taken from the
  47. * sampled set, we track a CONFIRMED GUARDS LIST. A guard becomes
  48. * confirmed when we successfully build a circuit through it, and decide
  49. * to use that circuit. We order the guards on this list by the order
  50. * in which they became confirmed.
  51. *
  52. * And as a final group, we have an ordered list of PRIMARY GUARDS,
  53. * whose elements are taken from the filtered set. We prefer
  54. * confirmed guards to non-confirmed guards for this list, and place
  55. * other restrictions on it. The primary guards are the ones that we
  56. * connect to "when nothing is wrong" -- circuits through them can be used
  57. * immediately.
  58. *
  59. * To build circuits, we take a primary guard if possible -- or a
  60. * reachable filtered confirmed guard if no primary guard is possible --
  61. * or a random reachable filtered guard otherwise. If the guard is
  62. * primary, we can use the circuit immediately on success. Otherwise,
  63. * the guard is now "pending" -- we won't use its circuit unless all
  64. * of the circuits we're trying to build through better guards have
  65. * definitely failed.
  66. *
  67. * While we're building circuits, we track a little "guard state" for
  68. * each circuit. We use this to keep track of whether the circuit is
  69. * one that we can use as soon as its done, or whether it's one that
  70. * we should keep around to see if we can do better. In the latter case,
  71. * a periodic call to entry_guards_upgrade_waiting_circuits() will
  72. * eventually upgrade it.
  73. **/
  74. /* DOCDOC -- expand this.
  75. *
  76. * Information invariants:
  77. *
  78. * [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
  79. *
  80. * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
  81. * flag is set, set its usable_filtered flag.
  82. *
  83. * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
  84. *
  85. * [x] Whenever the configuration changes in a relevant way, update the
  86. * filtered/usable flags. (LATER.)
  87. *
  88. * [x] Whenever we add a guard to the sample, make sure its filtered/usable
  89. * flags are set as possible.
  90. *
  91. * [x] Whenever we remove a guard from the sample, remove it from the primary
  92. * and confirmed lists.
  93. *
  94. * [x] When we make a guard confirmed, update the primary list.
  95. *
  96. * [x] When we make a guard filtered or unfiltered, update the primary list.
  97. *
  98. * [x] When we are about to pick a guard, make sure that the primary list is
  99. * full.
  100. *
  101. * [x] Before calling sample_reachable_filtered_entry_guards(), make sure
  102. * that the filtered, primary, and confirmed flags are up-to-date.
  103. *
  104. * [x] Call entry_guard_consider_retry every time we are about to check
  105. * is_usable_filtered or is_reachable, and every time we set
  106. * is_filtered to 1.
  107. *
  108. * [x] Call entry_guards_changed_for_guard_selection() whenever we update
  109. * a persistent field.
  110. */
  111. #define ENTRYNODES_PRIVATE
  112. #include "or.h"
  113. #include "channel.h"
  114. #include "bridges.h"
  115. #include "circpathbias.h"
  116. #include "circuitbuild.h"
  117. #include "circuitlist.h"
  118. #include "circuitstats.h"
  119. #include "config.h"
  120. #include "confparse.h"
  121. #include "connection.h"
  122. #include "control.h"
  123. #include "directory.h"
  124. #include "entrynodes.h"
  125. #include "main.h"
  126. #include "microdesc.h"
  127. #include "networkstatus.h"
  128. #include "nodelist.h"
  129. #include "policies.h"
  130. #include "router.h"
  131. #include "routerlist.h"
  132. #include "routerparse.h"
  133. #include "routerset.h"
  134. #include "transports.h"
  135. #include "statefile.h"
  136. /** A list of existing guard selection contexts. */
  137. static smartlist_t *guard_contexts = NULL;
  138. /** The currently enabled guard selection context. */
  139. static guard_selection_t *curr_guard_context = NULL;
  140. /** A value of 1 means that at least one context has changed,
  141. * and those changes need to be flushed to disk. */
  142. static int entry_guards_dirty = 0;
  143. static void entry_guard_set_filtered_flags(const or_options_t *options,
  144. guard_selection_t *gs,
  145. entry_guard_t *guard);
  146. static void pathbias_check_use_success_count(entry_guard_t *guard);
  147. static void pathbias_check_close_success_count(entry_guard_t *guard);
  148. static int node_is_possible_guard(const node_t *node);
  149. static int node_passes_guard_filter(const or_options_t *options,
  150. const node_t *node);
  151. static entry_guard_t *entry_guard_add_to_sample_impl(guard_selection_t *gs,
  152. const uint8_t *rsa_id_digest,
  153. const char *nickname,
  154. const tor_addr_port_t *bridge_addrport);
  155. static entry_guard_t *get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
  156. const tor_addr_port_t *addrport);
  157. static int entry_guard_obeys_restriction(const entry_guard_t *guard,
  158. const entry_guard_restriction_t *rst);
  159. /** Return 0 if we should apply guardfraction information found in the
  160. * consensus. A specific consensus can be specified with the
  161. * <b>ns</b> argument, if NULL the most recent one will be picked.*/
  162. int
  163. should_apply_guardfraction(const networkstatus_t *ns)
  164. {
  165. /* We need to check the corresponding torrc option and the consensus
  166. * parameter if we need to. */
  167. const or_options_t *options = get_options();
  168. /* If UseGuardFraction is 'auto' then check the same-named consensus
  169. * parameter. If the consensus parameter is not present, default to
  170. * "off". */
  171. if (options->UseGuardFraction == -1) {
  172. return networkstatus_get_param(ns, "UseGuardFraction",
  173. 0, /* default to "off" */
  174. 0, 1);
  175. }
  176. return options->UseGuardFraction;
  177. }
  178. /** Return true iff we know a descriptor for <b>guard</b> */
  179. static int
  180. guard_has_descriptor(const entry_guard_t *guard)
  181. {
  182. const node_t *node = node_get_by_id(guard->identity);
  183. if (!node)
  184. return 0;
  185. return node_has_descriptor(node);
  186. }
  187. /**
  188. * Try to determine the correct type for a selection named "name",
  189. * if <b>type</b> is GS_TYPE_INFER.
  190. */
  191. STATIC guard_selection_type_t
  192. guard_selection_infer_type(guard_selection_type_t type,
  193. const char *name)
  194. {
  195. if (type == GS_TYPE_INFER) {
  196. if (!strcmp(name, "bridges"))
  197. type = GS_TYPE_BRIDGE;
  198. else if (!strcmp(name, "restricted"))
  199. type = GS_TYPE_RESTRICTED;
  200. else
  201. type = GS_TYPE_NORMAL;
  202. }
  203. return type;
  204. }
  205. /**
  206. * Allocate and return a new guard_selection_t, with the name <b>name</b>.
  207. */
  208. STATIC guard_selection_t *
  209. guard_selection_new(const char *name,
  210. guard_selection_type_t type)
  211. {
  212. guard_selection_t *gs;
  213. type = guard_selection_infer_type(type, name);
  214. gs = tor_malloc_zero(sizeof(*gs));
  215. gs->name = tor_strdup(name);
  216. gs->type = type;
  217. gs->sampled_entry_guards = smartlist_new();
  218. gs->confirmed_entry_guards = smartlist_new();
  219. gs->primary_entry_guards = smartlist_new();
  220. return gs;
  221. }
  222. /**
  223. * Return the guard selection called <b>name</b>. If there is none, and
  224. * <b>create_if_absent</b> is true, then create and return it. If there
  225. * is none, and <b>create_if_absent</b> is false, then return NULL.
  226. */
  227. STATIC guard_selection_t *
  228. get_guard_selection_by_name(const char *name,
  229. guard_selection_type_t type,
  230. int create_if_absent)
  231. {
  232. if (!guard_contexts) {
  233. guard_contexts = smartlist_new();
  234. }
  235. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  236. if (!strcmp(gs->name, name))
  237. return gs;
  238. } SMARTLIST_FOREACH_END(gs);
  239. if (! create_if_absent)
  240. return NULL;
  241. log_debug(LD_GUARD, "Creating a guard selection called %s", name);
  242. guard_selection_t *new_selection = guard_selection_new(name, type);
  243. smartlist_add(guard_contexts, new_selection);
  244. return new_selection;
  245. }
  246. /**
  247. * Allocate the first guard context that we're planning to use,
  248. * and make it the current context.
  249. */
  250. static void
  251. create_initial_guard_context(void)
  252. {
  253. tor_assert(! curr_guard_context);
  254. if (!guard_contexts) {
  255. guard_contexts = smartlist_new();
  256. }
  257. guard_selection_type_t type = GS_TYPE_INFER;
  258. const char *name = choose_guard_selection(
  259. get_options(),
  260. networkstatus_get_live_consensus(approx_time()),
  261. NULL,
  262. &type);
  263. tor_assert(name); // "name" can only be NULL if we had an old name.
  264. tor_assert(type != GS_TYPE_INFER);
  265. log_notice(LD_GUARD, "Starting with guard context \"%s\"", name);
  266. curr_guard_context = get_guard_selection_by_name(name, type, 1);
  267. }
  268. /** Get current default guard_selection_t, creating it if necessary */
  269. guard_selection_t *
  270. get_guard_selection_info(void)
  271. {
  272. if (!curr_guard_context) {
  273. create_initial_guard_context();
  274. }
  275. return curr_guard_context;
  276. }
  277. /** Return a statically allocated human-readable description of <b>guard</b>
  278. */
  279. const char *
  280. entry_guard_describe(const entry_guard_t *guard)
  281. {
  282. static char buf[256];
  283. tor_snprintf(buf, sizeof(buf),
  284. "%s ($%s)",
  285. strlen(guard->nickname) ? guard->nickname : "[bridge]",
  286. hex_str(guard->identity, DIGEST_LEN));
  287. return buf;
  288. }
  289. /** Return <b>guard</b>'s 20-byte RSA identity digest */
  290. const char *
  291. entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
  292. {
  293. return guard->identity;
  294. }
  295. /** Return the pathbias state associated with <b>guard</b>. */
  296. guard_pathbias_t *
  297. entry_guard_get_pathbias_state(entry_guard_t *guard)
  298. {
  299. return &guard->pb;
  300. }
  301. HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC)
  302. /** Return an interval betweeen 'now' and 'max_backdate' seconds in the past,
  303. * chosen uniformly at random. We use this before recording persistent
  304. * dates, so that we aren't leaking exactly when we recorded it.
  305. */
  306. MOCK_IMPL(STATIC time_t,
  307. randomize_time,(time_t now, time_t max_backdate))
  308. {
  309. tor_assert(max_backdate > 0);
  310. time_t earliest = now - max_backdate;
  311. time_t latest = now;
  312. if (earliest <= 0)
  313. earliest = 1;
  314. if (latest <= earliest)
  315. latest = earliest + 1;
  316. return crypto_rand_time_range(earliest, latest);
  317. }
  318. /**
  319. * @name parameters for networkstatus algorithm
  320. *
  321. * These parameters are taken from the consensus; some are overrideable in
  322. * the torrc.
  323. */
  324. /**@{*/
  325. /**
  326. * We never let our sampled guard set grow larger than this fraction
  327. * of the guards on the network.
  328. */
  329. STATIC double
  330. get_max_sample_threshold(void)
  331. {
  332. int32_t pct =
  333. networkstatus_get_param(NULL, "guard-max-sample-threshold-percent",
  334. DFLT_MAX_SAMPLE_THRESHOLD_PERCENT,
  335. 1, 100);
  336. return pct / 100.0;
  337. }
  338. /**
  339. * We never let our sampled guard set grow larger than this number.
  340. */
  341. STATIC int
  342. get_max_sample_size_absolute(void)
  343. {
  344. return (int) networkstatus_get_param(NULL, "guard-max-sample-size",
  345. DFLT_MAX_SAMPLE_SIZE,
  346. 1, INT32_MAX);
  347. }
  348. /**
  349. * We always try to make our sample contain at least this many guards.
  350. */
  351. STATIC int
  352. get_min_filtered_sample_size(void)
  353. {
  354. return networkstatus_get_param(NULL, "guard-min-filtered-sample-size",
  355. DFLT_MIN_FILTERED_SAMPLE_SIZE,
  356. 1, INT32_MAX);
  357. }
  358. /**
  359. * If a guard is unlisted for this many days in a row, we remove it.
  360. */
  361. STATIC int
  362. get_remove_unlisted_guards_after_days(void)
  363. {
  364. return networkstatus_get_param(NULL,
  365. "guard-remove-unlisted-guards-after-days",
  366. DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS,
  367. 1, 365*10);
  368. }
  369. /**
  370. * We remove unconfirmed guards from the sample after this many days,
  371. * regardless of whether they are listed or unlisted.
  372. */
  373. STATIC int
  374. get_guard_lifetime(void)
  375. {
  376. if (get_options()->GuardLifetime >= 86400)
  377. return get_options()->GuardLifetime;
  378. int32_t days;
  379. days = networkstatus_get_param(NULL,
  380. "guard-lifetime-days",
  381. DFLT_GUARD_LIFETIME_DAYS, 1, 365*10);
  382. return days * 86400;
  383. }
  384. /**
  385. * We remove confirmed guards from the sample if they were sampled
  386. * GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
  387. */
  388. STATIC int
  389. get_guard_confirmed_min_lifetime(void)
  390. {
  391. if (get_options()->GuardLifetime >= 86400)
  392. return get_options()->GuardLifetime;
  393. int32_t days;
  394. days = networkstatus_get_param(NULL, "guard-confirmed-min-lifetime-days",
  395. DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS,
  396. 1, 365*10);
  397. return days * 86400;
  398. }
  399. /**
  400. * How many guards do we try to keep on our primary guard list?
  401. */
  402. STATIC int
  403. get_n_primary_guards(void)
  404. {
  405. const int n = get_options()->NumEntryGuards;
  406. const int n_dir = get_options()->NumDirectoryGuards;
  407. if (n > 5) {
  408. return MAX(n_dir, n + n / 2);
  409. } else if (n >= 1) {
  410. return MAX(n_dir, n * 2);
  411. }
  412. return networkstatus_get_param(NULL,
  413. "guard-n-primary-guards",
  414. DFLT_N_PRIMARY_GUARDS, 1, INT32_MAX);
  415. }
  416. /**
  417. * Return the number of the live primary guards we should look at when
  418. * making a circuit.
  419. */
  420. STATIC int
  421. get_n_primary_guards_to_use(guard_usage_t usage)
  422. {
  423. int configured;
  424. const char *param_name;
  425. int param_default;
  426. if (usage == GUARD_USAGE_DIRGUARD) {
  427. configured = get_options()->NumDirectoryGuards;
  428. param_name = "guard-n-primary-dir-guards-to-use";
  429. param_default = DFLT_N_PRIMARY_DIR_GUARDS_TO_USE;
  430. } else {
  431. configured = get_options()->NumEntryGuards;
  432. param_name = "guard-n-primary-guards-to-use";
  433. param_default = DFLT_N_PRIMARY_GUARDS_TO_USE;
  434. }
  435. if (configured >= 1) {
  436. return configured;
  437. }
  438. return networkstatus_get_param(NULL,
  439. param_name, param_default, 1, INT32_MAX);
  440. }
  441. /**
  442. * If we haven't successfully built or used a circuit in this long, then
  443. * consider that the internet is probably down.
  444. */
  445. STATIC int
  446. get_internet_likely_down_interval(void)
  447. {
  448. return networkstatus_get_param(NULL, "guard-internet-likely-down-interval",
  449. DFLT_INTERNET_LIKELY_DOWN_INTERVAL,
  450. 1, INT32_MAX);
  451. }
  452. /**
  453. * If we're trying to connect to a nonprimary guard for at least this
  454. * many seconds, and we haven't gotten the connection to work, we will treat
  455. * lower-priority guards as usable.
  456. */
  457. STATIC int
  458. get_nonprimary_guard_connect_timeout(void)
  459. {
  460. return networkstatus_get_param(NULL,
  461. "guard-nonprimary-guard-connect-timeout",
  462. DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT,
  463. 1, INT32_MAX);
  464. }
  465. /**
  466. * If a circuit has been sitting around in 'waiting for better guard' state
  467. * for at least this long, we'll expire it.
  468. */
  469. STATIC int
  470. get_nonprimary_guard_idle_timeout(void)
  471. {
  472. return networkstatus_get_param(NULL,
  473. "guard-nonprimary-guard-idle-timeout",
  474. DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT,
  475. 1, INT32_MAX);
  476. }
  477. /**
  478. * If our configuration retains fewer than this fraction of guards from the
  479. * torrc, we are in a restricted setting.
  480. */
  481. STATIC double
  482. get_meaningful_restriction_threshold(void)
  483. {
  484. int32_t pct = networkstatus_get_param(NULL,
  485. "guard-meaningful-restriction-percent",
  486. DFLT_MEANINGFUL_RESTRICTION_PERCENT,
  487. 1, INT32_MAX);
  488. return pct / 100.0;
  489. }
  490. /**
  491. * If our configuration retains fewer than this fraction of guards from the
  492. * torrc, we are in an extremely restricted setting, and should warn.
  493. */
  494. STATIC double
  495. get_extreme_restriction_threshold(void)
  496. {
  497. int32_t pct = networkstatus_get_param(NULL,
  498. "guard-extreme-restriction-percent",
  499. DFLT_EXTREME_RESTRICTION_PERCENT,
  500. 1, INT32_MAX);
  501. return pct / 100.0;
  502. }
  503. /* Mark <b>guard</b> as maybe reachable again. */
  504. static void
  505. mark_guard_maybe_reachable(entry_guard_t *guard)
  506. {
  507. if (guard->is_reachable != GUARD_REACHABLE_NO) {
  508. return;
  509. }
  510. /* Note that we do not clear failing_since: this guard is now only
  511. * _maybe-reachable_. */
  512. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  513. if (guard->is_filtered_guard)
  514. guard->is_usable_filtered_guard = 1;
  515. }
  516. /**
  517. * Called when the network comes up after having seemed to be down for
  518. * a while: Mark the primary guards as maybe-reachable so that we'll
  519. * try them again.
  520. */
  521. STATIC void
  522. mark_primary_guards_maybe_reachable(guard_selection_t *gs)
  523. {
  524. tor_assert(gs);
  525. if (!gs->primary_guards_up_to_date)
  526. entry_guards_update_primary(gs);
  527. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  528. mark_guard_maybe_reachable(guard);
  529. } SMARTLIST_FOREACH_END(guard);
  530. }
  531. /* Called when we exhaust all guards in our sampled set: Marks all guards as
  532. maybe-reachable so that we 'll try them again. */
  533. static void
  534. mark_all_guards_maybe_reachable(guard_selection_t *gs)
  535. {
  536. tor_assert(gs);
  537. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  538. mark_guard_maybe_reachable(guard);
  539. } SMARTLIST_FOREACH_END(guard);
  540. }
  541. /**@}*/
  542. /**
  543. * Given our options and our list of nodes, return the name of the
  544. * guard selection that we should use. Return NULL for "use the
  545. * same selection you were using before.
  546. */
  547. STATIC const char *
  548. choose_guard_selection(const or_options_t *options,
  549. const networkstatus_t *live_ns,
  550. const guard_selection_t *old_selection,
  551. guard_selection_type_t *type_out)
  552. {
  553. tor_assert(options);
  554. tor_assert(type_out);
  555. if (options->UseBridges) {
  556. *type_out = GS_TYPE_BRIDGE;
  557. return "bridges";
  558. }
  559. if (! live_ns) {
  560. /* without a networkstatus, we can't tell any more than that. */
  561. *type_out = GS_TYPE_NORMAL;
  562. return "default";
  563. }
  564. const smartlist_t *nodes = nodelist_get_list();
  565. int n_guards = 0, n_passing_filter = 0;
  566. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  567. if (node_is_possible_guard(node)) {
  568. ++n_guards;
  569. if (node_passes_guard_filter(options, node)) {
  570. ++n_passing_filter;
  571. }
  572. }
  573. } SMARTLIST_FOREACH_END(node);
  574. /* We use separate 'high' and 'low' thresholds here to prevent flapping
  575. * back and forth */
  576. const int meaningful_threshold_high =
  577. (int)(n_guards * get_meaningful_restriction_threshold() * 1.05);
  578. const int meaningful_threshold_mid =
  579. (int)(n_guards * get_meaningful_restriction_threshold());
  580. const int meaningful_threshold_low =
  581. (int)(n_guards * get_meaningful_restriction_threshold() * .95);
  582. const int extreme_threshold =
  583. (int)(n_guards * get_extreme_restriction_threshold());
  584. /*
  585. If we have no previous selection, then we're "restricted" iff we are
  586. below the meaningful restriction threshold. That's easy enough.
  587. But if we _do_ have a previous selection, we make it a little
  588. "sticky": we only move from "restricted" to "default" when we find
  589. that we're above the threshold plus 5%, and we only move from
  590. "default" to "restricted" when we're below the threshold minus 5%.
  591. That should prevent us from flapping back and forth if we happen to
  592. be hovering very close to the default.
  593. The extreme threshold is for warning only.
  594. */
  595. static int have_warned_extreme_threshold = 0;
  596. if (n_guards &&
  597. n_passing_filter < extreme_threshold &&
  598. ! have_warned_extreme_threshold) {
  599. have_warned_extreme_threshold = 1;
  600. const double exclude_frac =
  601. (n_guards - n_passing_filter) / (double)n_guards;
  602. log_warn(LD_GUARD, "Your configuration excludes %d%% of all possible "
  603. "guards. That's likely to make you stand out from the "
  604. "rest of the world.", (int)(exclude_frac * 100));
  605. }
  606. /* Easy case: no previous selection. Just check if we are in restricted or
  607. normal guard selection. */
  608. if (old_selection == NULL) {
  609. if (n_passing_filter >= meaningful_threshold_mid) {
  610. *type_out = GS_TYPE_NORMAL;
  611. return "default";
  612. } else {
  613. *type_out = GS_TYPE_RESTRICTED;
  614. return "restricted";
  615. }
  616. }
  617. /* Trickier case: we do have a previous guard selection context. */
  618. tor_assert(old_selection);
  619. /* Use high and low thresholds to decide guard selection, and if we fall in
  620. the middle then keep the current guard selection context. */
  621. if (n_passing_filter >= meaningful_threshold_high) {
  622. *type_out = GS_TYPE_NORMAL;
  623. return "default";
  624. } else if (n_passing_filter < meaningful_threshold_low) {
  625. *type_out = GS_TYPE_RESTRICTED;
  626. return "restricted";
  627. } else {
  628. /* we are in the middle: maintain previous guard selection */
  629. *type_out = old_selection->type;
  630. return old_selection->name;
  631. }
  632. }
  633. /**
  634. * Check whether we should switch from our current guard selection to a
  635. * different one. If so, switch and return 1. Return 0 otherwise.
  636. *
  637. * On a 1 return, the caller should mark all currently live circuits unusable
  638. * for new streams, by calling circuit_mark_all_unused_circs() and
  639. * circuit_mark_all_dirty_circs_as_unusable().
  640. */
  641. int
  642. update_guard_selection_choice(const or_options_t *options)
  643. {
  644. if (!curr_guard_context) {
  645. create_initial_guard_context();
  646. return 1;
  647. }
  648. guard_selection_type_t type = GS_TYPE_INFER;
  649. const char *new_name = choose_guard_selection(
  650. options,
  651. networkstatus_get_live_consensus(approx_time()),
  652. curr_guard_context,
  653. &type);
  654. tor_assert(new_name);
  655. tor_assert(type != GS_TYPE_INFER);
  656. const char *cur_name = curr_guard_context->name;
  657. if (! strcmp(cur_name, new_name)) {
  658. log_debug(LD_GUARD,
  659. "Staying with guard context \"%s\" (no change)", new_name);
  660. return 0; // No change
  661. }
  662. log_notice(LD_GUARD, "Switching to guard context \"%s\" (was using \"%s\")",
  663. new_name, cur_name);
  664. guard_selection_t *new_guard_context;
  665. new_guard_context = get_guard_selection_by_name(new_name, type, 1);
  666. tor_assert(new_guard_context);
  667. tor_assert(new_guard_context != curr_guard_context);
  668. curr_guard_context = new_guard_context;
  669. return 1;
  670. }
  671. /**
  672. * Return true iff <b>node</b> has all the flags needed for us to consider it
  673. * a possible guard when sampling guards.
  674. */
  675. static int
  676. node_is_possible_guard(const node_t *node)
  677. {
  678. /* The "GUARDS" set is all nodes in the nodelist for which this predicate
  679. * holds. */
  680. tor_assert(node);
  681. return (node->is_possible_guard &&
  682. node->is_stable &&
  683. node->is_fast &&
  684. node->is_valid &&
  685. node_is_dir(node));
  686. }
  687. /**
  688. * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
  689. * NULL if we don't have one. */
  690. STATIC entry_guard_t *
  691. get_sampled_guard_with_id(guard_selection_t *gs,
  692. const uint8_t *rsa_id)
  693. {
  694. tor_assert(gs);
  695. tor_assert(rsa_id);
  696. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  697. if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN))
  698. return guard;
  699. } SMARTLIST_FOREACH_END(guard);
  700. return NULL;
  701. }
  702. /** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>,
  703. * return that guard. Otherwise return NULL. */
  704. static entry_guard_t *
  705. get_sampled_guard_for_bridge(guard_selection_t *gs,
  706. const bridge_info_t *bridge)
  707. {
  708. const uint8_t *id = bridge_get_rsa_id_digest(bridge);
  709. const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
  710. entry_guard_t *guard;
  711. if (BUG(!addrport))
  712. return NULL; // LCOV_EXCL_LINE
  713. guard = get_sampled_guard_by_bridge_addr(gs, addrport);
  714. if (! guard || (id && tor_memneq(id, guard->identity, DIGEST_LEN)))
  715. return NULL;
  716. else
  717. return guard;
  718. }
  719. /** If we know a bridge_info_t matching <b>guard</b>, return that
  720. * bridge. Otherwise return NULL. */
  721. static bridge_info_t *
  722. get_bridge_info_for_guard(const entry_guard_t *guard)
  723. {
  724. const uint8_t *identity = NULL;
  725. if (! tor_digest_is_zero(guard->identity)) {
  726. identity = (const uint8_t *)guard->identity;
  727. }
  728. if (BUG(guard->bridge_addr == NULL))
  729. return NULL;
  730. return get_configured_bridge_by_exact_addr_port_digest(
  731. &guard->bridge_addr->addr,
  732. guard->bridge_addr->port,
  733. (const char*)identity);
  734. }
  735. /**
  736. * Return true iff we have a sampled guard with the RSA identity digest
  737. * <b>rsa_id</b>. */
  738. static inline int
  739. have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
  740. {
  741. return get_sampled_guard_with_id(gs, rsa_id) != NULL;
  742. }
  743. /**
  744. * Allocate a new entry_guard_t object for <b>node</b>, add it to the
  745. * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
  746. * not currently be a sampled guard in <b>gs</b>.
  747. */
  748. STATIC entry_guard_t *
  749. entry_guard_add_to_sample(guard_selection_t *gs,
  750. const node_t *node)
  751. {
  752. log_info(LD_GUARD, "Adding %s as to the entry guard sample set.",
  753. node_describe(node));
  754. /* make sure that the guard is not already sampled. */
  755. if (BUG(have_sampled_guard_with_id(gs, (const uint8_t*)node->identity)))
  756. return NULL; // LCOV_EXCL_LINE
  757. return entry_guard_add_to_sample_impl(gs,
  758. (const uint8_t*)node->identity,
  759. node_get_nickname(node),
  760. NULL);
  761. }
  762. /**
  763. * Backend: adds a new sampled guard to <b>gs</b>, with given identity,
  764. * nickname, and ORPort. rsa_id_digest and bridge_addrport are optional, but
  765. * we need one of them. nickname is optional. The caller is responsible for
  766. * maintaining the size limit of the SAMPLED_GUARDS set.
  767. */
  768. static entry_guard_t *
  769. entry_guard_add_to_sample_impl(guard_selection_t *gs,
  770. const uint8_t *rsa_id_digest,
  771. const char *nickname,
  772. const tor_addr_port_t *bridge_addrport)
  773. {
  774. const int GUARD_LIFETIME = get_guard_lifetime();
  775. tor_assert(gs);
  776. // XXXX #20827 take ed25519 identity here too.
  777. /* Make sure we can actually identify the guard. */
  778. if (BUG(!rsa_id_digest && !bridge_addrport))
  779. return NULL; // LCOV_EXCL_LINE
  780. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  781. /* persistent fields */
  782. guard->is_persistent = (rsa_id_digest != NULL);
  783. guard->selection_name = tor_strdup(gs->name);
  784. if (rsa_id_digest)
  785. memcpy(guard->identity, rsa_id_digest, DIGEST_LEN);
  786. if (nickname)
  787. strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  788. guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  789. tor_free(guard->sampled_by_version);
  790. guard->sampled_by_version = tor_strdup(VERSION);
  791. guard->currently_listed = 1;
  792. guard->confirmed_idx = -1;
  793. /* non-persistent fields */
  794. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  795. if (bridge_addrport)
  796. guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport));
  797. smartlist_add(gs->sampled_entry_guards, guard);
  798. guard->in_selection = gs;
  799. entry_guard_set_filtered_flags(get_options(), gs, guard);
  800. entry_guards_changed_for_guard_selection(gs);
  801. return guard;
  802. }
  803. /**
  804. * Add an entry guard to the "bridges" guard selection sample, with
  805. * information taken from <b>bridge</b>. Return that entry guard.
  806. */
  807. static entry_guard_t *
  808. entry_guard_add_bridge_to_sample(guard_selection_t *gs,
  809. const bridge_info_t *bridge)
  810. {
  811. const uint8_t *id_digest = bridge_get_rsa_id_digest(bridge);
  812. const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
  813. tor_assert(addrport);
  814. /* make sure that the guard is not already sampled. */
  815. if (BUG(get_sampled_guard_for_bridge(gs, bridge)))
  816. return NULL; // LCOV_EXCL_LINE
  817. return entry_guard_add_to_sample_impl(gs, id_digest, NULL, addrport);
  818. }
  819. /**
  820. * Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>,
  821. * or NULL if none exists.
  822. */
  823. static entry_guard_t *
  824. get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
  825. const tor_addr_port_t *addrport)
  826. {
  827. if (! gs)
  828. return NULL;
  829. if (BUG(!addrport))
  830. return NULL;
  831. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, g) {
  832. if (g->bridge_addr && tor_addr_port_eq(addrport, g->bridge_addr))
  833. return g;
  834. } SMARTLIST_FOREACH_END(g);
  835. return NULL;
  836. }
  837. /** Update the guard subsystem's knowledge of the identity of the bridge
  838. * at <b>addrport</b>. Idempotent.
  839. */
  840. void
  841. entry_guard_learned_bridge_identity(const tor_addr_port_t *addrport,
  842. const uint8_t *rsa_id_digest)
  843. {
  844. guard_selection_t *gs = get_guard_selection_by_name("bridges",
  845. GS_TYPE_BRIDGE,
  846. 0);
  847. if (!gs)
  848. return;
  849. entry_guard_t *g = get_sampled_guard_by_bridge_addr(gs, addrport);
  850. if (!g)
  851. return;
  852. int make_persistent = 0;
  853. if (tor_digest_is_zero(g->identity)) {
  854. memcpy(g->identity, rsa_id_digest, DIGEST_LEN);
  855. make_persistent = 1;
  856. } else if (tor_memeq(g->identity, rsa_id_digest, DIGEST_LEN)) {
  857. /* Nothing to see here; we learned something we already knew. */
  858. if (BUG(! g->is_persistent))
  859. make_persistent = 1;
  860. } else {
  861. char old_id[HEX_DIGEST_LEN+1];
  862. base16_encode(old_id, sizeof(old_id), g->identity, sizeof(g->identity));
  863. log_warn(LD_BUG, "We 'learned' an identity %s for a bridge at %s:%d, but "
  864. "we already knew a different one (%s). Ignoring the new info as "
  865. "possibly bogus.",
  866. hex_str((const char *)rsa_id_digest, DIGEST_LEN),
  867. fmt_and_decorate_addr(&addrport->addr), addrport->port,
  868. old_id);
  869. return; // redundant, but let's be clear: we're not making this persistent.
  870. }
  871. if (make_persistent) {
  872. g->is_persistent = 1;
  873. entry_guards_changed_for_guard_selection(gs);
  874. }
  875. }
  876. /**
  877. * Return the number of sampled guards in <b>gs</b> that are "filtered"
  878. * (that is, we're willing to connect to them) and that are "usable"
  879. * (that is, either "reachable" or "maybe reachable").
  880. *
  881. * If a restriction is provided in <b>rst</b>, do not count any guards that
  882. * violate it.
  883. */
  884. STATIC int
  885. num_reachable_filtered_guards(guard_selection_t *gs,
  886. const entry_guard_restriction_t *rst)
  887. {
  888. int n_reachable_filtered_guards = 0;
  889. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  890. entry_guard_consider_retry(guard);
  891. if (! entry_guard_obeys_restriction(guard, rst))
  892. continue;
  893. if (guard->is_usable_filtered_guard)
  894. ++n_reachable_filtered_guards;
  895. } SMARTLIST_FOREACH_END(guard);
  896. return n_reachable_filtered_guards;
  897. }
  898. /** Return the actual maximum size for the sample in <b>gs</b>,
  899. * given that we know about <b>n_guards</b> total. */
  900. static int
  901. get_max_sample_size(guard_selection_t *gs,
  902. int n_guards)
  903. {
  904. const int using_bridges = (gs->type == GS_TYPE_BRIDGE);
  905. const int min_sample = get_min_filtered_sample_size();
  906. /* If we are in bridge mode, expand our sample set as needed without worrying
  907. * about max size. We should respect the user's wishes to use many bridges if
  908. * that's what they have specified in their configuration file. */
  909. if (using_bridges)
  910. return INT_MAX;
  911. const int max_sample_by_pct = (int)(n_guards * get_max_sample_threshold());
  912. const int max_sample_absolute = get_max_sample_size_absolute();
  913. const int max_sample = MIN(max_sample_by_pct, max_sample_absolute);
  914. if (max_sample < min_sample)
  915. return min_sample;
  916. else
  917. return max_sample;
  918. }
  919. /**
  920. * Return a smartlist of the all the guards that are not currently
  921. * members of the sample (GUARDS - SAMPLED_GUARDS). The elements of
  922. * this list are node_t pointers in the non-bridge case, and
  923. * bridge_info_t pointers in the bridge case. Set *<b>n_guards_out/b>
  924. * to the number of guards that we found in GUARDS, including those
  925. * that were already sampled.
  926. */
  927. static smartlist_t *
  928. get_eligible_guards(const or_options_t *options,
  929. guard_selection_t *gs,
  930. int *n_guards_out)
  931. {
  932. /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
  933. smartlist_t *eligible_guards = smartlist_new();
  934. int n_guards = 0; // total size of "GUARDS"
  935. if (gs->type == GS_TYPE_BRIDGE) {
  936. const smartlist_t *bridges = bridge_list_get();
  937. SMARTLIST_FOREACH_BEGIN(bridges, bridge_info_t *, bridge) {
  938. ++n_guards;
  939. if (NULL != get_sampled_guard_for_bridge(gs, bridge)) {
  940. continue;
  941. }
  942. smartlist_add(eligible_guards, bridge);
  943. } SMARTLIST_FOREACH_END(bridge);
  944. } else {
  945. const smartlist_t *nodes = nodelist_get_list();
  946. const int n_sampled = smartlist_len(gs->sampled_entry_guards);
  947. /* Build a bloom filter of our current guards: let's keep this O(N). */
  948. digestset_t *sampled_guard_ids = digestset_new(n_sampled);
  949. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *,
  950. guard) {
  951. digestset_add(sampled_guard_ids, guard->identity);
  952. } SMARTLIST_FOREACH_END(guard);
  953. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  954. if (! node_is_possible_guard(node))
  955. continue;
  956. if (gs->type == GS_TYPE_RESTRICTED) {
  957. /* In restricted mode, we apply the filter BEFORE sampling, so
  958. * that we are sampling from the nodes that we might actually
  959. * select. If we sampled first, we might wind up with a sample
  960. * that didn't include any EntryNodes at all. */
  961. if (! node_passes_guard_filter(options, node))
  962. continue;
  963. }
  964. ++n_guards;
  965. if (digestset_contains(sampled_guard_ids, node->identity))
  966. continue;
  967. smartlist_add(eligible_guards, (node_t*)node);
  968. } SMARTLIST_FOREACH_END(node);
  969. /* Now we can free that bloom filter. */
  970. digestset_free(sampled_guard_ids);
  971. }
  972. *n_guards_out = n_guards;
  973. return eligible_guards;
  974. }
  975. /** Helper: given a smartlist of either bridge_info_t (if gs->type is
  976. * GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard,
  977. * add it as a guard, remove it from the list, and return a new
  978. * entry_guard_t. Return NULL on failure. */
  979. static entry_guard_t *
  980. select_and_add_guard_item_for_sample(guard_selection_t *gs,
  981. smartlist_t *eligible_guards)
  982. {
  983. entry_guard_t *added_guard;
  984. if (gs->type == GS_TYPE_BRIDGE) {
  985. const bridge_info_t *bridge = smartlist_choose(eligible_guards);
  986. if (BUG(!bridge))
  987. return NULL; // LCOV_EXCL_LINE
  988. smartlist_remove(eligible_guards, bridge);
  989. added_guard = entry_guard_add_bridge_to_sample(gs, bridge);
  990. } else {
  991. const node_t *node =
  992. node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD);
  993. if (BUG(!node))
  994. return NULL; // LCOV_EXCL_LINE
  995. smartlist_remove(eligible_guards, node);
  996. added_guard = entry_guard_add_to_sample(gs, node);
  997. }
  998. return added_guard;
  999. }
  1000. /**
  1001. * Add new guards to the sampled guards in <b>gs</b> until there are
  1002. * enough usable filtered guards, but never grow the sample beyond its
  1003. * maximum size. Return the last guard added, or NULL if none were
  1004. * added.
  1005. */
  1006. STATIC entry_guard_t *
  1007. entry_guards_expand_sample(guard_selection_t *gs)
  1008. {
  1009. tor_assert(gs);
  1010. const or_options_t *options = get_options();
  1011. if (gs->type != GS_TYPE_BRIDGE) {
  1012. networkstatus_t *consensus = networkstatus_get_latest_consensus();
  1013. time_t now = approx_time();
  1014. if (consensus == NULL) {
  1015. log_info(LD_GUARD, "Not expanding the sample guard set; we have "
  1016. "no consensus.");
  1017. return NULL;
  1018. } else if (!networkstatus_consensus_reasonably_live(consensus, now)) {
  1019. log_info(LD_GUARD, "Not expanding the sample guard set; we have "
  1020. "a consensus, but it is far too old.");
  1021. return NULL;
  1022. }
  1023. }
  1024. int n_sampled = smartlist_len(gs->sampled_entry_guards);
  1025. entry_guard_t *added_guard = NULL;
  1026. int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL);
  1027. int n_guards = 0;
  1028. smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards);
  1029. const int max_sample = get_max_sample_size(gs, n_guards);
  1030. const int min_filtered_sample = get_min_filtered_sample_size();
  1031. log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
  1032. "in the sample, and %d eligible guards to extend it with.",
  1033. n_sampled, smartlist_len(eligible_guards));
  1034. while (n_usable_filtered_guards < min_filtered_sample) {
  1035. /* Has our sample grown too large to expand? */
  1036. if (n_sampled >= max_sample) {
  1037. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  1038. "just hit the maximum sample threshold of %d",
  1039. max_sample);
  1040. goto done;
  1041. }
  1042. /* Did we run out of guards? */
  1043. if (smartlist_len(eligible_guards) == 0) {
  1044. /* LCOV_EXCL_START
  1045. As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
  1046. allow all guards to be sampled, this can't be reached.
  1047. */
  1048. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  1049. "just ran out of eligible guards");
  1050. goto done;
  1051. /* LCOV_EXCL_STOP */
  1052. }
  1053. /* Otherwise we can add at least one new guard. */
  1054. added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards);
  1055. if (!added_guard)
  1056. goto done; // LCOV_EXCL_LINE -- only fails on BUG.
  1057. ++n_sampled;
  1058. if (added_guard->is_usable_filtered_guard)
  1059. ++n_usable_filtered_guards;
  1060. }
  1061. done:
  1062. smartlist_free(eligible_guards);
  1063. return added_guard;
  1064. }
  1065. /**
  1066. * Helper: <b>guard</b> has just been removed from the sampled guards:
  1067. * also remove it from primary and confirmed. */
  1068. static void
  1069. remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs,
  1070. entry_guard_t *guard)
  1071. {
  1072. if (guard->is_primary) {
  1073. guard->is_primary = 0;
  1074. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  1075. } else {
  1076. if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
  1077. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  1078. }
  1079. }
  1080. if (guard->confirmed_idx >= 0) {
  1081. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  1082. guard->confirmed_idx = -1;
  1083. guard->confirmed_on_date = 0;
  1084. } else {
  1085. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
  1086. // LCOV_EXCL_START
  1087. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  1088. // LCOV_EXCL_STOP
  1089. }
  1090. }
  1091. }
  1092. /** Return true iff <b>guard</b> is currently "listed" -- that is, it
  1093. * appears in the consensus, or as a configured bridge (as
  1094. * appropriate) */
  1095. MOCK_IMPL(STATIC int,
  1096. entry_guard_is_listed,(guard_selection_t *gs, const entry_guard_t *guard))
  1097. {
  1098. if (gs->type == GS_TYPE_BRIDGE) {
  1099. return NULL != get_bridge_info_for_guard(guard);
  1100. } else {
  1101. const node_t *node = node_get_by_id(guard->identity);
  1102. return node && node_is_possible_guard(node);
  1103. }
  1104. }
  1105. /**
  1106. * Update the status of all sampled guards based on the arrival of a
  1107. * new consensus networkstatus document. This will include marking
  1108. * some guards as listed or unlisted, and removing expired guards. */
  1109. STATIC void
  1110. sampled_guards_update_from_consensus(guard_selection_t *gs)
  1111. {
  1112. tor_assert(gs);
  1113. const int REMOVE_UNLISTED_GUARDS_AFTER =
  1114. (get_remove_unlisted_guards_after_days() * 86400);
  1115. const int unlisted_since_slop = REMOVE_UNLISTED_GUARDS_AFTER / 5;
  1116. // It's important to use only a live consensus here; we don't want to
  1117. // make changes based on anything expired or old.
  1118. if (gs->type != GS_TYPE_BRIDGE) {
  1119. networkstatus_t *ns = networkstatus_get_live_consensus(approx_time());
  1120. if (! ns) {
  1121. log_info(LD_GUARD, "No live consensus; can't update "
  1122. "sampled entry guards.");
  1123. return;
  1124. } else {
  1125. log_info(LD_GUARD, "Updating sampled guard status based on received "
  1126. "consensus.");
  1127. }
  1128. }
  1129. int n_changes = 0;
  1130. /* First: Update listed/unlisted. */
  1131. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1132. /* XXXX #20827 check ed ID too */
  1133. const int is_listed = entry_guard_is_listed(gs, guard);
  1134. if (is_listed && ! guard->currently_listed) {
  1135. ++n_changes;
  1136. guard->currently_listed = 1;
  1137. guard->unlisted_since_date = 0;
  1138. log_info(LD_GUARD, "Sampled guard %s is now listed again.",
  1139. entry_guard_describe(guard));
  1140. } else if (!is_listed && guard->currently_listed) {
  1141. ++n_changes;
  1142. guard->currently_listed = 0;
  1143. guard->unlisted_since_date = randomize_time(approx_time(),
  1144. unlisted_since_slop);
  1145. log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
  1146. entry_guard_describe(guard));
  1147. } else if (is_listed && guard->currently_listed) {
  1148. log_debug(LD_GUARD, "Sampled guard %s is still listed.",
  1149. entry_guard_describe(guard));
  1150. } else {
  1151. tor_assert(! is_listed && ! guard->currently_listed);
  1152. log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
  1153. entry_guard_describe(guard));
  1154. }
  1155. /* Clean up unlisted_since_date, just in case. */
  1156. if (guard->currently_listed && guard->unlisted_since_date) {
  1157. ++n_changes;
  1158. guard->unlisted_since_date = 0;
  1159. log_warn(LD_BUG, "Sampled guard %s was listed, but with "
  1160. "unlisted_since_date set. Fixing.",
  1161. entry_guard_describe(guard));
  1162. } else if (!guard->currently_listed && ! guard->unlisted_since_date) {
  1163. ++n_changes;
  1164. guard->unlisted_since_date = randomize_time(approx_time(),
  1165. unlisted_since_slop);
  1166. log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
  1167. "unlisted_since_date unset. Fixing.",
  1168. entry_guard_describe(guard));
  1169. }
  1170. } SMARTLIST_FOREACH_END(guard);
  1171. const time_t remove_if_unlisted_since =
  1172. approx_time() - REMOVE_UNLISTED_GUARDS_AFTER;
  1173. const time_t maybe_remove_if_sampled_before =
  1174. approx_time() - get_guard_lifetime();
  1175. const time_t remove_if_confirmed_before =
  1176. approx_time() - get_guard_confirmed_min_lifetime();
  1177. /* Then: remove the ones that have been junk for too long */
  1178. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1179. int rmv = 0;
  1180. if (guard->currently_listed == 0 &&
  1181. guard->unlisted_since_date < remove_if_unlisted_since) {
  1182. /*
  1183. "We have a live consensus, and {IS_LISTED} is false, and
  1184. {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}
  1185. days in the past."
  1186. */
  1187. log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
  1188. "for over %d days", entry_guard_describe(guard),
  1189. get_remove_unlisted_guards_after_days());
  1190. rmv = 1;
  1191. } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
  1192. /* We have a live consensus, and {ADDED_ON_DATE} is over
  1193. {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
  1194. "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
  1195. */
  1196. if (guard->confirmed_on_date == 0) {
  1197. rmv = 1;
  1198. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  1199. "over %d days ago, but never confirmed.",
  1200. entry_guard_describe(guard),
  1201. get_guard_lifetime() / 86400);
  1202. } else if (guard->confirmed_on_date < remove_if_confirmed_before) {
  1203. rmv = 1;
  1204. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  1205. "over %d days ago, and confirmed over %d days ago.",
  1206. entry_guard_describe(guard),
  1207. get_guard_lifetime() / 86400,
  1208. get_guard_confirmed_min_lifetime() / 86400);
  1209. }
  1210. }
  1211. if (rmv) {
  1212. ++n_changes;
  1213. SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard);
  1214. remove_guard_from_confirmed_and_primary_lists(gs, guard);
  1215. entry_guard_free(guard);
  1216. }
  1217. } SMARTLIST_FOREACH_END(guard);
  1218. if (n_changes) {
  1219. gs->primary_guards_up_to_date = 0;
  1220. entry_guards_update_filtered_sets(gs);
  1221. /* We don't need to rebuild the confirmed list right here -- we may have
  1222. * removed confirmed guards above, but we can't have added any new
  1223. * confirmed guards.
  1224. */
  1225. entry_guards_changed_for_guard_selection(gs);
  1226. }
  1227. }
  1228. /**
  1229. * Return true iff <b>node</b> is a Tor relay that we are configured to
  1230. * be able to connect to. */
  1231. static int
  1232. node_passes_guard_filter(const or_options_t *options,
  1233. const node_t *node)
  1234. {
  1235. /* NOTE: Make sure that this function stays in sync with
  1236. * options_transition_affects_entry_guards */
  1237. if (routerset_contains_node(options->ExcludeNodes, node))
  1238. return 0;
  1239. if (options->EntryNodes &&
  1240. !routerset_contains_node(options->EntryNodes, node))
  1241. return 0;
  1242. if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
  1243. return 0;
  1244. if (node_is_a_configured_bridge(node))
  1245. return 0;
  1246. return 1;
  1247. }
  1248. /** Helper: Return true iff <b>bridge</b> passes our configuration
  1249. * filter-- if it is a relay that we are configured to be able to
  1250. * connect to. */
  1251. static int
  1252. bridge_passes_guard_filter(const or_options_t *options,
  1253. const bridge_info_t *bridge)
  1254. {
  1255. tor_assert(bridge);
  1256. if (!bridge)
  1257. return 0;
  1258. if (routerset_contains_bridge(options->ExcludeNodes, bridge))
  1259. return 0;
  1260. /* Ignore entrynodes */
  1261. const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
  1262. if (!fascist_firewall_allows_address_addr(&addrport->addr,
  1263. addrport->port,
  1264. FIREWALL_OR_CONNECTION,
  1265. 0, 0))
  1266. return 0;
  1267. return 1;
  1268. }
  1269. /**
  1270. * Return true iff <b>guard</b> is a Tor relay that we are configured to
  1271. * be able to connect to, and we haven't disabled it for omission from
  1272. * the consensus or path bias issues. */
  1273. static int
  1274. entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
  1275. entry_guard_t *guard)
  1276. {
  1277. if (guard->currently_listed == 0)
  1278. return 0;
  1279. if (guard->pb.path_bias_disabled)
  1280. return 0;
  1281. if (gs->type == GS_TYPE_BRIDGE) {
  1282. const bridge_info_t *bridge = get_bridge_info_for_guard(guard);
  1283. if (bridge == NULL)
  1284. return 0;
  1285. return bridge_passes_guard_filter(options, bridge);
  1286. } else {
  1287. const node_t *node = node_get_by_id(guard->identity);
  1288. if (node == NULL) {
  1289. // This can happen when currently_listed is true, and we're not updating
  1290. // it because we don't have a live consensus.
  1291. return 0;
  1292. }
  1293. return node_passes_guard_filter(options, node);
  1294. }
  1295. }
  1296. /**
  1297. * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
  1298. * (If <b>rst</b> is NULL, there are no restrictions.)
  1299. */
  1300. static int
  1301. entry_guard_obeys_restriction(const entry_guard_t *guard,
  1302. const entry_guard_restriction_t *rst)
  1303. {
  1304. tor_assert(guard);
  1305. if (! rst)
  1306. return 1; // No restriction? No problem.
  1307. // Only one kind of restriction exists right now
  1308. return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
  1309. }
  1310. /**
  1311. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  1312. * flags on <b>guard</b>. */
  1313. void
  1314. entry_guard_set_filtered_flags(const or_options_t *options,
  1315. guard_selection_t *gs,
  1316. entry_guard_t *guard)
  1317. {
  1318. unsigned was_filtered = guard->is_filtered_guard;
  1319. guard->is_filtered_guard = 0;
  1320. guard->is_usable_filtered_guard = 0;
  1321. if (entry_guard_passes_filter(options, gs, guard)) {
  1322. guard->is_filtered_guard = 1;
  1323. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1324. guard->is_usable_filtered_guard = 1;
  1325. entry_guard_consider_retry(guard);
  1326. }
  1327. log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
  1328. "reachable_filtered=%d.", entry_guard_describe(guard),
  1329. guard->is_filtered_guard, guard->is_usable_filtered_guard);
  1330. if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
  1331. /* This guard might now be primary or nonprimary. */
  1332. gs->primary_guards_up_to_date = 0;
  1333. }
  1334. }
  1335. /**
  1336. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  1337. * flag on every guard in <b>gs</b>. */
  1338. STATIC void
  1339. entry_guards_update_filtered_sets(guard_selection_t *gs)
  1340. {
  1341. const or_options_t *options = get_options();
  1342. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1343. entry_guard_set_filtered_flags(options, gs, guard);
  1344. } SMARTLIST_FOREACH_END(guard);
  1345. }
  1346. /**
  1347. * Return a random guard from the reachable filtered sample guards
  1348. * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
  1349. * Return NULL if no such guard can be found.
  1350. *
  1351. * Make sure that the sample is big enough, and that all the filter flags
  1352. * are set correctly, before calling this function.
  1353. *
  1354. * If a restriction is provided in <b>rst</b>, do not return any guards that
  1355. * violate it.
  1356. **/
  1357. STATIC entry_guard_t *
  1358. sample_reachable_filtered_entry_guards(guard_selection_t *gs,
  1359. const entry_guard_restriction_t *rst,
  1360. unsigned flags)
  1361. {
  1362. tor_assert(gs);
  1363. entry_guard_t *result = NULL;
  1364. const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
  1365. const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
  1366. const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
  1367. const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
  1368. const unsigned need_descriptor = flags & SAMPLE_EXCLUDE_NO_DESCRIPTOR;
  1369. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1370. entry_guard_consider_retry(guard);
  1371. } SMARTLIST_FOREACH_END(guard);
  1372. const int n_reachable_filtered = num_reachable_filtered_guards(gs, rst);
  1373. log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
  1374. "in the USABLE_FILTERED set.", n_reachable_filtered);
  1375. const int min_filtered_sample = get_min_filtered_sample_size();
  1376. if (n_reachable_filtered < min_filtered_sample) {
  1377. log_info(LD_GUARD, " (That isn't enough. Trying to expand the sample.)");
  1378. entry_guards_expand_sample(gs);
  1379. }
  1380. if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
  1381. entry_guards_update_primary(gs);
  1382. /* Build the set of reachable filtered guards. */
  1383. smartlist_t *reachable_filtered_sample = smartlist_new();
  1384. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1385. entry_guard_consider_retry(guard);// redundant, but cheap.
  1386. if (! entry_guard_obeys_restriction(guard, rst))
  1387. continue;
  1388. if (! guard->is_usable_filtered_guard)
  1389. continue;
  1390. if (exclude_confirmed && guard->confirmed_idx >= 0)
  1391. continue;
  1392. if (exclude_primary && guard->is_primary)
  1393. continue;
  1394. if (exclude_pending && guard->is_pending)
  1395. continue;
  1396. if (need_descriptor && !guard_has_descriptor(guard))
  1397. continue;
  1398. smartlist_add(reachable_filtered_sample, guard);
  1399. } SMARTLIST_FOREACH_END(guard);
  1400. log_info(LD_GUARD, " (After filters [%x], we have %d guards to consider.)",
  1401. flags, smartlist_len(reachable_filtered_sample));
  1402. if (smartlist_len(reachable_filtered_sample)) {
  1403. result = smartlist_choose(reachable_filtered_sample);
  1404. log_info(LD_GUARD, " (Selected %s.)",
  1405. result ? entry_guard_describe(result) : "<null>");
  1406. }
  1407. smartlist_free(reachable_filtered_sample);
  1408. return result;
  1409. }
  1410. /**
  1411. * Helper: compare two entry_guard_t by their confirmed_idx values.
  1412. * Used to sort the confirmed list.
  1413. */
  1414. static int
  1415. compare_guards_by_confirmed_idx(const void **a_, const void **b_)
  1416. {
  1417. const entry_guard_t *a = *a_, *b = *b_;
  1418. if (a->confirmed_idx < b->confirmed_idx)
  1419. return -1;
  1420. else if (a->confirmed_idx > b->confirmed_idx)
  1421. return 1;
  1422. else
  1423. return 0;
  1424. }
  1425. /**
  1426. * Find the confirmed guards from among the sampled guards in <b>gs</b>,
  1427. * and put them in confirmed_entry_guards in the correct
  1428. * order. Recalculate their indices.
  1429. */
  1430. STATIC void
  1431. entry_guards_update_confirmed(guard_selection_t *gs)
  1432. {
  1433. smartlist_clear(gs->confirmed_entry_guards);
  1434. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1435. if (guard->confirmed_idx >= 0)
  1436. smartlist_add(gs->confirmed_entry_guards, guard);
  1437. } SMARTLIST_FOREACH_END(guard);
  1438. smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
  1439. int any_changed = 0;
  1440. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1441. if (guard->confirmed_idx != guard_sl_idx) {
  1442. any_changed = 1;
  1443. guard->confirmed_idx = guard_sl_idx;
  1444. }
  1445. } SMARTLIST_FOREACH_END(guard);
  1446. gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
  1447. if (any_changed) {
  1448. entry_guards_changed_for_guard_selection(gs);
  1449. }
  1450. }
  1451. /**
  1452. * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
  1453. * connected to, and intend to use again.
  1454. */
  1455. STATIC void
  1456. make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
  1457. {
  1458. if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
  1459. return; // LCOV_EXCL_LINE
  1460. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
  1461. return; // LCOV_EXCL_LINE
  1462. const int GUARD_LIFETIME = get_guard_lifetime();
  1463. guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  1464. log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
  1465. entry_guard_describe(guard),
  1466. gs->next_confirmed_idx);
  1467. guard->confirmed_idx = gs->next_confirmed_idx++;
  1468. smartlist_add(gs->confirmed_entry_guards, guard);
  1469. // This confirmed guard might kick something else out of the primary
  1470. // guards.
  1471. gs->primary_guards_up_to_date = 0;
  1472. entry_guards_changed_for_guard_selection(gs);
  1473. }
  1474. /**
  1475. * Recalculate the list of primary guards (the ones we'd prefer to use) from
  1476. * the filtered sample and the confirmed list.
  1477. */
  1478. STATIC void
  1479. entry_guards_update_primary(guard_selection_t *gs)
  1480. {
  1481. tor_assert(gs);
  1482. // prevent recursion. Recursion is potentially very bad here.
  1483. static int running = 0;
  1484. tor_assert(!running);
  1485. running = 1;
  1486. const int N_PRIMARY_GUARDS = get_n_primary_guards();
  1487. smartlist_t *new_primary_guards = smartlist_new();
  1488. smartlist_t *old_primary_guards = smartlist_new();
  1489. smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
  1490. /* Set this flag now, to prevent the calls below from recursing. */
  1491. gs->primary_guards_up_to_date = 1;
  1492. /* First, can we fill it up with confirmed guards? */
  1493. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1494. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  1495. break;
  1496. if (! guard->is_filtered_guard)
  1497. continue;
  1498. guard->is_primary = 1;
  1499. smartlist_add(new_primary_guards, guard);
  1500. } SMARTLIST_FOREACH_END(guard);
  1501. /* Can we keep any older primary guards? First remove all the ones
  1502. * that we already kept. */
  1503. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1504. if (smartlist_contains(new_primary_guards, guard)) {
  1505. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  1506. }
  1507. } SMARTLIST_FOREACH_END(guard);
  1508. /* Now add any that are still good. */
  1509. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1510. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  1511. break;
  1512. if (! guard->is_filtered_guard)
  1513. continue;
  1514. guard->is_primary = 1;
  1515. smartlist_add(new_primary_guards, guard);
  1516. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  1517. } SMARTLIST_FOREACH_END(guard);
  1518. /* Mark the remaining previous primary guards as non-primary */
  1519. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1520. guard->is_primary = 0;
  1521. } SMARTLIST_FOREACH_END(guard);
  1522. /* Finally, fill out the list with sampled guards. */
  1523. while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
  1524. entry_guard_t *guard = sample_reachable_filtered_entry_guards(gs, NULL,
  1525. SAMPLE_EXCLUDE_CONFIRMED|
  1526. SAMPLE_EXCLUDE_PRIMARY|
  1527. SAMPLE_NO_UPDATE_PRIMARY);
  1528. if (!guard)
  1529. break;
  1530. guard->is_primary = 1;
  1531. smartlist_add(new_primary_guards, guard);
  1532. }
  1533. #if 1
  1534. /* Debugging. */
  1535. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
  1536. tor_assert_nonfatal(
  1537. bool_eq(guard->is_primary,
  1538. smartlist_contains(new_primary_guards, guard)));
  1539. });
  1540. #endif
  1541. int any_change = 0;
  1542. if (smartlist_len(gs->primary_entry_guards) !=
  1543. smartlist_len(new_primary_guards)) {
  1544. any_change = 1;
  1545. } else {
  1546. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, g) {
  1547. if (g != smartlist_get(new_primary_guards, g_sl_idx)) {
  1548. any_change = 1;
  1549. }
  1550. } SMARTLIST_FOREACH_END(g);
  1551. }
  1552. if (any_change) {
  1553. log_info(LD_GUARD, "Primary entry guards have changed. "
  1554. "New primary guard list is: ");
  1555. int n = smartlist_len(new_primary_guards);
  1556. SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
  1557. log_info(LD_GUARD, " %d/%d: %s%s%s",
  1558. g_sl_idx+1, n, entry_guard_describe(g),
  1559. g->confirmed_idx >= 0 ? " (confirmed)" : "",
  1560. g->is_filtered_guard ? "" : " (excluded by filter)");
  1561. } SMARTLIST_FOREACH_END(g);
  1562. }
  1563. smartlist_free(old_primary_guards);
  1564. smartlist_free(gs->primary_entry_guards);
  1565. gs->primary_entry_guards = new_primary_guards;
  1566. gs->primary_guards_up_to_date = 1;
  1567. running = 0;
  1568. }
  1569. /**
  1570. * Return the number of seconds after the last attempt at which we should
  1571. * retry a guard that has been failing since <b>failing_since</b>.
  1572. */
  1573. static int
  1574. get_retry_schedule(time_t failing_since, time_t now,
  1575. int is_primary)
  1576. {
  1577. const unsigned SIX_HOURS = 6 * 3600;
  1578. const unsigned FOUR_DAYS = 4 * 86400;
  1579. const unsigned SEVEN_DAYS = 7 * 86400;
  1580. time_t tdiff;
  1581. if (now > failing_since) {
  1582. tdiff = now - failing_since;
  1583. } else {
  1584. tdiff = 0;
  1585. }
  1586. const struct {
  1587. time_t maximum; int primary_delay; int nonprimary_delay;
  1588. } delays[] = {
  1589. { SIX_HOURS, 10*60, 1*60*60 },
  1590. { FOUR_DAYS, 90*60, 4*60*60 },
  1591. { SEVEN_DAYS, 4*60*60, 18*60*60 },
  1592. { TIME_MAX, 9*60*60, 36*60*60 }
  1593. };
  1594. unsigned i;
  1595. for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
  1596. if (tdiff <= delays[i].maximum) {
  1597. return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
  1598. }
  1599. }
  1600. /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
  1601. tor_assert_nonfatal_unreached();
  1602. return 36*60*60;
  1603. /* LCOV_EXCL_STOP */
  1604. }
  1605. /**
  1606. * If <b>guard</b> is unreachable, consider whether enough time has passed
  1607. * to consider it maybe-reachable again.
  1608. */
  1609. STATIC void
  1610. entry_guard_consider_retry(entry_guard_t *guard)
  1611. {
  1612. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1613. return; /* No retry needed. */
  1614. const time_t now = approx_time();
  1615. const int delay =
  1616. get_retry_schedule(guard->failing_since, now, guard->is_primary);
  1617. const time_t last_attempt = guard->last_tried_to_connect;
  1618. if (BUG(last_attempt == 0) ||
  1619. now >= last_attempt + delay) {
  1620. /* We should mark this retriable. */
  1621. char tbuf[ISO_TIME_LEN+1];
  1622. format_local_iso_time(tbuf, last_attempt);
  1623. log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
  1624. "haven't tried to use it since %s.",
  1625. guard->is_primary?"primary ":"",
  1626. guard->confirmed_idx>=0?"confirmed ":"",
  1627. entry_guard_describe(guard),
  1628. tbuf);
  1629. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  1630. if (guard->is_filtered_guard)
  1631. guard->is_usable_filtered_guard = 1;
  1632. }
  1633. }
  1634. /** Tell the entry guards subsystem that we have confirmed that as of
  1635. * just now, we're on the internet. */
  1636. void
  1637. entry_guards_note_internet_connectivity(guard_selection_t *gs)
  1638. {
  1639. gs->last_time_on_internet = approx_time();
  1640. }
  1641. /**
  1642. * Get a guard for use with a circuit. Prefer to pick a running primary
  1643. * guard; then a non-pending running filtered confirmed guard; then a
  1644. * non-pending runnable filtered guard. Update the
  1645. * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
  1646. * guard as appropriate. Set <b>state_out</b> to the new guard-state
  1647. * of the circuit.
  1648. */
  1649. STATIC entry_guard_t *
  1650. select_entry_guard_for_circuit(guard_selection_t *gs,
  1651. guard_usage_t usage,
  1652. const entry_guard_restriction_t *rst,
  1653. unsigned *state_out)
  1654. {
  1655. const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
  1656. tor_assert(gs);
  1657. tor_assert(state_out);
  1658. if (!gs->primary_guards_up_to_date)
  1659. entry_guards_update_primary(gs);
  1660. int num_entry_guards = get_n_primary_guards_to_use(usage);
  1661. smartlist_t *usable_primary_guards = smartlist_new();
  1662. /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
  1663. <maybe> or <yes>, return the first such guard." */
  1664. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1665. entry_guard_consider_retry(guard);
  1666. if (! entry_guard_obeys_restriction(guard, rst))
  1667. continue;
  1668. if (guard->is_reachable != GUARD_REACHABLE_NO) {
  1669. if (need_descriptor && !guard_has_descriptor(guard)) {
  1670. continue;
  1671. }
  1672. *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
  1673. guard->last_tried_to_connect = approx_time();
  1674. smartlist_add(usable_primary_guards, guard);
  1675. if (smartlist_len(usable_primary_guards) >= num_entry_guards)
  1676. break;
  1677. }
  1678. } SMARTLIST_FOREACH_END(guard);
  1679. if (smartlist_len(usable_primary_guards)) {
  1680. entry_guard_t *guard = smartlist_choose(usable_primary_guards);
  1681. smartlist_free(usable_primary_guards);
  1682. log_info(LD_GUARD, "Selected primary guard %s for circuit.",
  1683. entry_guard_describe(guard));
  1684. return guard;
  1685. }
  1686. smartlist_free(usable_primary_guards);
  1687. /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
  1688. and {USABLE_FILTERED_GUARDS} is nonempty, return the first
  1689. entry in that intersection that has {is_pending} set to
  1690. false." */
  1691. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1692. if (guard->is_primary)
  1693. continue; /* we already considered this one. */
  1694. if (! entry_guard_obeys_restriction(guard, rst))
  1695. continue;
  1696. entry_guard_consider_retry(guard);
  1697. if (guard->is_usable_filtered_guard && ! guard->is_pending) {
  1698. if (need_descriptor && !guard_has_descriptor(guard))
  1699. continue; /* not a bug */
  1700. guard->is_pending = 1;
  1701. guard->last_tried_to_connect = approx_time();
  1702. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1703. log_info(LD_GUARD, "No primary guards available. Selected confirmed "
  1704. "guard %s for circuit. Will try other guards before using "
  1705. "this circuit.",
  1706. entry_guard_describe(guard));
  1707. return guard;
  1708. }
  1709. } SMARTLIST_FOREACH_END(guard);
  1710. /* "Otherwise, if there is no such entry, select a member at
  1711. random from {USABLE_FILTERED_GUARDS}." */
  1712. {
  1713. entry_guard_t *guard;
  1714. unsigned flags = 0;
  1715. if (need_descriptor)
  1716. flags |= SAMPLE_EXCLUDE_NO_DESCRIPTOR;
  1717. guard = sample_reachable_filtered_entry_guards(gs,
  1718. rst,
  1719. SAMPLE_EXCLUDE_CONFIRMED |
  1720. SAMPLE_EXCLUDE_PRIMARY |
  1721. SAMPLE_EXCLUDE_PENDING |
  1722. flags);
  1723. if (guard == NULL) {
  1724. log_info(LD_GUARD, "Absolutely no sampled guards were available. "
  1725. "Marking all guards for retry and starting from top again.");
  1726. mark_all_guards_maybe_reachable(gs);
  1727. return NULL;
  1728. }
  1729. guard->is_pending = 1;
  1730. guard->last_tried_to_connect = approx_time();
  1731. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1732. log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
  1733. "random guard %s for circuit. Will try other guards before "
  1734. "using this circuit.",
  1735. entry_guard_describe(guard));
  1736. return guard;
  1737. }
  1738. }
  1739. /**
  1740. * Note that we failed to connect to or build circuits through <b>guard</b>.
  1741. * Use with a guard returned by select_entry_guard_for_circuit().
  1742. */
  1743. STATIC void
  1744. entry_guards_note_guard_failure(guard_selection_t *gs,
  1745. entry_guard_t *guard)
  1746. {
  1747. tor_assert(gs);
  1748. guard->is_reachable = GUARD_REACHABLE_NO;
  1749. guard->is_usable_filtered_guard = 0;
  1750. guard->is_pending = 0;
  1751. if (guard->failing_since == 0)
  1752. guard->failing_since = approx_time();
  1753. log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
  1754. guard->is_primary?"primary ":"",
  1755. guard->confirmed_idx>=0?"confirmed ":"",
  1756. entry_guard_describe(guard));
  1757. }
  1758. /**
  1759. * Note that we successfully connected to, and built a circuit through
  1760. * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
  1761. * return the new guard-state of the circuit.
  1762. *
  1763. * Be aware: the circuit is only usable when its guard-state becomes
  1764. * GUARD_CIRC_STATE_COMPLETE.
  1765. **/
  1766. STATIC unsigned
  1767. entry_guards_note_guard_success(guard_selection_t *gs,
  1768. entry_guard_t *guard,
  1769. unsigned old_state)
  1770. {
  1771. tor_assert(gs);
  1772. /* Save this, since we're about to overwrite it. */
  1773. const time_t last_time_on_internet = gs->last_time_on_internet;
  1774. gs->last_time_on_internet = approx_time();
  1775. guard->is_reachable = GUARD_REACHABLE_YES;
  1776. guard->failing_since = 0;
  1777. guard->is_pending = 0;
  1778. if (guard->is_filtered_guard)
  1779. guard->is_usable_filtered_guard = 1;
  1780. if (guard->confirmed_idx < 0) {
  1781. make_guard_confirmed(gs, guard);
  1782. if (!gs->primary_guards_up_to_date)
  1783. entry_guards_update_primary(gs);
  1784. }
  1785. unsigned new_state;
  1786. switch (old_state) {
  1787. case GUARD_CIRC_STATE_COMPLETE:
  1788. case GUARD_CIRC_STATE_USABLE_ON_COMPLETION:
  1789. new_state = GUARD_CIRC_STATE_COMPLETE;
  1790. break;
  1791. default:
  1792. tor_assert_nonfatal_unreached();
  1793. /* Fall through. */
  1794. case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD:
  1795. if (guard->is_primary) {
  1796. /* XXXX #20832 -- I don't actually like this logic. It seems to make
  1797. * us a little more susceptible to evil-ISP attacks. The mitigations
  1798. * I'm thinking of, however, aren't local to this point, so I'll leave
  1799. * it alone. */
  1800. /* This guard may have become primary by virtue of being confirmed.
  1801. * If so, the circuit for it is now complete.
  1802. */
  1803. new_state = GUARD_CIRC_STATE_COMPLETE;
  1804. } else {
  1805. new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
  1806. }
  1807. break;
  1808. }
  1809. if (! guard->is_primary) {
  1810. if (last_time_on_internet + get_internet_likely_down_interval()
  1811. < approx_time()) {
  1812. mark_primary_guards_maybe_reachable(gs);
  1813. }
  1814. }
  1815. log_info(LD_GUARD, "Recorded success for %s%sguard %s",
  1816. guard->is_primary?"primary ":"",
  1817. guard->confirmed_idx>=0?"confirmed ":"",
  1818. entry_guard_describe(guard));
  1819. return new_state;
  1820. }
  1821. /**
  1822. * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
  1823. */
  1824. STATIC int
  1825. entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
  1826. {
  1827. tor_assert(a && b);
  1828. if (a == b)
  1829. return 0;
  1830. /* Confirmed is always better than unconfirmed; lower index better
  1831. than higher */
  1832. if (a->confirmed_idx < 0) {
  1833. if (b->confirmed_idx >= 0)
  1834. return 0;
  1835. } else {
  1836. if (b->confirmed_idx < 0)
  1837. return 1;
  1838. /* Lower confirmed_idx is better than higher. */
  1839. return (a->confirmed_idx < b->confirmed_idx);
  1840. }
  1841. /* If we reach this point, both are unconfirmed. If one is pending, it
  1842. * has higher priority. */
  1843. if (a->is_pending) {
  1844. if (! b->is_pending)
  1845. return 1;
  1846. /* Both are pending: earlier last_tried_connect wins. */
  1847. return a->last_tried_to_connect < b->last_tried_to_connect;
  1848. } else {
  1849. if (b->is_pending)
  1850. return 0;
  1851. /* Neither is pending: priorities are equal. */
  1852. return 0;
  1853. }
  1854. }
  1855. /** Release all storage held in <b>restriction</b> */
  1856. static void
  1857. entry_guard_restriction_free(entry_guard_restriction_t *rst)
  1858. {
  1859. tor_free(rst);
  1860. }
  1861. /**
  1862. * Release all storage held in <b>state</b>.
  1863. */
  1864. void
  1865. circuit_guard_state_free(circuit_guard_state_t *state)
  1866. {
  1867. if (!state)
  1868. return;
  1869. entry_guard_restriction_free(state->restrictions);
  1870. entry_guard_handle_free(state->guard);
  1871. tor_free(state);
  1872. }
  1873. /**
  1874. * Pick a suitable entry guard for a circuit in, and place that guard
  1875. * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
  1876. * state object that will record whether the circuit is ready to be used
  1877. * or not. Return 0 on success; on failure, return -1.
  1878. *
  1879. * If a restriction is provided in <b>rst</b>, do not return any guards that
  1880. * violate it, and remember that restriction in <b>guard_state_out</b> for
  1881. * later use. (Takes ownership of the <b>rst</b> object.)
  1882. */
  1883. int
  1884. entry_guard_pick_for_circuit(guard_selection_t *gs,
  1885. guard_usage_t usage,
  1886. entry_guard_restriction_t *rst,
  1887. const node_t **chosen_node_out,
  1888. circuit_guard_state_t **guard_state_out)
  1889. {
  1890. tor_assert(gs);
  1891. tor_assert(chosen_node_out);
  1892. tor_assert(guard_state_out);
  1893. *chosen_node_out = NULL;
  1894. *guard_state_out = NULL;
  1895. unsigned state = 0;
  1896. entry_guard_t *guard =
  1897. select_entry_guard_for_circuit(gs, usage, rst, &state);
  1898. if (! guard)
  1899. goto fail;
  1900. if (BUG(state == 0))
  1901. goto fail;
  1902. const node_t *node = node_get_by_id(guard->identity);
  1903. // XXXX #20827 check Ed ID.
  1904. if (! node)
  1905. goto fail;
  1906. if (BUG(usage != GUARD_USAGE_DIRGUARD && !node_has_descriptor(node)))
  1907. goto fail;
  1908. *chosen_node_out = node;
  1909. *guard_state_out = tor_malloc_zero(sizeof(circuit_guard_state_t));
  1910. (*guard_state_out)->guard = entry_guard_handle_new(guard);
  1911. (*guard_state_out)->state = state;
  1912. (*guard_state_out)->state_set_at = approx_time();
  1913. (*guard_state_out)->restrictions = rst;
  1914. return 0;
  1915. fail:
  1916. entry_guard_restriction_free(rst);
  1917. return -1;
  1918. }
  1919. /**
  1920. * Called by the circuit building module when a circuit has succeeded: informs
  1921. * the guards code that the guard in *<b>guard_state_p</b> is working, and
  1922. * advances the state of the guard module. On a GUARD_USABLE_NEVER return
  1923. * value, the circuit is broken and should not be used. On a GUARD_USABLE_NOW
  1924. * return value, the circuit is ready to use. On a GUARD_MAYBE_USABLE_LATER
  1925. * return value, the circuit should not be used until we find out whether
  1926. * preferred guards will work for us.
  1927. */
  1928. guard_usable_t
  1929. entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
  1930. {
  1931. if (BUG(*guard_state_p == NULL))
  1932. return GUARD_USABLE_NEVER;
  1933. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1934. if (! guard || BUG(guard->in_selection == NULL))
  1935. return GUARD_USABLE_NEVER;
  1936. unsigned newstate =
  1937. entry_guards_note_guard_success(guard->in_selection, guard,
  1938. (*guard_state_p)->state);
  1939. (*guard_state_p)->state = newstate;
  1940. (*guard_state_p)->state_set_at = approx_time();
  1941. if (newstate == GUARD_CIRC_STATE_COMPLETE) {
  1942. return GUARD_USABLE_NOW;
  1943. } else {
  1944. return GUARD_MAYBE_USABLE_LATER;
  1945. }
  1946. }
  1947. /** Cancel the selection of *<b>guard_state_p</b> without declaring
  1948. * success or failure. It is safe to call this function if success or
  1949. * failure _has_ already been declared. */
  1950. void
  1951. entry_guard_cancel(circuit_guard_state_t **guard_state_p)
  1952. {
  1953. if (BUG(*guard_state_p == NULL))
  1954. return;
  1955. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1956. if (! guard)
  1957. return;
  1958. /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
  1959. * function will only get called in "bug" cases anyway. */
  1960. guard->is_pending = 0;
  1961. circuit_guard_state_free(*guard_state_p);
  1962. *guard_state_p = NULL;
  1963. }
  1964. /**
  1965. * Called by the circuit building module when a circuit has succeeded:
  1966. * informs the guards code that the guard in *<b>guard_state_p</b> is
  1967. * not working, and advances the state of the guard module.
  1968. */
  1969. void
  1970. entry_guard_failed(circuit_guard_state_t **guard_state_p)
  1971. {
  1972. if (BUG(*guard_state_p == NULL))
  1973. return;
  1974. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1975. if (! guard || BUG(guard->in_selection == NULL))
  1976. return;
  1977. entry_guards_note_guard_failure(guard->in_selection, guard);
  1978. (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
  1979. (*guard_state_p)->state_set_at = approx_time();
  1980. }
  1981. /**
  1982. * Run the entry_guard_failed() function on every circuit that is
  1983. * pending on <b>chan</b>.
  1984. */
  1985. void
  1986. entry_guard_chan_failed(channel_t *chan)
  1987. {
  1988. if (!chan)
  1989. return;
  1990. smartlist_t *pending = smartlist_new();
  1991. circuit_get_all_pending_on_channel(pending, chan);
  1992. SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
  1993. if (!CIRCUIT_IS_ORIGIN(circ))
  1994. continue;
  1995. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1996. if (origin_circ->guard_state) {
  1997. /* We might have no guard state if we didn't use a guard on this
  1998. * circuit (eg it's for a fallback directory). */
  1999. entry_guard_failed(&origin_circ->guard_state);
  2000. }
  2001. } SMARTLIST_FOREACH_END(circ);
  2002. smartlist_free(pending);
  2003. }
  2004. /**
  2005. * Return true iff every primary guard in <b>gs</b> is believed to
  2006. * be unreachable.
  2007. */
  2008. STATIC int
  2009. entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
  2010. {
  2011. tor_assert(gs);
  2012. if (!gs->primary_guards_up_to_date)
  2013. entry_guards_update_primary(gs);
  2014. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  2015. entry_guard_consider_retry(guard);
  2016. if (guard->is_reachable != GUARD_REACHABLE_NO)
  2017. return 0;
  2018. } SMARTLIST_FOREACH_END(guard);
  2019. return 1;
  2020. }
  2021. /** Wrapper for entry_guard_has_higher_priority that compares the
  2022. * guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher
  2023. * priority than <b>b</b>.
  2024. *
  2025. * If a restriction is provided in <b>rst</b>, then do not consider
  2026. * <b>a</b> to have higher priority if it violates the restriction.
  2027. */
  2028. static int
  2029. circ_state_has_higher_priority(origin_circuit_t *a,
  2030. const entry_guard_restriction_t *rst,
  2031. origin_circuit_t *b)
  2032. {
  2033. circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
  2034. circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);
  2035. tor_assert(state_a);
  2036. tor_assert(state_b);
  2037. entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
  2038. entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);
  2039. if (! guard_a) {
  2040. /* Unknown guard -- never higher priority. */
  2041. return 0;
  2042. } else if (! guard_b) {
  2043. /* Known guard -- higher priority than any unknown guard. */
  2044. return 1;
  2045. } else if (! entry_guard_obeys_restriction(guard_a, rst)) {
  2046. /* Restriction violated; guard_a cannot have higher priority. */
  2047. return 0;
  2048. } else {
  2049. /* Both known -- compare.*/
  2050. return entry_guard_has_higher_priority(guard_a, guard_b);
  2051. }
  2052. }
  2053. /**
  2054. * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
  2055. * and see if any of them that were previously not ready to use for
  2056. * guard-related reasons are now ready to use. Place those circuits
  2057. * in <b>newly_complete_out</b>, and mark them COMPLETE.
  2058. *
  2059. * Return 1 if we upgraded any circuits, and 0 otherwise.
  2060. */
  2061. int
  2062. entry_guards_upgrade_waiting_circuits(guard_selection_t *gs,
  2063. const smartlist_t *all_circuits_in,
  2064. smartlist_t *newly_complete_out)
  2065. {
  2066. tor_assert(gs);
  2067. tor_assert(all_circuits_in);
  2068. tor_assert(newly_complete_out);
  2069. if (! entry_guards_all_primary_guards_are_down(gs)) {
  2070. /* We only upgrade a waiting circuit if the primary guards are all
  2071. * down. */
  2072. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  2073. "but not all primary guards were definitely down.");
  2074. return 0;
  2075. }
  2076. int n_waiting = 0;
  2077. int n_complete = 0;
  2078. int n_complete_blocking = 0;
  2079. origin_circuit_t *best_waiting_circuit = NULL;
  2080. smartlist_t *all_circuits = smartlist_new();
  2081. SMARTLIST_FOREACH_BEGIN(all_circuits_in, origin_circuit_t *, circ) {
  2082. // We filter out circuits that aren't ours, or which we can't
  2083. // reason about.
  2084. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2085. if (state == NULL)
  2086. continue;
  2087. entry_guard_t *guard = entry_guard_handle_get(state->guard);
  2088. if (!guard || guard->in_selection != gs)
  2089. continue;
  2090. smartlist_add(all_circuits, circ);
  2091. } SMARTLIST_FOREACH_END(circ);
  2092. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2093. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2094. if BUG((state == NULL))
  2095. continue;
  2096. if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
  2097. ++n_waiting;
  2098. if (! best_waiting_circuit ||
  2099. circ_state_has_higher_priority(circ, NULL, best_waiting_circuit)) {
  2100. best_waiting_circuit = circ;
  2101. }
  2102. }
  2103. } SMARTLIST_FOREACH_END(circ);
  2104. if (! best_waiting_circuit) {
  2105. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  2106. "but didn't find any.");
  2107. goto no_change;
  2108. }
  2109. /* We'll need to keep track of what restrictions were used when picking this
  2110. * circuit, so that we don't allow any circuit without those restrictions to
  2111. * block it. */
  2112. const entry_guard_restriction_t *rst_on_best_waiting =
  2113. origin_circuit_get_guard_state(best_waiting_circuit)->restrictions;
  2114. /* First look at the complete circuits: Do any block this circuit? */
  2115. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2116. /* "C2 "blocks" C1 if:
  2117. * C2 obeys all the restrictions that C1 had to obey, AND
  2118. * C2 has higher priority than C1, AND
  2119. * Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
  2120. or C2 has been <usable_if_no_better_guard> for no more than
  2121. {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
  2122. */
  2123. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2124. if BUG((state == NULL))
  2125. continue;
  2126. if (state->state != GUARD_CIRC_STATE_COMPLETE)
  2127. continue;
  2128. ++n_complete;
  2129. if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
  2130. best_waiting_circuit))
  2131. ++n_complete_blocking;
  2132. } SMARTLIST_FOREACH_END(circ);
  2133. if (n_complete_blocking) {
  2134. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  2135. "%d complete and %d guard-stalled. At least one complete "
  2136. "circuit had higher priority, so not upgrading.",
  2137. n_complete, n_waiting);
  2138. goto no_change;
  2139. }
  2140. /* " * If any circuit C1 is <waiting_for_better_guard>, AND:
  2141. * All primary guards have reachable status of <no>.
  2142. * There is no circuit C2 that "blocks" C1.
  2143. Then, upgrade C1 to <complete>.""
  2144. */
  2145. int n_blockers_found = 0;
  2146. const time_t state_set_at_cutoff =
  2147. approx_time() - get_nonprimary_guard_connect_timeout();
  2148. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2149. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2150. if (BUG(state == NULL))
  2151. continue;
  2152. if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
  2153. continue;
  2154. if (state->state_set_at <= state_set_at_cutoff)
  2155. continue;
  2156. if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
  2157. best_waiting_circuit))
  2158. ++n_blockers_found;
  2159. } SMARTLIST_FOREACH_END(circ);
  2160. if (n_blockers_found) {
  2161. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  2162. "%d guard-stalled, but %d pending circuit(s) had higher "
  2163. "guard priority, so not upgrading.",
  2164. n_waiting, n_blockers_found);
  2165. goto no_change;
  2166. }
  2167. /* Okay. We have a best waiting circuit, and we aren't waiting for
  2168. anything better. Add all circuits with that priority to the
  2169. list, and call them COMPLETE. */
  2170. int n_succeeded = 0;
  2171. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2172. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2173. if (BUG(state == NULL))
  2174. continue;
  2175. if (circ != best_waiting_circuit && rst_on_best_waiting) {
  2176. /* Can't upgrade other circ with same priority as best; might
  2177. be blocked. */
  2178. continue;
  2179. }
  2180. if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
  2181. continue;
  2182. if (circ_state_has_higher_priority(best_waiting_circuit, NULL, circ))
  2183. continue;
  2184. state->state = GUARD_CIRC_STATE_COMPLETE;
  2185. state->state_set_at = approx_time();
  2186. smartlist_add(newly_complete_out, circ);
  2187. ++n_succeeded;
  2188. } SMARTLIST_FOREACH_END(circ);
  2189. log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  2190. "%d guard-stalled, %d complete. %d of the guard-stalled "
  2191. "circuit(s) had high enough priority to upgrade.",
  2192. n_waiting, n_complete, n_succeeded);
  2193. tor_assert_nonfatal(n_succeeded >= 1);
  2194. smartlist_free(all_circuits);
  2195. return 1;
  2196. no_change:
  2197. smartlist_free(all_circuits);
  2198. return 0;
  2199. }
  2200. /**
  2201. * Return true iff the circuit whose state is <b>guard_state</b> should
  2202. * expire.
  2203. */
  2204. int
  2205. entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
  2206. {
  2207. if (guard_state == NULL)
  2208. return 0;
  2209. const time_t expire_if_waiting_since =
  2210. approx_time() - get_nonprimary_guard_idle_timeout();
  2211. return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
  2212. && guard_state->state_set_at < expire_if_waiting_since);
  2213. }
  2214. /**
  2215. * Update all derived pieces of the guard selection state in <b>gs</b>.
  2216. * Return true iff we should stop using all previously generated circuits.
  2217. */
  2218. int
  2219. entry_guards_update_all(guard_selection_t *gs)
  2220. {
  2221. sampled_guards_update_from_consensus(gs);
  2222. entry_guards_update_filtered_sets(gs);
  2223. entry_guards_update_confirmed(gs);
  2224. entry_guards_update_primary(gs);
  2225. return 0;
  2226. }
  2227. /**
  2228. * Return a newly allocated string for encoding the persistent parts of
  2229. * <b>guard</b> to the state file.
  2230. */
  2231. STATIC char *
  2232. entry_guard_encode_for_state(entry_guard_t *guard)
  2233. {
  2234. /*
  2235. * The meta-format we use is K=V K=V K=V... where K can be any
  2236. * characters excepts space and =, and V can be any characters except
  2237. * space. The order of entries is not allowed to matter.
  2238. * Unrecognized K=V entries are persisted; recognized but erroneous
  2239. * entries are corrected.
  2240. */
  2241. smartlist_t *result = smartlist_new();
  2242. char tbuf[ISO_TIME_LEN+1];
  2243. tor_assert(guard);
  2244. smartlist_add_asprintf(result, "in=%s", guard->selection_name);
  2245. smartlist_add_asprintf(result, "rsa_id=%s",
  2246. hex_str(guard->identity, DIGEST_LEN));
  2247. if (guard->bridge_addr) {
  2248. smartlist_add_asprintf(result, "bridge_addr=%s:%d",
  2249. fmt_and_decorate_addr(&guard->bridge_addr->addr),
  2250. guard->bridge_addr->port);
  2251. }
  2252. if (strlen(guard->nickname) && is_legal_nickname(guard->nickname)) {
  2253. smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
  2254. }
  2255. format_iso_time_nospace(tbuf, guard->sampled_on_date);
  2256. smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
  2257. if (guard->sampled_by_version) {
  2258. smartlist_add_asprintf(result, "sampled_by=%s",
  2259. guard->sampled_by_version);
  2260. }
  2261. if (guard->unlisted_since_date > 0) {
  2262. format_iso_time_nospace(tbuf, guard->unlisted_since_date);
  2263. smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
  2264. }
  2265. smartlist_add_asprintf(result, "listed=%d",
  2266. (int)guard->currently_listed);
  2267. if (guard->confirmed_idx >= 0) {
  2268. format_iso_time_nospace(tbuf, guard->confirmed_on_date);
  2269. smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
  2270. smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
  2271. }
  2272. const double EPSILON = 1.0e-6;
  2273. /* Make a copy of the pathbias object, since we will want to update
  2274. some of them */
  2275. guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
  2276. pb->use_successes = pathbias_get_use_success_count(guard);
  2277. pb->successful_circuits_closed = pathbias_get_close_success_count(guard);
  2278. #define PB_FIELD(field) do { \
  2279. if (pb->field >= EPSILON) { \
  2280. smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
  2281. } \
  2282. } while (0)
  2283. PB_FIELD(use_attempts);
  2284. PB_FIELD(use_successes);
  2285. PB_FIELD(circ_attempts);
  2286. PB_FIELD(circ_successes);
  2287. PB_FIELD(successful_circuits_closed);
  2288. PB_FIELD(collapsed_circuits);
  2289. PB_FIELD(unusable_circuits);
  2290. PB_FIELD(timeouts);
  2291. tor_free(pb);
  2292. #undef PB_FIELD
  2293. if (guard->extra_state_fields)
  2294. smartlist_add_strdup(result, guard->extra_state_fields);
  2295. char *joined = smartlist_join_strings(result, " ", 0, NULL);
  2296. SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
  2297. smartlist_free(result);
  2298. return joined;
  2299. }
  2300. /**
  2301. * Given a string generated by entry_guard_encode_for_state(), parse it
  2302. * (if possible) and return an entry_guard_t object for it. Return NULL
  2303. * on complete failure.
  2304. */
  2305. STATIC entry_guard_t *
  2306. entry_guard_parse_from_state(const char *s)
  2307. {
  2308. /* Unrecognized entries get put in here. */
  2309. smartlist_t *extra = smartlist_new();
  2310. /* These fields get parsed from the string. */
  2311. char *in = NULL;
  2312. char *rsa_id = NULL;
  2313. char *nickname = NULL;
  2314. char *sampled_on = NULL;
  2315. char *sampled_by = NULL;
  2316. char *unlisted_since = NULL;
  2317. char *listed = NULL;
  2318. char *confirmed_on = NULL;
  2319. char *confirmed_idx = NULL;
  2320. char *bridge_addr = NULL;
  2321. // pathbias
  2322. char *pb_use_attempts = NULL;
  2323. char *pb_use_successes = NULL;
  2324. char *pb_circ_attempts = NULL;
  2325. char *pb_circ_successes = NULL;
  2326. char *pb_successful_circuits_closed = NULL;
  2327. char *pb_collapsed_circuits = NULL;
  2328. char *pb_unusable_circuits = NULL;
  2329. char *pb_timeouts = NULL;
  2330. /* Split up the entries. Put the ones we know about in strings and the
  2331. * rest in "extra". */
  2332. {
  2333. smartlist_t *entries = smartlist_new();
  2334. strmap_t *vals = strmap_new(); // Maps keyword to location
  2335. #define FIELD(f) \
  2336. strmap_set(vals, #f, &f);
  2337. FIELD(in);
  2338. FIELD(rsa_id);
  2339. FIELD(nickname);
  2340. FIELD(sampled_on);
  2341. FIELD(sampled_by);
  2342. FIELD(unlisted_since);
  2343. FIELD(listed);
  2344. FIELD(confirmed_on);
  2345. FIELD(confirmed_idx);
  2346. FIELD(bridge_addr);
  2347. FIELD(pb_use_attempts);
  2348. FIELD(pb_use_successes);
  2349. FIELD(pb_circ_attempts);
  2350. FIELD(pb_circ_successes);
  2351. FIELD(pb_successful_circuits_closed);
  2352. FIELD(pb_collapsed_circuits);
  2353. FIELD(pb_unusable_circuits);
  2354. FIELD(pb_timeouts);
  2355. #undef FIELD
  2356. smartlist_split_string(entries, s, " ",
  2357. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2358. SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
  2359. const char *eq = strchr(entry, '=');
  2360. if (!eq) {
  2361. smartlist_add(extra, entry);
  2362. continue;
  2363. }
  2364. char *key = tor_strndup(entry, eq-entry);
  2365. char **target = strmap_get(vals, key);
  2366. if (target == NULL || *target != NULL) {
  2367. /* unrecognized or already set */
  2368. smartlist_add(extra, entry);
  2369. tor_free(key);
  2370. continue;
  2371. }
  2372. *target = tor_strdup(eq+1);
  2373. tor_free(key);
  2374. tor_free(entry);
  2375. } SMARTLIST_FOREACH_END(entry);
  2376. smartlist_free(entries);
  2377. strmap_free(vals, NULL);
  2378. }
  2379. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  2380. guard->is_persistent = 1;
  2381. if (in == NULL) {
  2382. log_warn(LD_CIRC, "Guard missing 'in' field");
  2383. goto err;
  2384. }
  2385. guard->selection_name = in;
  2386. in = NULL;
  2387. if (rsa_id == NULL) {
  2388. log_warn(LD_CIRC, "Guard missing RSA ID field");
  2389. goto err;
  2390. }
  2391. /* Process the identity and nickname. */
  2392. if (base16_decode(guard->identity, sizeof(guard->identity),
  2393. rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
  2394. log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
  2395. goto err;
  2396. }
  2397. if (nickname) {
  2398. strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  2399. } else {
  2400. guard->nickname[0]='$';
  2401. base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
  2402. guard->identity, DIGEST_LEN);
  2403. }
  2404. if (bridge_addr) {
  2405. tor_addr_port_t res;
  2406. memset(&res, 0, sizeof(res));
  2407. int r = tor_addr_port_parse(LOG_WARN, bridge_addr,
  2408. &res.addr, &res.port, -1);
  2409. if (r == 0)
  2410. guard->bridge_addr = tor_memdup(&res, sizeof(res));
  2411. /* On error, we already warned. */
  2412. }
  2413. /* Process the various time fields. */
  2414. #define HANDLE_TIME(field) do { \
  2415. if (field) { \
  2416. int r = parse_iso_time_nospace(field, &field ## _time); \
  2417. if (r < 0) { \
  2418. log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
  2419. #field, escaped(field)); \
  2420. field##_time = -1; \
  2421. } \
  2422. } \
  2423. } while (0)
  2424. time_t sampled_on_time = 0;
  2425. time_t unlisted_since_time = 0;
  2426. time_t confirmed_on_time = 0;
  2427. HANDLE_TIME(sampled_on);
  2428. HANDLE_TIME(unlisted_since);
  2429. HANDLE_TIME(confirmed_on);
  2430. if (sampled_on_time <= 0)
  2431. sampled_on_time = approx_time();
  2432. if (unlisted_since_time < 0)
  2433. unlisted_since_time = 0;
  2434. if (confirmed_on_time < 0)
  2435. confirmed_on_time = 0;
  2436. #undef HANDLE_TIME
  2437. guard->sampled_on_date = sampled_on_time;
  2438. guard->unlisted_since_date = unlisted_since_time;
  2439. guard->confirmed_on_date = confirmed_on_time;
  2440. /* Take sampled_by_version verbatim. */
  2441. guard->sampled_by_version = sampled_by;
  2442. sampled_by = NULL; /* prevent free */
  2443. /* Listed is a boolean */
  2444. if (listed && strcmp(listed, "0"))
  2445. guard->currently_listed = 1;
  2446. /* The index is a nonnegative integer. */
  2447. guard->confirmed_idx = -1;
  2448. if (confirmed_idx) {
  2449. int ok=1;
  2450. long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
  2451. if (! ok) {
  2452. log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
  2453. escaped(confirmed_idx));
  2454. } else {
  2455. guard->confirmed_idx = (int)idx;
  2456. }
  2457. }
  2458. /* Anything we didn't recognize gets crammed together */
  2459. if (smartlist_len(extra) > 0) {
  2460. guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
  2461. }
  2462. /* initialize non-persistent fields */
  2463. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  2464. #define PB_FIELD(field) \
  2465. do { \
  2466. if (pb_ ## field) { \
  2467. int ok = 1; \
  2468. double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
  2469. if (! ok) { \
  2470. log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
  2471. #field, pb_ ## field); \
  2472. } else { \
  2473. guard->pb.field = r; \
  2474. } \
  2475. } \
  2476. } while (0)
  2477. PB_FIELD(use_attempts);
  2478. PB_FIELD(use_successes);
  2479. PB_FIELD(circ_attempts);
  2480. PB_FIELD(circ_successes);
  2481. PB_FIELD(successful_circuits_closed);
  2482. PB_FIELD(collapsed_circuits);
  2483. PB_FIELD(unusable_circuits);
  2484. PB_FIELD(timeouts);
  2485. #undef PB_FIELD
  2486. pathbias_check_use_success_count(guard);
  2487. pathbias_check_close_success_count(guard);
  2488. /* We update everything on this guard later, after we've parsed
  2489. * everything. */
  2490. goto done;
  2491. err:
  2492. // only consider it an error if the guard state was totally unparseable.
  2493. entry_guard_free(guard);
  2494. guard = NULL;
  2495. done:
  2496. tor_free(in);
  2497. tor_free(rsa_id);
  2498. tor_free(nickname);
  2499. tor_free(sampled_on);
  2500. tor_free(sampled_by);
  2501. tor_free(unlisted_since);
  2502. tor_free(listed);
  2503. tor_free(confirmed_on);
  2504. tor_free(confirmed_idx);
  2505. tor_free(bridge_addr);
  2506. tor_free(pb_use_attempts);
  2507. tor_free(pb_use_successes);
  2508. tor_free(pb_circ_attempts);
  2509. tor_free(pb_circ_successes);
  2510. tor_free(pb_successful_circuits_closed);
  2511. tor_free(pb_collapsed_circuits);
  2512. tor_free(pb_unusable_circuits);
  2513. tor_free(pb_timeouts);
  2514. SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
  2515. smartlist_free(extra);
  2516. return guard;
  2517. }
  2518. /**
  2519. * Replace the Guards entries in <b>state</b> with a list of all our sampled
  2520. * guards.
  2521. */
  2522. static void
  2523. entry_guards_update_guards_in_state(or_state_t *state)
  2524. {
  2525. if (!guard_contexts)
  2526. return;
  2527. config_line_t *lines = NULL;
  2528. config_line_t **nextline = &lines;
  2529. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2530. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  2531. if (guard->is_persistent == 0)
  2532. continue;
  2533. *nextline = tor_malloc_zero(sizeof(config_line_t));
  2534. (*nextline)->key = tor_strdup("Guard");
  2535. (*nextline)->value = entry_guard_encode_for_state(guard);
  2536. nextline = &(*nextline)->next;
  2537. } SMARTLIST_FOREACH_END(guard);
  2538. } SMARTLIST_FOREACH_END(gs);
  2539. config_free_lines(state->Guard);
  2540. state->Guard = lines;
  2541. }
  2542. /**
  2543. * Replace our sampled guards from the Guards entries in <b>state</b>. Return 0
  2544. * on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only
  2545. * check whether replacing would work.)
  2546. */
  2547. static int
  2548. entry_guards_load_guards_from_state(or_state_t *state, int set)
  2549. {
  2550. const config_line_t *line = state->Guard;
  2551. int n_errors = 0;
  2552. if (!guard_contexts)
  2553. guard_contexts = smartlist_new();
  2554. /* Wipe all our existing guard info. (we shouldn't have any, but
  2555. * let's be safe.) */
  2556. if (set) {
  2557. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2558. guard_selection_free(gs);
  2559. if (curr_guard_context == gs)
  2560. curr_guard_context = NULL;
  2561. SMARTLIST_DEL_CURRENT(guard_contexts, gs);
  2562. } SMARTLIST_FOREACH_END(gs);
  2563. }
  2564. for ( ; line != NULL; line = line->next) {
  2565. entry_guard_t *guard = entry_guard_parse_from_state(line->value);
  2566. if (guard == NULL) {
  2567. ++n_errors;
  2568. continue;
  2569. }
  2570. tor_assert(guard->selection_name);
  2571. if (!strcmp(guard->selection_name, "legacy")) {
  2572. ++n_errors;
  2573. entry_guard_free(guard);
  2574. continue;
  2575. }
  2576. if (set) {
  2577. guard_selection_t *gs;
  2578. gs = get_guard_selection_by_name(guard->selection_name,
  2579. GS_TYPE_INFER, 1);
  2580. tor_assert(gs);
  2581. smartlist_add(gs->sampled_entry_guards, guard);
  2582. guard->in_selection = gs;
  2583. } else {
  2584. entry_guard_free(guard);
  2585. }
  2586. }
  2587. if (set) {
  2588. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2589. entry_guards_update_all(gs);
  2590. } SMARTLIST_FOREACH_END(gs);
  2591. }
  2592. return n_errors ? -1 : 0;
  2593. }
  2594. /** If <b>digest</b> matches the identity of any node in the
  2595. * entry_guards list for the provided guard selection state,
  2596. return that node. Else return NULL. */
  2597. entry_guard_t *
  2598. entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
  2599. const char *digest)
  2600. {
  2601. return get_sampled_guard_with_id(gs, (const uint8_t*)digest);
  2602. }
  2603. /** Return the node_t associated with a single entry_guard_t. May
  2604. * return NULL if the guard is not currently in the consensus. */
  2605. const node_t *
  2606. entry_guard_find_node(const entry_guard_t *guard)
  2607. {
  2608. tor_assert(guard);
  2609. return node_get_by_id(guard->identity);
  2610. }
  2611. /** If <b>digest</b> matches the identity of any node in the
  2612. * entry_guards list for the default guard selection state,
  2613. return that node. Else return NULL. */
  2614. entry_guard_t *
  2615. entry_guard_get_by_id_digest(const char *digest)
  2616. {
  2617. return entry_guard_get_by_id_digest_for_guard_selection(
  2618. get_guard_selection_info(), digest);
  2619. }
  2620. /** Release all storage held by <b>e</b>. */
  2621. STATIC void
  2622. entry_guard_free(entry_guard_t *e)
  2623. {
  2624. if (!e)
  2625. return;
  2626. entry_guard_handles_clear(e);
  2627. tor_free(e->sampled_by_version);
  2628. tor_free(e->extra_state_fields);
  2629. tor_free(e->selection_name);
  2630. tor_free(e->bridge_addr);
  2631. tor_free(e);
  2632. }
  2633. /** Return 0 if we're fine adding arbitrary routers out of the
  2634. * directory to our entry guard list, or return 1 if we have a
  2635. * list already and we must stick to it.
  2636. */
  2637. int
  2638. entry_list_is_constrained(const or_options_t *options)
  2639. {
  2640. // XXXX #21425 look at the current selection.
  2641. if (options->EntryNodes)
  2642. return 1;
  2643. if (options->UseBridges)
  2644. return 1;
  2645. return 0;
  2646. }
  2647. /** Return the number of bridges that have descriptors that are marked with
  2648. * purpose 'bridge' and are running.
  2649. */
  2650. int
  2651. num_bridges_usable(void)
  2652. {
  2653. int n_options = 0;
  2654. tor_assert(get_options()->UseBridges);
  2655. guard_selection_t *gs = get_guard_selection_info();
  2656. tor_assert(gs->type == GS_TYPE_BRIDGE);
  2657. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  2658. if (guard->is_reachable == GUARD_REACHABLE_NO)
  2659. continue;
  2660. if (tor_digest_is_zero(guard->identity))
  2661. continue;
  2662. const node_t *node = node_get_by_id(guard->identity);
  2663. if (node && node->ri)
  2664. ++n_options;
  2665. } SMARTLIST_FOREACH_END(guard);
  2666. return n_options;
  2667. }
  2668. /** Check the pathbias use success count of <b>node</b> and disable it if it
  2669. * goes over our thresholds. */
  2670. static void
  2671. pathbias_check_use_success_count(entry_guard_t *node)
  2672. {
  2673. const or_options_t *options = get_options();
  2674. const double EPSILON = 1.0e-9;
  2675. /* Note: We rely on the < comparison here to allow us to set a 0
  2676. * rate and disable the feature entirely. If refactoring, don't
  2677. * change to <= */
  2678. if (node->pb.use_attempts > EPSILON &&
  2679. pathbias_get_use_success_count(node)/node->pb.use_attempts
  2680. < pathbias_get_extreme_use_rate(options) &&
  2681. pathbias_get_dropguards(options)) {
  2682. node->pb.path_bias_disabled = 1;
  2683. log_info(LD_GENERAL,
  2684. "Path use bias is too high (%f/%f); disabling node %s",
  2685. node->pb.circ_successes, node->pb.circ_attempts,
  2686. node->nickname);
  2687. }
  2688. }
  2689. /** Check the pathbias close count of <b>node</b> and disable it if it goes
  2690. * over our thresholds. */
  2691. static void
  2692. pathbias_check_close_success_count(entry_guard_t *node)
  2693. {
  2694. const or_options_t *options = get_options();
  2695. const double EPSILON = 1.0e-9;
  2696. /* Note: We rely on the < comparison here to allow us to set a 0
  2697. * rate and disable the feature entirely. If refactoring, don't
  2698. * change to <= */
  2699. if (node->pb.circ_attempts > EPSILON &&
  2700. pathbias_get_close_success_count(node)/node->pb.circ_attempts
  2701. < pathbias_get_extreme_rate(options) &&
  2702. pathbias_get_dropguards(options)) {
  2703. node->pb.path_bias_disabled = 1;
  2704. log_info(LD_GENERAL,
  2705. "Path bias is too high (%f/%f); disabling node %s",
  2706. node->pb.circ_successes, node->pb.circ_attempts,
  2707. node->nickname);
  2708. }
  2709. }
  2710. /** Parse <b>state</b> and learn about the entry guards it describes.
  2711. * If <b>set</b> is true, and there are no errors, replace the guard
  2712. * list in the default guard selection context with what we find.
  2713. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  2714. * describing the error, and return -1.
  2715. */
  2716. int
  2717. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  2718. {
  2719. entry_guards_dirty = 0;
  2720. int r1 = entry_guards_load_guards_from_state(state, set);
  2721. entry_guards_dirty = 0;
  2722. if (r1 < 0) {
  2723. if (msg && *msg == NULL) {
  2724. *msg = tor_strdup("parsing error");
  2725. }
  2726. return -1;
  2727. }
  2728. return 0;
  2729. }
  2730. /** How long will we let a change in our guard nodes stay un-saved
  2731. * when we are trying to avoid disk writes? */
  2732. #define SLOW_GUARD_STATE_FLUSH_TIME 600
  2733. /** How long will we let a change in our guard nodes stay un-saved
  2734. * when we are not trying to avoid disk writes? */
  2735. #define FAST_GUARD_STATE_FLUSH_TIME 30
  2736. /** Our list of entry guards has changed for a particular guard selection
  2737. * context, or some element of one of our entry guards has changed for one.
  2738. * Write the changes to disk within the next few minutes.
  2739. */
  2740. void
  2741. entry_guards_changed_for_guard_selection(guard_selection_t *gs)
  2742. {
  2743. time_t when;
  2744. tor_assert(gs != NULL);
  2745. entry_guards_dirty = 1;
  2746. if (get_options()->AvoidDiskWrites)
  2747. when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
  2748. else
  2749. when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
  2750. /* or_state_save() will call entry_guards_update_state() and
  2751. entry_guards_update_guards_in_state()
  2752. */
  2753. or_state_mark_dirty(get_or_state(), when);
  2754. }
  2755. /** Our list of entry guards has changed for the default guard selection
  2756. * context, or some element of one of our entry guards has changed. Write
  2757. * the changes to disk within the next few minutes.
  2758. */
  2759. void
  2760. entry_guards_changed(void)
  2761. {
  2762. entry_guards_changed_for_guard_selection(get_guard_selection_info());
  2763. }
  2764. /** If the entry guard info has not changed, do nothing and return.
  2765. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  2766. * a new one out of the global entry_guards list, and then mark
  2767. * <b>state</b> dirty so it will get saved to disk.
  2768. */
  2769. void
  2770. entry_guards_update_state(or_state_t *state)
  2771. {
  2772. entry_guards_dirty = 0;
  2773. // Handles all guard info.
  2774. entry_guards_update_guards_in_state(state);
  2775. entry_guards_dirty = 0;
  2776. if (!get_options()->AvoidDiskWrites)
  2777. or_state_mark_dirty(get_or_state(), 0);
  2778. entry_guards_dirty = 0;
  2779. }
  2780. /**
  2781. * Format a single entry guard in the format expected by the controller.
  2782. * Return a newly allocated string.
  2783. */
  2784. STATIC char *
  2785. getinfo_helper_format_single_entry_guard(const entry_guard_t *e)
  2786. {
  2787. const char *status = NULL;
  2788. time_t when = 0;
  2789. const node_t *node;
  2790. char tbuf[ISO_TIME_LEN+1];
  2791. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  2792. /* This is going to be a bit tricky, since the status
  2793. * codes weren't really intended for prop271 guards.
  2794. *
  2795. * XXXX use a more appropriate format for exporting this information
  2796. */
  2797. if (e->confirmed_idx < 0) {
  2798. status = "never-connected";
  2799. } else if (! e->currently_listed) {
  2800. when = e->unlisted_since_date;
  2801. status = "unusable";
  2802. } else if (! e->is_filtered_guard) {
  2803. status = "unusable";
  2804. } else if (e->is_reachable == GUARD_REACHABLE_NO) {
  2805. when = e->failing_since;
  2806. status = "down";
  2807. } else {
  2808. status = "up";
  2809. }
  2810. node = entry_guard_find_node(e);
  2811. if (node) {
  2812. node_get_verbose_nickname(node, nbuf);
  2813. } else {
  2814. nbuf[0] = '$';
  2815. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  2816. /* e->nickname field is not very reliable if we don't know about
  2817. * this router any longer; don't include it. */
  2818. }
  2819. char *result = NULL;
  2820. if (when) {
  2821. format_iso_time(tbuf, when);
  2822. tor_asprintf(&result, "%s %s %s\n", nbuf, status, tbuf);
  2823. } else {
  2824. tor_asprintf(&result, "%s %s\n", nbuf, status);
  2825. }
  2826. return result;
  2827. }
  2828. /** If <b>question</b> is the string "entry-guards", then dump
  2829. * to *<b>answer</b> a newly allocated string describing all of
  2830. * the nodes in the global entry_guards list. See control-spec.txt
  2831. * for details.
  2832. * For backward compatibility, we also handle the string "helper-nodes".
  2833. *
  2834. * XXX this should be totally redesigned after prop 271 too, and that's
  2835. * going to take some control spec work.
  2836. * */
  2837. int
  2838. getinfo_helper_entry_guards(control_connection_t *conn,
  2839. const char *question, char **answer,
  2840. const char **errmsg)
  2841. {
  2842. guard_selection_t *gs = get_guard_selection_info();
  2843. tor_assert(gs != NULL);
  2844. (void) conn;
  2845. (void) errmsg;
  2846. if (!strcmp(question,"entry-guards") ||
  2847. !strcmp(question,"helper-nodes")) {
  2848. const smartlist_t *guards;
  2849. guards = gs->sampled_entry_guards;
  2850. smartlist_t *sl = smartlist_new();
  2851. SMARTLIST_FOREACH_BEGIN(guards, const entry_guard_t *, e) {
  2852. char *cp = getinfo_helper_format_single_entry_guard(e);
  2853. smartlist_add(sl, cp);
  2854. } SMARTLIST_FOREACH_END(e);
  2855. *answer = smartlist_join_strings(sl, "", 0, NULL);
  2856. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  2857. smartlist_free(sl);
  2858. }
  2859. return 0;
  2860. }
  2861. /* Given the original bandwidth of a guard and its guardfraction,
  2862. * calculate how much bandwidth the guard should have as a guard and
  2863. * as a non-guard.
  2864. *
  2865. * Quoting from proposal236:
  2866. *
  2867. * Let Wpf denote the weight from the 'bandwidth-weights' line a
  2868. * client would apply to N for position p if it had the guard
  2869. * flag, Wpn the weight if it did not have the guard flag, and B the
  2870. * measured bandwidth of N in the consensus. Then instead of choosing
  2871. * N for position p proportionally to Wpf*B or Wpn*B, clients should
  2872. * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
  2873. *
  2874. * This function fills the <b>guardfraction_bw</b> structure. It sets
  2875. * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
  2876. */
  2877. void
  2878. guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
  2879. int orig_bandwidth,
  2880. uint32_t guardfraction_percentage)
  2881. {
  2882. double guardfraction_fraction;
  2883. /* Turn the percentage into a fraction. */
  2884. tor_assert(guardfraction_percentage <= 100);
  2885. guardfraction_fraction = guardfraction_percentage / 100.0;
  2886. long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
  2887. tor_assert(guard_bw <= INT_MAX);
  2888. guardfraction_bw->guard_bw = (int) guard_bw;
  2889. guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
  2890. }
  2891. /** Helper: Update the status of all entry guards, in whatever algorithm
  2892. * is used. Return true if we should stop using all previously generated
  2893. * circuits, by calling circuit_mark_all_unused_circs() and
  2894. * circuit_mark_all_dirty_circs_as_unusable().
  2895. */
  2896. int
  2897. guards_update_all(void)
  2898. {
  2899. int mark_circuits = 0;
  2900. if (update_guard_selection_choice(get_options()))
  2901. mark_circuits = 1;
  2902. tor_assert(curr_guard_context);
  2903. if (entry_guards_update_all(curr_guard_context))
  2904. mark_circuits = 1;
  2905. return mark_circuits;
  2906. }
  2907. /** Helper: pick a guard for a circuit, with whatever algorithm is
  2908. used. */
  2909. const node_t *
  2910. guards_choose_guard(cpath_build_state_t *state,
  2911. circuit_guard_state_t **guard_state_out)
  2912. {
  2913. const node_t *r = NULL;
  2914. const uint8_t *exit_id = NULL;
  2915. entry_guard_restriction_t *rst = NULL;
  2916. if (state && (exit_id = build_state_get_exit_rsa_id(state))) {
  2917. /* We're building to a targeted exit node, so that node can't be
  2918. * chosen as our guard for this circuit. Remember that fact in a
  2919. * restriction. */
  2920. rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
  2921. memcpy(rst->exclude_id, exit_id, DIGEST_LEN);
  2922. }
  2923. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  2924. GUARD_USAGE_TRAFFIC,
  2925. rst,
  2926. &r,
  2927. guard_state_out) < 0) {
  2928. tor_assert(r == NULL);
  2929. }
  2930. return r;
  2931. }
  2932. /** Remove all currently listed entry guards for a given guard selection
  2933. * context. This frees and replaces <b>gs</b>, so don't use <b>gs</b>
  2934. * after calling this function. */
  2935. void
  2936. remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
  2937. {
  2938. // This function shouldn't exist. XXXX
  2939. tor_assert(gs != NULL);
  2940. char *old_name = tor_strdup(gs->name);
  2941. guard_selection_type_t old_type = gs->type;
  2942. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry, {
  2943. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2944. });
  2945. if (gs == curr_guard_context) {
  2946. curr_guard_context = NULL;
  2947. }
  2948. smartlist_remove(guard_contexts, gs);
  2949. guard_selection_free(gs);
  2950. gs = get_guard_selection_by_name(old_name, old_type, 1);
  2951. entry_guards_changed_for_guard_selection(gs);
  2952. tor_free(old_name);
  2953. }
  2954. /** Remove all currently listed entry guards, so new ones will be chosen.
  2955. *
  2956. * XXXX This function shouldn't exist -- it's meant to support the DROPGUARDS
  2957. * command, which is deprecated.
  2958. */
  2959. void
  2960. remove_all_entry_guards(void)
  2961. {
  2962. remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
  2963. }
  2964. /** Helper: pick a directory guard, with whatever algorithm is used. */
  2965. const node_t *
  2966. guards_choose_dirguard(circuit_guard_state_t **guard_state_out)
  2967. {
  2968. const node_t *r = NULL;
  2969. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  2970. GUARD_USAGE_DIRGUARD,
  2971. NULL,
  2972. &r,
  2973. guard_state_out) < 0) {
  2974. tor_assert(r == NULL);
  2975. }
  2976. return r;
  2977. }
  2978. /**
  2979. * If we're running with a constrained guard set, then maybe mark our guards
  2980. * usable. Return 1 if we do; 0 if we don't.
  2981. */
  2982. int
  2983. guards_retry_optimistic(const or_options_t *options)
  2984. {
  2985. if (! entry_list_is_constrained(options))
  2986. return 0;
  2987. mark_primary_guards_maybe_reachable(get_guard_selection_info());
  2988. return 1;
  2989. }
  2990. /**
  2991. * Return true iff we know enough directory information to construct
  2992. * circuits through all of the primary guards we'd currently use.
  2993. */
  2994. int
  2995. guard_selection_have_enough_dir_info_to_build_circuits(guard_selection_t *gs)
  2996. {
  2997. if (!gs->primary_guards_up_to_date)
  2998. entry_guards_update_primary(gs);
  2999. int n_missing_descriptors = 0;
  3000. int n_considered = 0;
  3001. int num_primary_to_check;
  3002. /* We want to check for the descriptor of at least the first two primary
  3003. * guards in our list, since these are the guards that we typically use for
  3004. * circuits. */
  3005. num_primary_to_check = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC);
  3006. num_primary_to_check++;
  3007. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  3008. entry_guard_consider_retry(guard);
  3009. if (guard->is_reachable == GUARD_REACHABLE_NO)
  3010. continue;
  3011. n_considered++;
  3012. if (!guard_has_descriptor(guard))
  3013. n_missing_descriptors++;
  3014. if (n_considered >= num_primary_to_check)
  3015. break;
  3016. } SMARTLIST_FOREACH_END(guard);
  3017. return n_missing_descriptors == 0;
  3018. }
  3019. /** As guard_selection_have_enough_dir_info_to_build_circuits, but uses
  3020. * the default guard selection. */
  3021. int
  3022. entry_guards_have_enough_dir_info_to_build_circuits(void)
  3023. {
  3024. return guard_selection_have_enough_dir_info_to_build_circuits(
  3025. get_guard_selection_info());
  3026. }
  3027. /** Free one guard selection context */
  3028. STATIC void
  3029. guard_selection_free(guard_selection_t *gs)
  3030. {
  3031. if (!gs) return;
  3032. tor_free(gs->name);
  3033. if (gs->sampled_entry_guards) {
  3034. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
  3035. entry_guard_free(e));
  3036. smartlist_free(gs->sampled_entry_guards);
  3037. gs->sampled_entry_guards = NULL;
  3038. }
  3039. smartlist_free(gs->confirmed_entry_guards);
  3040. smartlist_free(gs->primary_entry_guards);
  3041. tor_free(gs);
  3042. }
  3043. /** Release all storage held by the list of entry guards and related
  3044. * memory structs. */
  3045. void
  3046. entry_guards_free_all(void)
  3047. {
  3048. /* Null out the default */
  3049. curr_guard_context = NULL;
  3050. /* Free all the guard contexts */
  3051. if (guard_contexts != NULL) {
  3052. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  3053. guard_selection_free(gs);
  3054. } SMARTLIST_FOREACH_END(gs);
  3055. smartlist_free(guard_contexts);
  3056. guard_contexts = NULL;
  3057. }
  3058. circuit_build_times_free_timeouts(get_circuit_build_times_mutable());
  3059. }