entrynodes.c 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541
  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-2017, 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 it's 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 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. /** Return true iff we need a consensus to maintain our */
  1001. static int
  1002. live_consensus_is_missing(const guard_selection_t *gs)
  1003. {
  1004. tor_assert(gs);
  1005. if (gs->type == GS_TYPE_BRIDGE) {
  1006. /* We don't update bridges from the consensus; they aren't there. */
  1007. return 0;
  1008. }
  1009. return networkstatus_get_live_consensus(approx_time()) == NULL;
  1010. }
  1011. /**
  1012. * Add new guards to the sampled guards in <b>gs</b> until there are
  1013. * enough usable filtered guards, but never grow the sample beyond its
  1014. * maximum size. Return the last guard added, or NULL if none were
  1015. * added.
  1016. */
  1017. STATIC entry_guard_t *
  1018. entry_guards_expand_sample(guard_selection_t *gs)
  1019. {
  1020. tor_assert(gs);
  1021. const or_options_t *options = get_options();
  1022. if (live_consensus_is_missing(gs)) {
  1023. log_info(LD_GUARD, "Not expanding the sample guard set; we have "
  1024. "no live consensus.");
  1025. return NULL;
  1026. }
  1027. int n_sampled = smartlist_len(gs->sampled_entry_guards);
  1028. entry_guard_t *added_guard = NULL;
  1029. int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL);
  1030. int n_guards = 0;
  1031. smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards);
  1032. const int max_sample = get_max_sample_size(gs, n_guards);
  1033. const int min_filtered_sample = get_min_filtered_sample_size();
  1034. log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
  1035. "in the sample, and %d eligible guards to extend it with.",
  1036. n_sampled, smartlist_len(eligible_guards));
  1037. while (n_usable_filtered_guards < min_filtered_sample) {
  1038. /* Has our sample grown too large to expand? */
  1039. if (n_sampled >= max_sample) {
  1040. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  1041. "just hit the maximum sample threshold of %d",
  1042. max_sample);
  1043. goto done;
  1044. }
  1045. /* Did we run out of guards? */
  1046. if (smartlist_len(eligible_guards) == 0) {
  1047. /* LCOV_EXCL_START
  1048. As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
  1049. allow all guards to be sampled, this can't be reached.
  1050. */
  1051. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  1052. "just ran out of eligible guards");
  1053. goto done;
  1054. /* LCOV_EXCL_STOP */
  1055. }
  1056. /* Otherwise we can add at least one new guard. */
  1057. added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards);
  1058. if (!added_guard)
  1059. goto done; // LCOV_EXCL_LINE -- only fails on BUG.
  1060. ++n_sampled;
  1061. if (added_guard->is_usable_filtered_guard)
  1062. ++n_usable_filtered_guards;
  1063. }
  1064. done:
  1065. smartlist_free(eligible_guards);
  1066. return added_guard;
  1067. }
  1068. /**
  1069. * Helper: <b>guard</b> has just been removed from the sampled guards:
  1070. * also remove it from primary and confirmed. */
  1071. static void
  1072. remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs,
  1073. entry_guard_t *guard)
  1074. {
  1075. if (guard->is_primary) {
  1076. guard->is_primary = 0;
  1077. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  1078. } else {
  1079. if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
  1080. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  1081. }
  1082. }
  1083. if (guard->confirmed_idx >= 0) {
  1084. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  1085. guard->confirmed_idx = -1;
  1086. guard->confirmed_on_date = 0;
  1087. } else {
  1088. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
  1089. // LCOV_EXCL_START
  1090. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  1091. // LCOV_EXCL_STOP
  1092. }
  1093. }
  1094. }
  1095. /** Return true iff <b>guard</b> is currently "listed" -- that is, it
  1096. * appears in the consensus, or as a configured bridge (as
  1097. * appropriate) */
  1098. MOCK_IMPL(STATIC int,
  1099. entry_guard_is_listed,(guard_selection_t *gs, const entry_guard_t *guard))
  1100. {
  1101. if (gs->type == GS_TYPE_BRIDGE) {
  1102. return NULL != get_bridge_info_for_guard(guard);
  1103. } else {
  1104. const node_t *node = node_get_by_id(guard->identity);
  1105. return node && node_is_possible_guard(node);
  1106. }
  1107. }
  1108. /**
  1109. * Update the status of all sampled guards based on the arrival of a
  1110. * new consensus networkstatus document. This will include marking
  1111. * some guards as listed or unlisted, and removing expired guards. */
  1112. STATIC void
  1113. sampled_guards_update_from_consensus(guard_selection_t *gs)
  1114. {
  1115. tor_assert(gs);
  1116. const int REMOVE_UNLISTED_GUARDS_AFTER =
  1117. (get_remove_unlisted_guards_after_days() * 86400);
  1118. const int unlisted_since_slop = REMOVE_UNLISTED_GUARDS_AFTER / 5;
  1119. // It's important to use only a live consensus here; we don't want to
  1120. // make changes based on anything expired or old.
  1121. if (live_consensus_is_missing(gs)) {
  1122. log_info(LD_GUARD, "Not updating the sample guard set; we have "
  1123. "no live consensus.");
  1124. return;
  1125. }
  1126. log_info(LD_GUARD, "Updating sampled guard status based on received "
  1127. "consensus.");
  1128. int n_changes = 0;
  1129. /* First: Update listed/unlisted. */
  1130. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1131. /* XXXX #20827 check ed ID too */
  1132. const int is_listed = entry_guard_is_listed(gs, guard);
  1133. if (is_listed && ! guard->currently_listed) {
  1134. ++n_changes;
  1135. guard->currently_listed = 1;
  1136. guard->unlisted_since_date = 0;
  1137. log_info(LD_GUARD, "Sampled guard %s is now listed again.",
  1138. entry_guard_describe(guard));
  1139. } else if (!is_listed && guard->currently_listed) {
  1140. ++n_changes;
  1141. guard->currently_listed = 0;
  1142. guard->unlisted_since_date = randomize_time(approx_time(),
  1143. unlisted_since_slop);
  1144. log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
  1145. entry_guard_describe(guard));
  1146. } else if (is_listed && guard->currently_listed) {
  1147. log_debug(LD_GUARD, "Sampled guard %s is still listed.",
  1148. entry_guard_describe(guard));
  1149. } else {
  1150. tor_assert(! is_listed && ! guard->currently_listed);
  1151. log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
  1152. entry_guard_describe(guard));
  1153. }
  1154. /* Clean up unlisted_since_date, just in case. */
  1155. if (guard->currently_listed && guard->unlisted_since_date) {
  1156. ++n_changes;
  1157. guard->unlisted_since_date = 0;
  1158. log_warn(LD_BUG, "Sampled guard %s was listed, but with "
  1159. "unlisted_since_date set. Fixing.",
  1160. entry_guard_describe(guard));
  1161. } else if (!guard->currently_listed && ! guard->unlisted_since_date) {
  1162. ++n_changes;
  1163. guard->unlisted_since_date = randomize_time(approx_time(),
  1164. unlisted_since_slop);
  1165. log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
  1166. "unlisted_since_date unset. Fixing.",
  1167. entry_guard_describe(guard));
  1168. }
  1169. } SMARTLIST_FOREACH_END(guard);
  1170. const time_t remove_if_unlisted_since =
  1171. approx_time() - REMOVE_UNLISTED_GUARDS_AFTER;
  1172. const time_t maybe_remove_if_sampled_before =
  1173. approx_time() - get_guard_lifetime();
  1174. const time_t remove_if_confirmed_before =
  1175. approx_time() - get_guard_confirmed_min_lifetime();
  1176. /* Then: remove the ones that have been junk for too long */
  1177. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1178. int rmv = 0;
  1179. if (guard->currently_listed == 0 &&
  1180. guard->unlisted_since_date < remove_if_unlisted_since) {
  1181. /*
  1182. "We have a live consensus, and {IS_LISTED} is false, and
  1183. {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}
  1184. days in the past."
  1185. */
  1186. log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
  1187. "for over %d days", entry_guard_describe(guard),
  1188. get_remove_unlisted_guards_after_days());
  1189. rmv = 1;
  1190. } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
  1191. /* We have a live consensus, and {ADDED_ON_DATE} is over
  1192. {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
  1193. "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
  1194. */
  1195. if (guard->confirmed_on_date == 0) {
  1196. rmv = 1;
  1197. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  1198. "over %d days ago, but never confirmed.",
  1199. entry_guard_describe(guard),
  1200. get_guard_lifetime() / 86400);
  1201. } else if (guard->confirmed_on_date < remove_if_confirmed_before) {
  1202. rmv = 1;
  1203. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  1204. "over %d days ago, and confirmed over %d days ago.",
  1205. entry_guard_describe(guard),
  1206. get_guard_lifetime() / 86400,
  1207. get_guard_confirmed_min_lifetime() / 86400);
  1208. }
  1209. }
  1210. if (rmv) {
  1211. ++n_changes;
  1212. SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard);
  1213. remove_guard_from_confirmed_and_primary_lists(gs, guard);
  1214. entry_guard_free(guard);
  1215. }
  1216. } SMARTLIST_FOREACH_END(guard);
  1217. if (n_changes) {
  1218. gs->primary_guards_up_to_date = 0;
  1219. entry_guards_update_filtered_sets(gs);
  1220. /* We don't need to rebuild the confirmed list right here -- we may have
  1221. * removed confirmed guards above, but we can't have added any new
  1222. * confirmed guards.
  1223. */
  1224. entry_guards_changed_for_guard_selection(gs);
  1225. }
  1226. }
  1227. /**
  1228. * Return true iff <b>node</b> is a Tor relay that we are configured to
  1229. * be able to connect to. */
  1230. static int
  1231. node_passes_guard_filter(const or_options_t *options,
  1232. const node_t *node)
  1233. {
  1234. /* NOTE: Make sure that this function stays in sync with
  1235. * options_transition_affects_entry_guards */
  1236. if (routerset_contains_node(options->ExcludeNodes, node))
  1237. return 0;
  1238. if (options->EntryNodes &&
  1239. !routerset_contains_node(options->EntryNodes, node))
  1240. return 0;
  1241. if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
  1242. return 0;
  1243. if (node_is_a_configured_bridge(node))
  1244. return 0;
  1245. return 1;
  1246. }
  1247. /** Helper: Return true iff <b>bridge</b> passes our configuration
  1248. * filter-- if it is a relay that we are configured to be able to
  1249. * connect to. */
  1250. static int
  1251. bridge_passes_guard_filter(const or_options_t *options,
  1252. const bridge_info_t *bridge)
  1253. {
  1254. tor_assert(bridge);
  1255. if (!bridge)
  1256. return 0;
  1257. if (routerset_contains_bridge(options->ExcludeNodes, bridge))
  1258. return 0;
  1259. /* Ignore entrynodes */
  1260. const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
  1261. if (!fascist_firewall_allows_address_addr(&addrport->addr,
  1262. addrport->port,
  1263. FIREWALL_OR_CONNECTION,
  1264. 0, 0))
  1265. return 0;
  1266. return 1;
  1267. }
  1268. /**
  1269. * Return true iff <b>guard</b> is a Tor relay that we are configured to
  1270. * be able to connect to, and we haven't disabled it for omission from
  1271. * the consensus or path bias issues. */
  1272. static int
  1273. entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
  1274. entry_guard_t *guard)
  1275. {
  1276. if (guard->currently_listed == 0)
  1277. return 0;
  1278. if (guard->pb.path_bias_disabled)
  1279. return 0;
  1280. if (gs->type == GS_TYPE_BRIDGE) {
  1281. const bridge_info_t *bridge = get_bridge_info_for_guard(guard);
  1282. if (bridge == NULL)
  1283. return 0;
  1284. return bridge_passes_guard_filter(options, bridge);
  1285. } else {
  1286. const node_t *node = node_get_by_id(guard->identity);
  1287. if (node == NULL) {
  1288. // This can happen when currently_listed is true, and we're not updating
  1289. // it because we don't have a live consensus.
  1290. return 0;
  1291. }
  1292. return node_passes_guard_filter(options, node);
  1293. }
  1294. }
  1295. /** Return true iff <b>guard</b> is in the same family as <b>node</b>.
  1296. */
  1297. static int
  1298. guard_in_node_family(const entry_guard_t *guard, const node_t *node)
  1299. {
  1300. const node_t *guard_node = node_get_by_id(guard->identity);
  1301. if (guard_node) {
  1302. return nodes_in_same_family(guard_node, node);
  1303. } else {
  1304. /* If we don't have a node_t for the guard node, we might have
  1305. * a bridge_info_t for it. So let's check to see whether the bridge
  1306. * address matches has any family issues.
  1307. *
  1308. * (Strictly speaking, I believe this check is unnecessary, since we only
  1309. * use it to avoid the exit's family when building circuits, and we don't
  1310. * build multihop circuits until we have a routerinfo_t for the
  1311. * bridge... at which point, we'll also have a node_t for the
  1312. * bridge. Nonetheless, it seems wise to include it, in case our
  1313. * assumptions change down the road. -nickm.)
  1314. */
  1315. if (get_options()->EnforceDistinctSubnets && guard->bridge_addr) {
  1316. tor_addr_t node_addr;
  1317. node_get_addr(node, &node_addr);
  1318. if (addrs_in_same_network_family(&node_addr,
  1319. &guard->bridge_addr->addr)) {
  1320. return 1;
  1321. }
  1322. }
  1323. return 0;
  1324. }
  1325. }
  1326. /**
  1327. * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
  1328. * (If <b>rst</b> is NULL, there are no restrictions.)
  1329. */
  1330. static int
  1331. entry_guard_obeys_restriction(const entry_guard_t *guard,
  1332. const entry_guard_restriction_t *rst)
  1333. {
  1334. tor_assert(guard);
  1335. if (! rst)
  1336. return 1; // No restriction? No problem.
  1337. // Only one kind of restriction exists right now: excluding an exit
  1338. // ID and all of its family.
  1339. const node_t *node = node_get_by_id((const char*)rst->exclude_id);
  1340. if (node && guard_in_node_family(guard, node))
  1341. return 0;
  1342. return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
  1343. }
  1344. /**
  1345. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  1346. * flags on <b>guard</b>. */
  1347. void
  1348. entry_guard_set_filtered_flags(const or_options_t *options,
  1349. guard_selection_t *gs,
  1350. entry_guard_t *guard)
  1351. {
  1352. unsigned was_filtered = guard->is_filtered_guard;
  1353. guard->is_filtered_guard = 0;
  1354. guard->is_usable_filtered_guard = 0;
  1355. if (entry_guard_passes_filter(options, gs, guard)) {
  1356. guard->is_filtered_guard = 1;
  1357. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1358. guard->is_usable_filtered_guard = 1;
  1359. entry_guard_consider_retry(guard);
  1360. }
  1361. log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
  1362. "reachable_filtered=%d.", entry_guard_describe(guard),
  1363. guard->is_filtered_guard, guard->is_usable_filtered_guard);
  1364. if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
  1365. /* This guard might now be primary or nonprimary. */
  1366. gs->primary_guards_up_to_date = 0;
  1367. }
  1368. }
  1369. /**
  1370. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  1371. * flag on every guard in <b>gs</b>. */
  1372. STATIC void
  1373. entry_guards_update_filtered_sets(guard_selection_t *gs)
  1374. {
  1375. const or_options_t *options = get_options();
  1376. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1377. entry_guard_set_filtered_flags(options, gs, guard);
  1378. } SMARTLIST_FOREACH_END(guard);
  1379. }
  1380. /**
  1381. * Return a random guard from the reachable filtered sample guards
  1382. * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
  1383. * Return NULL if no such guard can be found.
  1384. *
  1385. * Make sure that the sample is big enough, and that all the filter flags
  1386. * are set correctly, before calling this function.
  1387. *
  1388. * If a restriction is provided in <b>rst</b>, do not return any guards that
  1389. * violate it.
  1390. **/
  1391. STATIC entry_guard_t *
  1392. sample_reachable_filtered_entry_guards(guard_selection_t *gs,
  1393. const entry_guard_restriction_t *rst,
  1394. unsigned flags)
  1395. {
  1396. tor_assert(gs);
  1397. entry_guard_t *result = NULL;
  1398. const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
  1399. const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
  1400. const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
  1401. const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
  1402. const unsigned need_descriptor = flags & SAMPLE_EXCLUDE_NO_DESCRIPTOR;
  1403. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1404. entry_guard_consider_retry(guard);
  1405. } SMARTLIST_FOREACH_END(guard);
  1406. const int n_reachable_filtered = num_reachable_filtered_guards(gs, rst);
  1407. log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
  1408. "in the USABLE_FILTERED set.", n_reachable_filtered);
  1409. const int min_filtered_sample = get_min_filtered_sample_size();
  1410. if (n_reachable_filtered < min_filtered_sample) {
  1411. log_info(LD_GUARD, " (That isn't enough. Trying to expand the sample.)");
  1412. entry_guards_expand_sample(gs);
  1413. }
  1414. if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
  1415. entry_guards_update_primary(gs);
  1416. /* Build the set of reachable filtered guards. */
  1417. smartlist_t *reachable_filtered_sample = smartlist_new();
  1418. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1419. entry_guard_consider_retry(guard);// redundant, but cheap.
  1420. if (! entry_guard_obeys_restriction(guard, rst))
  1421. continue;
  1422. if (! guard->is_usable_filtered_guard)
  1423. continue;
  1424. if (exclude_confirmed && guard->confirmed_idx >= 0)
  1425. continue;
  1426. if (exclude_primary && guard->is_primary)
  1427. continue;
  1428. if (exclude_pending && guard->is_pending)
  1429. continue;
  1430. if (need_descriptor && !guard_has_descriptor(guard))
  1431. continue;
  1432. smartlist_add(reachable_filtered_sample, guard);
  1433. } SMARTLIST_FOREACH_END(guard);
  1434. log_info(LD_GUARD, " (After filters [%x], we have %d guards to consider.)",
  1435. flags, smartlist_len(reachable_filtered_sample));
  1436. if (smartlist_len(reachable_filtered_sample)) {
  1437. result = smartlist_choose(reachable_filtered_sample);
  1438. log_info(LD_GUARD, " (Selected %s.)",
  1439. result ? entry_guard_describe(result) : "<null>");
  1440. }
  1441. smartlist_free(reachable_filtered_sample);
  1442. return result;
  1443. }
  1444. /**
  1445. * Helper: compare two entry_guard_t by their confirmed_idx values.
  1446. * Used to sort the confirmed list.
  1447. */
  1448. static int
  1449. compare_guards_by_confirmed_idx(const void **a_, const void **b_)
  1450. {
  1451. const entry_guard_t *a = *a_, *b = *b_;
  1452. if (a->confirmed_idx < b->confirmed_idx)
  1453. return -1;
  1454. else if (a->confirmed_idx > b->confirmed_idx)
  1455. return 1;
  1456. else
  1457. return 0;
  1458. }
  1459. /**
  1460. * Find the confirmed guards from among the sampled guards in <b>gs</b>,
  1461. * and put them in confirmed_entry_guards in the correct
  1462. * order. Recalculate their indices.
  1463. */
  1464. STATIC void
  1465. entry_guards_update_confirmed(guard_selection_t *gs)
  1466. {
  1467. smartlist_clear(gs->confirmed_entry_guards);
  1468. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1469. if (guard->confirmed_idx >= 0)
  1470. smartlist_add(gs->confirmed_entry_guards, guard);
  1471. } SMARTLIST_FOREACH_END(guard);
  1472. smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
  1473. int any_changed = 0;
  1474. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1475. if (guard->confirmed_idx != guard_sl_idx) {
  1476. any_changed = 1;
  1477. guard->confirmed_idx = guard_sl_idx;
  1478. }
  1479. } SMARTLIST_FOREACH_END(guard);
  1480. gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
  1481. if (any_changed) {
  1482. entry_guards_changed_for_guard_selection(gs);
  1483. }
  1484. }
  1485. /**
  1486. * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
  1487. * connected to, and intend to use again.
  1488. */
  1489. STATIC void
  1490. make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
  1491. {
  1492. if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
  1493. return; // LCOV_EXCL_LINE
  1494. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
  1495. return; // LCOV_EXCL_LINE
  1496. const int GUARD_LIFETIME = get_guard_lifetime();
  1497. guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  1498. log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
  1499. entry_guard_describe(guard),
  1500. gs->next_confirmed_idx);
  1501. guard->confirmed_idx = gs->next_confirmed_idx++;
  1502. smartlist_add(gs->confirmed_entry_guards, guard);
  1503. // This confirmed guard might kick something else out of the primary
  1504. // guards.
  1505. gs->primary_guards_up_to_date = 0;
  1506. entry_guards_changed_for_guard_selection(gs);
  1507. }
  1508. /**
  1509. * Recalculate the list of primary guards (the ones we'd prefer to use) from
  1510. * the filtered sample and the confirmed list.
  1511. */
  1512. STATIC void
  1513. entry_guards_update_primary(guard_selection_t *gs)
  1514. {
  1515. tor_assert(gs);
  1516. // prevent recursion. Recursion is potentially very bad here.
  1517. static int running = 0;
  1518. tor_assert(!running);
  1519. running = 1;
  1520. const int N_PRIMARY_GUARDS = get_n_primary_guards();
  1521. smartlist_t *new_primary_guards = smartlist_new();
  1522. smartlist_t *old_primary_guards = smartlist_new();
  1523. smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
  1524. /* Set this flag now, to prevent the calls below from recursing. */
  1525. gs->primary_guards_up_to_date = 1;
  1526. /* First, can we fill it up with confirmed guards? */
  1527. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1528. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  1529. break;
  1530. if (! guard->is_filtered_guard)
  1531. continue;
  1532. guard->is_primary = 1;
  1533. smartlist_add(new_primary_guards, guard);
  1534. } SMARTLIST_FOREACH_END(guard);
  1535. /* Can we keep any older primary guards? First remove all the ones
  1536. * that we already kept. */
  1537. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1538. if (smartlist_contains(new_primary_guards, guard)) {
  1539. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  1540. }
  1541. } SMARTLIST_FOREACH_END(guard);
  1542. /* Now add any that are still good. */
  1543. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1544. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  1545. break;
  1546. if (! guard->is_filtered_guard)
  1547. continue;
  1548. guard->is_primary = 1;
  1549. smartlist_add(new_primary_guards, guard);
  1550. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  1551. } SMARTLIST_FOREACH_END(guard);
  1552. /* Mark the remaining previous primary guards as non-primary */
  1553. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  1554. guard->is_primary = 0;
  1555. } SMARTLIST_FOREACH_END(guard);
  1556. /* Finally, fill out the list with sampled guards. */
  1557. while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
  1558. entry_guard_t *guard = sample_reachable_filtered_entry_guards(gs, NULL,
  1559. SAMPLE_EXCLUDE_CONFIRMED|
  1560. SAMPLE_EXCLUDE_PRIMARY|
  1561. SAMPLE_NO_UPDATE_PRIMARY);
  1562. if (!guard)
  1563. break;
  1564. guard->is_primary = 1;
  1565. smartlist_add(new_primary_guards, guard);
  1566. }
  1567. #if 1
  1568. /* Debugging. */
  1569. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
  1570. tor_assert_nonfatal(
  1571. bool_eq(guard->is_primary,
  1572. smartlist_contains(new_primary_guards, guard)));
  1573. });
  1574. #endif /* 1 */
  1575. int any_change = 0;
  1576. if (smartlist_len(gs->primary_entry_guards) !=
  1577. smartlist_len(new_primary_guards)) {
  1578. any_change = 1;
  1579. } else {
  1580. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, g) {
  1581. if (g != smartlist_get(new_primary_guards, g_sl_idx)) {
  1582. any_change = 1;
  1583. }
  1584. } SMARTLIST_FOREACH_END(g);
  1585. }
  1586. if (any_change) {
  1587. log_info(LD_GUARD, "Primary entry guards have changed. "
  1588. "New primary guard list is: ");
  1589. int n = smartlist_len(new_primary_guards);
  1590. SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
  1591. log_info(LD_GUARD, " %d/%d: %s%s%s",
  1592. g_sl_idx+1, n, entry_guard_describe(g),
  1593. g->confirmed_idx >= 0 ? " (confirmed)" : "",
  1594. g->is_filtered_guard ? "" : " (excluded by filter)");
  1595. } SMARTLIST_FOREACH_END(g);
  1596. }
  1597. smartlist_free(old_primary_guards);
  1598. smartlist_free(gs->primary_entry_guards);
  1599. gs->primary_entry_guards = new_primary_guards;
  1600. gs->primary_guards_up_to_date = 1;
  1601. running = 0;
  1602. }
  1603. /**
  1604. * Return the number of seconds after the last attempt at which we should
  1605. * retry a guard that has been failing since <b>failing_since</b>.
  1606. */
  1607. static int
  1608. get_retry_schedule(time_t failing_since, time_t now,
  1609. int is_primary)
  1610. {
  1611. const unsigned SIX_HOURS = 6 * 3600;
  1612. const unsigned FOUR_DAYS = 4 * 86400;
  1613. const unsigned SEVEN_DAYS = 7 * 86400;
  1614. time_t tdiff;
  1615. if (now > failing_since) {
  1616. tdiff = now - failing_since;
  1617. } else {
  1618. tdiff = 0;
  1619. }
  1620. const struct {
  1621. time_t maximum; int primary_delay; int nonprimary_delay;
  1622. } delays[] = {
  1623. { SIX_HOURS, 10*60, 1*60*60 },
  1624. { FOUR_DAYS, 90*60, 4*60*60 },
  1625. { SEVEN_DAYS, 4*60*60, 18*60*60 },
  1626. { TIME_MAX, 9*60*60, 36*60*60 }
  1627. };
  1628. unsigned i;
  1629. for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
  1630. if (tdiff <= delays[i].maximum) {
  1631. return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
  1632. }
  1633. }
  1634. /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
  1635. tor_assert_nonfatal_unreached();
  1636. return 36*60*60;
  1637. /* LCOV_EXCL_STOP */
  1638. }
  1639. /**
  1640. * If <b>guard</b> is unreachable, consider whether enough time has passed
  1641. * to consider it maybe-reachable again.
  1642. */
  1643. STATIC void
  1644. entry_guard_consider_retry(entry_guard_t *guard)
  1645. {
  1646. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1647. return; /* No retry needed. */
  1648. const time_t now = approx_time();
  1649. const int delay =
  1650. get_retry_schedule(guard->failing_since, now, guard->is_primary);
  1651. const time_t last_attempt = guard->last_tried_to_connect;
  1652. if (BUG(last_attempt == 0) ||
  1653. now >= last_attempt + delay) {
  1654. /* We should mark this retriable. */
  1655. char tbuf[ISO_TIME_LEN+1];
  1656. format_local_iso_time(tbuf, last_attempt);
  1657. log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
  1658. "haven't tried to use it since %s.",
  1659. guard->is_primary?"primary ":"",
  1660. guard->confirmed_idx>=0?"confirmed ":"",
  1661. entry_guard_describe(guard),
  1662. tbuf);
  1663. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  1664. if (guard->is_filtered_guard)
  1665. guard->is_usable_filtered_guard = 1;
  1666. }
  1667. }
  1668. /** Tell the entry guards subsystem that we have confirmed that as of
  1669. * just now, we're on the internet. */
  1670. void
  1671. entry_guards_note_internet_connectivity(guard_selection_t *gs)
  1672. {
  1673. gs->last_time_on_internet = approx_time();
  1674. }
  1675. /**
  1676. * Get a guard for use with a circuit. Prefer to pick a running primary
  1677. * guard; then a non-pending running filtered confirmed guard; then a
  1678. * non-pending runnable filtered guard. Update the
  1679. * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
  1680. * guard as appropriate. Set <b>state_out</b> to the new guard-state
  1681. * of the circuit.
  1682. */
  1683. STATIC entry_guard_t *
  1684. select_entry_guard_for_circuit(guard_selection_t *gs,
  1685. guard_usage_t usage,
  1686. const entry_guard_restriction_t *rst,
  1687. unsigned *state_out)
  1688. {
  1689. const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
  1690. tor_assert(gs);
  1691. tor_assert(state_out);
  1692. if (!gs->primary_guards_up_to_date)
  1693. entry_guards_update_primary(gs);
  1694. int num_entry_guards = get_n_primary_guards_to_use(usage);
  1695. smartlist_t *usable_primary_guards = smartlist_new();
  1696. /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
  1697. <maybe> or <yes>, return the first such guard." */
  1698. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1699. entry_guard_consider_retry(guard);
  1700. if (! entry_guard_obeys_restriction(guard, rst))
  1701. continue;
  1702. if (guard->is_reachable != GUARD_REACHABLE_NO) {
  1703. if (need_descriptor && !guard_has_descriptor(guard)) {
  1704. continue;
  1705. }
  1706. *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
  1707. guard->last_tried_to_connect = approx_time();
  1708. smartlist_add(usable_primary_guards, guard);
  1709. if (smartlist_len(usable_primary_guards) >= num_entry_guards)
  1710. break;
  1711. }
  1712. } SMARTLIST_FOREACH_END(guard);
  1713. if (smartlist_len(usable_primary_guards)) {
  1714. entry_guard_t *guard = smartlist_choose(usable_primary_guards);
  1715. smartlist_free(usable_primary_guards);
  1716. log_info(LD_GUARD, "Selected primary guard %s for circuit.",
  1717. entry_guard_describe(guard));
  1718. return guard;
  1719. }
  1720. smartlist_free(usable_primary_guards);
  1721. /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
  1722. and {USABLE_FILTERED_GUARDS} is nonempty, return the first
  1723. entry in that intersection that has {is_pending} set to
  1724. false." */
  1725. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1726. if (guard->is_primary)
  1727. continue; /* we already considered this one. */
  1728. if (! entry_guard_obeys_restriction(guard, rst))
  1729. continue;
  1730. entry_guard_consider_retry(guard);
  1731. if (guard->is_usable_filtered_guard && ! guard->is_pending) {
  1732. if (need_descriptor && !guard_has_descriptor(guard))
  1733. continue; /* not a bug */
  1734. guard->is_pending = 1;
  1735. guard->last_tried_to_connect = approx_time();
  1736. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1737. log_info(LD_GUARD, "No primary guards available. Selected confirmed "
  1738. "guard %s for circuit. Will try other guards before using "
  1739. "this circuit.",
  1740. entry_guard_describe(guard));
  1741. return guard;
  1742. }
  1743. } SMARTLIST_FOREACH_END(guard);
  1744. /* "Otherwise, if there is no such entry, select a member at
  1745. random from {USABLE_FILTERED_GUARDS}." */
  1746. {
  1747. entry_guard_t *guard;
  1748. unsigned flags = 0;
  1749. if (need_descriptor)
  1750. flags |= SAMPLE_EXCLUDE_NO_DESCRIPTOR;
  1751. guard = sample_reachable_filtered_entry_guards(gs,
  1752. rst,
  1753. SAMPLE_EXCLUDE_CONFIRMED |
  1754. SAMPLE_EXCLUDE_PRIMARY |
  1755. SAMPLE_EXCLUDE_PENDING |
  1756. flags);
  1757. if (guard == NULL) {
  1758. log_info(LD_GUARD, "Absolutely no sampled guards were available. "
  1759. "Marking all guards for retry and starting from top again.");
  1760. mark_all_guards_maybe_reachable(gs);
  1761. return NULL;
  1762. }
  1763. guard->is_pending = 1;
  1764. guard->last_tried_to_connect = approx_time();
  1765. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1766. log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
  1767. "random guard %s for circuit. Will try other guards before "
  1768. "using this circuit.",
  1769. entry_guard_describe(guard));
  1770. return guard;
  1771. }
  1772. }
  1773. /**
  1774. * Note that we failed to connect to or build circuits through <b>guard</b>.
  1775. * Use with a guard returned by select_entry_guard_for_circuit().
  1776. */
  1777. STATIC void
  1778. entry_guards_note_guard_failure(guard_selection_t *gs,
  1779. entry_guard_t *guard)
  1780. {
  1781. tor_assert(gs);
  1782. guard->is_reachable = GUARD_REACHABLE_NO;
  1783. guard->is_usable_filtered_guard = 0;
  1784. guard->is_pending = 0;
  1785. if (guard->failing_since == 0)
  1786. guard->failing_since = approx_time();
  1787. log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
  1788. guard->is_primary?"primary ":"",
  1789. guard->confirmed_idx>=0?"confirmed ":"",
  1790. entry_guard_describe(guard));
  1791. }
  1792. /**
  1793. * Note that we successfully connected to, and built a circuit through
  1794. * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
  1795. * return the new guard-state of the circuit.
  1796. *
  1797. * Be aware: the circuit is only usable when its guard-state becomes
  1798. * GUARD_CIRC_STATE_COMPLETE.
  1799. **/
  1800. STATIC unsigned
  1801. entry_guards_note_guard_success(guard_selection_t *gs,
  1802. entry_guard_t *guard,
  1803. unsigned old_state)
  1804. {
  1805. tor_assert(gs);
  1806. /* Save this, since we're about to overwrite it. */
  1807. const time_t last_time_on_internet = gs->last_time_on_internet;
  1808. gs->last_time_on_internet = approx_time();
  1809. guard->is_reachable = GUARD_REACHABLE_YES;
  1810. guard->failing_since = 0;
  1811. guard->is_pending = 0;
  1812. if (guard->is_filtered_guard)
  1813. guard->is_usable_filtered_guard = 1;
  1814. if (guard->confirmed_idx < 0) {
  1815. make_guard_confirmed(gs, guard);
  1816. if (!gs->primary_guards_up_to_date)
  1817. entry_guards_update_primary(gs);
  1818. }
  1819. unsigned new_state;
  1820. switch (old_state) {
  1821. case GUARD_CIRC_STATE_COMPLETE:
  1822. case GUARD_CIRC_STATE_USABLE_ON_COMPLETION:
  1823. new_state = GUARD_CIRC_STATE_COMPLETE;
  1824. break;
  1825. default:
  1826. tor_assert_nonfatal_unreached();
  1827. /* Fall through. */
  1828. case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD:
  1829. if (guard->is_primary) {
  1830. /* XXXX #20832 -- I don't actually like this logic. It seems to make
  1831. * us a little more susceptible to evil-ISP attacks. The mitigations
  1832. * I'm thinking of, however, aren't local to this point, so I'll leave
  1833. * it alone. */
  1834. /* This guard may have become primary by virtue of being confirmed.
  1835. * If so, the circuit for it is now complete.
  1836. */
  1837. new_state = GUARD_CIRC_STATE_COMPLETE;
  1838. } else {
  1839. new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
  1840. }
  1841. break;
  1842. }
  1843. if (! guard->is_primary) {
  1844. if (last_time_on_internet + get_internet_likely_down_interval()
  1845. < approx_time()) {
  1846. mark_primary_guards_maybe_reachable(gs);
  1847. }
  1848. }
  1849. log_info(LD_GUARD, "Recorded success for %s%sguard %s",
  1850. guard->is_primary?"primary ":"",
  1851. guard->confirmed_idx>=0?"confirmed ":"",
  1852. entry_guard_describe(guard));
  1853. return new_state;
  1854. }
  1855. /**
  1856. * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
  1857. */
  1858. STATIC int
  1859. entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
  1860. {
  1861. tor_assert(a && b);
  1862. if (a == b)
  1863. return 0;
  1864. /* Confirmed is always better than unconfirmed; lower index better
  1865. than higher */
  1866. if (a->confirmed_idx < 0) {
  1867. if (b->confirmed_idx >= 0)
  1868. return 0;
  1869. } else {
  1870. if (b->confirmed_idx < 0)
  1871. return 1;
  1872. /* Lower confirmed_idx is better than higher. */
  1873. return (a->confirmed_idx < b->confirmed_idx);
  1874. }
  1875. /* If we reach this point, both are unconfirmed. If one is pending, it
  1876. * has higher priority. */
  1877. if (a->is_pending) {
  1878. if (! b->is_pending)
  1879. return 1;
  1880. /* Both are pending: earlier last_tried_connect wins. */
  1881. return a->last_tried_to_connect < b->last_tried_to_connect;
  1882. } else {
  1883. if (b->is_pending)
  1884. return 0;
  1885. /* Neither is pending: priorities are equal. */
  1886. return 0;
  1887. }
  1888. }
  1889. /** Release all storage held in <b>restriction</b> */
  1890. static void
  1891. entry_guard_restriction_free(entry_guard_restriction_t *rst)
  1892. {
  1893. tor_free(rst);
  1894. }
  1895. /**
  1896. * Release all storage held in <b>state</b>.
  1897. */
  1898. void
  1899. circuit_guard_state_free(circuit_guard_state_t *state)
  1900. {
  1901. if (!state)
  1902. return;
  1903. entry_guard_restriction_free(state->restrictions);
  1904. entry_guard_handle_free(state->guard);
  1905. tor_free(state);
  1906. }
  1907. /** Allocate and return a new circuit_guard_state_t to track the result
  1908. * of using <b>guard</b> for a given operation. */
  1909. static circuit_guard_state_t *
  1910. circuit_guard_state_new(entry_guard_t *guard, unsigned state,
  1911. entry_guard_restriction_t *rst)
  1912. {
  1913. circuit_guard_state_t *result;
  1914. result = tor_malloc_zero(sizeof(circuit_guard_state_t));
  1915. result->guard = entry_guard_handle_new(guard);
  1916. result->state = state;
  1917. result->state_set_at = approx_time();
  1918. result->restrictions = rst;
  1919. return result;
  1920. }
  1921. /**
  1922. * Pick a suitable entry guard for a circuit in, and place that guard
  1923. * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
  1924. * state object that will record whether the circuit is ready to be used
  1925. * or not. Return 0 on success; on failure, return -1.
  1926. *
  1927. * If a restriction is provided in <b>rst</b>, do not return any guards that
  1928. * violate it, and remember that restriction in <b>guard_state_out</b> for
  1929. * later use. (Takes ownership of the <b>rst</b> object.)
  1930. */
  1931. int
  1932. entry_guard_pick_for_circuit(guard_selection_t *gs,
  1933. guard_usage_t usage,
  1934. entry_guard_restriction_t *rst,
  1935. const node_t **chosen_node_out,
  1936. circuit_guard_state_t **guard_state_out)
  1937. {
  1938. tor_assert(gs);
  1939. tor_assert(chosen_node_out);
  1940. tor_assert(guard_state_out);
  1941. *chosen_node_out = NULL;
  1942. *guard_state_out = NULL;
  1943. unsigned state = 0;
  1944. entry_guard_t *guard =
  1945. select_entry_guard_for_circuit(gs, usage, rst, &state);
  1946. if (! guard)
  1947. goto fail;
  1948. if (BUG(state == 0))
  1949. goto fail;
  1950. const node_t *node = node_get_by_id(guard->identity);
  1951. // XXXX #20827 check Ed ID.
  1952. if (! node)
  1953. goto fail;
  1954. if (BUG(usage != GUARD_USAGE_DIRGUARD && !node_has_descriptor(node)))
  1955. goto fail;
  1956. *chosen_node_out = node;
  1957. *guard_state_out = circuit_guard_state_new(guard, state, rst);
  1958. return 0;
  1959. fail:
  1960. entry_guard_restriction_free(rst);
  1961. return -1;
  1962. }
  1963. /**
  1964. * Called by the circuit building module when a circuit has succeeded: informs
  1965. * the guards code that the guard in *<b>guard_state_p</b> is working, and
  1966. * advances the state of the guard module. On a GUARD_USABLE_NEVER return
  1967. * value, the circuit is broken and should not be used. On a GUARD_USABLE_NOW
  1968. * return value, the circuit is ready to use. On a GUARD_MAYBE_USABLE_LATER
  1969. * return value, the circuit should not be used until we find out whether
  1970. * preferred guards will work for us.
  1971. */
  1972. guard_usable_t
  1973. entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
  1974. {
  1975. if (BUG(*guard_state_p == NULL))
  1976. return GUARD_USABLE_NEVER;
  1977. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1978. if (! guard || BUG(guard->in_selection == NULL))
  1979. return GUARD_USABLE_NEVER;
  1980. unsigned newstate =
  1981. entry_guards_note_guard_success(guard->in_selection, guard,
  1982. (*guard_state_p)->state);
  1983. (*guard_state_p)->state = newstate;
  1984. (*guard_state_p)->state_set_at = approx_time();
  1985. if (newstate == GUARD_CIRC_STATE_COMPLETE) {
  1986. return GUARD_USABLE_NOW;
  1987. } else {
  1988. return GUARD_MAYBE_USABLE_LATER;
  1989. }
  1990. }
  1991. /** Cancel the selection of *<b>guard_state_p</b> without declaring
  1992. * success or failure. It is safe to call this function if success or
  1993. * failure _has_ already been declared. */
  1994. void
  1995. entry_guard_cancel(circuit_guard_state_t **guard_state_p)
  1996. {
  1997. if (BUG(*guard_state_p == NULL))
  1998. return;
  1999. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  2000. if (! guard)
  2001. return;
  2002. /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
  2003. * function will only get called in "bug" cases anyway. */
  2004. guard->is_pending = 0;
  2005. circuit_guard_state_free(*guard_state_p);
  2006. *guard_state_p = NULL;
  2007. }
  2008. /**
  2009. * Called by the circuit building module when a circuit has succeeded:
  2010. * informs the guards code that the guard in *<b>guard_state_p</b> is
  2011. * not working, and advances the state of the guard module.
  2012. */
  2013. void
  2014. entry_guard_failed(circuit_guard_state_t **guard_state_p)
  2015. {
  2016. if (BUG(*guard_state_p == NULL))
  2017. return;
  2018. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  2019. if (! guard || BUG(guard->in_selection == NULL))
  2020. return;
  2021. entry_guards_note_guard_failure(guard->in_selection, guard);
  2022. (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
  2023. (*guard_state_p)->state_set_at = approx_time();
  2024. }
  2025. /**
  2026. * Run the entry_guard_failed() function on every circuit that is
  2027. * pending on <b>chan</b>.
  2028. */
  2029. void
  2030. entry_guard_chan_failed(channel_t *chan)
  2031. {
  2032. if (!chan)
  2033. return;
  2034. smartlist_t *pending = smartlist_new();
  2035. circuit_get_all_pending_on_channel(pending, chan);
  2036. SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
  2037. if (!CIRCUIT_IS_ORIGIN(circ))
  2038. continue;
  2039. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2040. if (origin_circ->guard_state) {
  2041. /* We might have no guard state if we didn't use a guard on this
  2042. * circuit (eg it's for a fallback directory). */
  2043. entry_guard_failed(&origin_circ->guard_state);
  2044. }
  2045. } SMARTLIST_FOREACH_END(circ);
  2046. smartlist_free(pending);
  2047. }
  2048. /**
  2049. * Return true iff every primary guard in <b>gs</b> is believed to
  2050. * be unreachable.
  2051. */
  2052. STATIC int
  2053. entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
  2054. {
  2055. tor_assert(gs);
  2056. if (!gs->primary_guards_up_to_date)
  2057. entry_guards_update_primary(gs);
  2058. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  2059. entry_guard_consider_retry(guard);
  2060. if (guard->is_reachable != GUARD_REACHABLE_NO)
  2061. return 0;
  2062. } SMARTLIST_FOREACH_END(guard);
  2063. return 1;
  2064. }
  2065. /** Wrapper for entry_guard_has_higher_priority that compares the
  2066. * guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher
  2067. * priority than <b>b</b>.
  2068. *
  2069. * If a restriction is provided in <b>rst</b>, then do not consider
  2070. * <b>a</b> to have higher priority if it violates the restriction.
  2071. */
  2072. static int
  2073. circ_state_has_higher_priority(origin_circuit_t *a,
  2074. const entry_guard_restriction_t *rst,
  2075. origin_circuit_t *b)
  2076. {
  2077. circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
  2078. circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);
  2079. tor_assert(state_a);
  2080. tor_assert(state_b);
  2081. entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
  2082. entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);
  2083. if (! guard_a) {
  2084. /* Unknown guard -- never higher priority. */
  2085. return 0;
  2086. } else if (! guard_b) {
  2087. /* Known guard -- higher priority than any unknown guard. */
  2088. return 1;
  2089. } else if (! entry_guard_obeys_restriction(guard_a, rst)) {
  2090. /* Restriction violated; guard_a cannot have higher priority. */
  2091. return 0;
  2092. } else {
  2093. /* Both known -- compare.*/
  2094. return entry_guard_has_higher_priority(guard_a, guard_b);
  2095. }
  2096. }
  2097. /**
  2098. * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
  2099. * and see if any of them that were previously not ready to use for
  2100. * guard-related reasons are now ready to use. Place those circuits
  2101. * in <b>newly_complete_out</b>, and mark them COMPLETE.
  2102. *
  2103. * Return 1 if we upgraded any circuits, and 0 otherwise.
  2104. */
  2105. int
  2106. entry_guards_upgrade_waiting_circuits(guard_selection_t *gs,
  2107. const smartlist_t *all_circuits_in,
  2108. smartlist_t *newly_complete_out)
  2109. {
  2110. tor_assert(gs);
  2111. tor_assert(all_circuits_in);
  2112. tor_assert(newly_complete_out);
  2113. if (! entry_guards_all_primary_guards_are_down(gs)) {
  2114. /* We only upgrade a waiting circuit if the primary guards are all
  2115. * down. */
  2116. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  2117. "but not all primary guards were definitely down.");
  2118. return 0;
  2119. }
  2120. int n_waiting = 0;
  2121. int n_complete = 0;
  2122. int n_complete_blocking = 0;
  2123. origin_circuit_t *best_waiting_circuit = NULL;
  2124. smartlist_t *all_circuits = smartlist_new();
  2125. SMARTLIST_FOREACH_BEGIN(all_circuits_in, origin_circuit_t *, circ) {
  2126. // We filter out circuits that aren't ours, or which we can't
  2127. // reason about.
  2128. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2129. if (state == NULL)
  2130. continue;
  2131. entry_guard_t *guard = entry_guard_handle_get(state->guard);
  2132. if (!guard || guard->in_selection != gs)
  2133. continue;
  2134. smartlist_add(all_circuits, circ);
  2135. } SMARTLIST_FOREACH_END(circ);
  2136. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2137. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2138. if (BUG(state == NULL))
  2139. continue;
  2140. if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
  2141. ++n_waiting;
  2142. if (! best_waiting_circuit ||
  2143. circ_state_has_higher_priority(circ, NULL, best_waiting_circuit)) {
  2144. best_waiting_circuit = circ;
  2145. }
  2146. }
  2147. } SMARTLIST_FOREACH_END(circ);
  2148. if (! best_waiting_circuit) {
  2149. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  2150. "but didn't find any.");
  2151. goto no_change;
  2152. }
  2153. /* We'll need to keep track of what restrictions were used when picking this
  2154. * circuit, so that we don't allow any circuit without those restrictions to
  2155. * block it. */
  2156. const entry_guard_restriction_t *rst_on_best_waiting =
  2157. origin_circuit_get_guard_state(best_waiting_circuit)->restrictions;
  2158. /* First look at the complete circuits: Do any block this circuit? */
  2159. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2160. /* "C2 "blocks" C1 if:
  2161. * C2 obeys all the restrictions that C1 had to obey, AND
  2162. * C2 has higher priority than C1, AND
  2163. * Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
  2164. or C2 has been <usable_if_no_better_guard> for no more than
  2165. {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
  2166. */
  2167. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2168. if BUG((state == NULL))
  2169. continue;
  2170. if (state->state != GUARD_CIRC_STATE_COMPLETE)
  2171. continue;
  2172. ++n_complete;
  2173. if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
  2174. best_waiting_circuit))
  2175. ++n_complete_blocking;
  2176. } SMARTLIST_FOREACH_END(circ);
  2177. if (n_complete_blocking) {
  2178. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  2179. "%d complete and %d guard-stalled. At least one complete "
  2180. "circuit had higher priority, so not upgrading.",
  2181. n_complete, n_waiting);
  2182. goto no_change;
  2183. }
  2184. /* " * If any circuit C1 is <waiting_for_better_guard>, AND:
  2185. * All primary guards have reachable status of <no>.
  2186. * There is no circuit C2 that "blocks" C1.
  2187. Then, upgrade C1 to <complete>.""
  2188. */
  2189. int n_blockers_found = 0;
  2190. const time_t state_set_at_cutoff =
  2191. approx_time() - get_nonprimary_guard_connect_timeout();
  2192. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2193. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2194. if (BUG(state == NULL))
  2195. continue;
  2196. if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
  2197. continue;
  2198. if (state->state_set_at <= state_set_at_cutoff)
  2199. continue;
  2200. if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
  2201. best_waiting_circuit))
  2202. ++n_blockers_found;
  2203. } SMARTLIST_FOREACH_END(circ);
  2204. if (n_blockers_found) {
  2205. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  2206. "%d guard-stalled, but %d pending circuit(s) had higher "
  2207. "guard priority, so not upgrading.",
  2208. n_waiting, n_blockers_found);
  2209. goto no_change;
  2210. }
  2211. /* Okay. We have a best waiting circuit, and we aren't waiting for
  2212. anything better. Add all circuits with that priority to the
  2213. list, and call them COMPLETE. */
  2214. int n_succeeded = 0;
  2215. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  2216. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  2217. if (BUG(state == NULL))
  2218. continue;
  2219. if (circ != best_waiting_circuit && rst_on_best_waiting) {
  2220. /* Can't upgrade other circ with same priority as best; might
  2221. be blocked. */
  2222. continue;
  2223. }
  2224. if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
  2225. continue;
  2226. if (circ_state_has_higher_priority(best_waiting_circuit, NULL, circ))
  2227. continue;
  2228. state->state = GUARD_CIRC_STATE_COMPLETE;
  2229. state->state_set_at = approx_time();
  2230. smartlist_add(newly_complete_out, circ);
  2231. ++n_succeeded;
  2232. } SMARTLIST_FOREACH_END(circ);
  2233. log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  2234. "%d guard-stalled, %d complete. %d of the guard-stalled "
  2235. "circuit(s) had high enough priority to upgrade.",
  2236. n_waiting, n_complete, n_succeeded);
  2237. tor_assert_nonfatal(n_succeeded >= 1);
  2238. smartlist_free(all_circuits);
  2239. return 1;
  2240. no_change:
  2241. smartlist_free(all_circuits);
  2242. return 0;
  2243. }
  2244. /**
  2245. * Return true iff the circuit whose state is <b>guard_state</b> should
  2246. * expire.
  2247. */
  2248. int
  2249. entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
  2250. {
  2251. if (guard_state == NULL)
  2252. return 0;
  2253. const time_t expire_if_waiting_since =
  2254. approx_time() - get_nonprimary_guard_idle_timeout();
  2255. return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
  2256. && guard_state->state_set_at < expire_if_waiting_since);
  2257. }
  2258. /**
  2259. * Update all derived pieces of the guard selection state in <b>gs</b>.
  2260. * Return true iff we should stop using all previously generated circuits.
  2261. */
  2262. int
  2263. entry_guards_update_all(guard_selection_t *gs)
  2264. {
  2265. sampled_guards_update_from_consensus(gs);
  2266. entry_guards_update_filtered_sets(gs);
  2267. entry_guards_update_confirmed(gs);
  2268. entry_guards_update_primary(gs);
  2269. return 0;
  2270. }
  2271. /**
  2272. * Return a newly allocated string for encoding the persistent parts of
  2273. * <b>guard</b> to the state file.
  2274. */
  2275. STATIC char *
  2276. entry_guard_encode_for_state(entry_guard_t *guard)
  2277. {
  2278. /*
  2279. * The meta-format we use is K=V K=V K=V... where K can be any
  2280. * characters excepts space and =, and V can be any characters except
  2281. * space. The order of entries is not allowed to matter.
  2282. * Unrecognized K=V entries are persisted; recognized but erroneous
  2283. * entries are corrected.
  2284. */
  2285. smartlist_t *result = smartlist_new();
  2286. char tbuf[ISO_TIME_LEN+1];
  2287. tor_assert(guard);
  2288. smartlist_add_asprintf(result, "in=%s", guard->selection_name);
  2289. smartlist_add_asprintf(result, "rsa_id=%s",
  2290. hex_str(guard->identity, DIGEST_LEN));
  2291. if (guard->bridge_addr) {
  2292. smartlist_add_asprintf(result, "bridge_addr=%s:%d",
  2293. fmt_and_decorate_addr(&guard->bridge_addr->addr),
  2294. guard->bridge_addr->port);
  2295. }
  2296. if (strlen(guard->nickname) && is_legal_nickname(guard->nickname)) {
  2297. smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
  2298. }
  2299. format_iso_time_nospace(tbuf, guard->sampled_on_date);
  2300. smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
  2301. if (guard->sampled_by_version) {
  2302. smartlist_add_asprintf(result, "sampled_by=%s",
  2303. guard->sampled_by_version);
  2304. }
  2305. if (guard->unlisted_since_date > 0) {
  2306. format_iso_time_nospace(tbuf, guard->unlisted_since_date);
  2307. smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
  2308. }
  2309. smartlist_add_asprintf(result, "listed=%d",
  2310. (int)guard->currently_listed);
  2311. if (guard->confirmed_idx >= 0) {
  2312. format_iso_time_nospace(tbuf, guard->confirmed_on_date);
  2313. smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
  2314. smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
  2315. }
  2316. const double EPSILON = 1.0e-6;
  2317. /* Make a copy of the pathbias object, since we will want to update
  2318. some of them */
  2319. guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
  2320. pb->use_successes = pathbias_get_use_success_count(guard);
  2321. pb->successful_circuits_closed = pathbias_get_close_success_count(guard);
  2322. #define PB_FIELD(field) do { \
  2323. if (pb->field >= EPSILON) { \
  2324. smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
  2325. } \
  2326. } while (0)
  2327. PB_FIELD(use_attempts);
  2328. PB_FIELD(use_successes);
  2329. PB_FIELD(circ_attempts);
  2330. PB_FIELD(circ_successes);
  2331. PB_FIELD(successful_circuits_closed);
  2332. PB_FIELD(collapsed_circuits);
  2333. PB_FIELD(unusable_circuits);
  2334. PB_FIELD(timeouts);
  2335. tor_free(pb);
  2336. #undef PB_FIELD
  2337. if (guard->extra_state_fields)
  2338. smartlist_add_strdup(result, guard->extra_state_fields);
  2339. char *joined = smartlist_join_strings(result, " ", 0, NULL);
  2340. SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
  2341. smartlist_free(result);
  2342. return joined;
  2343. }
  2344. /**
  2345. * Given a string generated by entry_guard_encode_for_state(), parse it
  2346. * (if possible) and return an entry_guard_t object for it. Return NULL
  2347. * on complete failure.
  2348. */
  2349. STATIC entry_guard_t *
  2350. entry_guard_parse_from_state(const char *s)
  2351. {
  2352. /* Unrecognized entries get put in here. */
  2353. smartlist_t *extra = smartlist_new();
  2354. /* These fields get parsed from the string. */
  2355. char *in = NULL;
  2356. char *rsa_id = NULL;
  2357. char *nickname = NULL;
  2358. char *sampled_on = NULL;
  2359. char *sampled_by = NULL;
  2360. char *unlisted_since = NULL;
  2361. char *listed = NULL;
  2362. char *confirmed_on = NULL;
  2363. char *confirmed_idx = NULL;
  2364. char *bridge_addr = NULL;
  2365. // pathbias
  2366. char *pb_use_attempts = NULL;
  2367. char *pb_use_successes = NULL;
  2368. char *pb_circ_attempts = NULL;
  2369. char *pb_circ_successes = NULL;
  2370. char *pb_successful_circuits_closed = NULL;
  2371. char *pb_collapsed_circuits = NULL;
  2372. char *pb_unusable_circuits = NULL;
  2373. char *pb_timeouts = NULL;
  2374. /* Split up the entries. Put the ones we know about in strings and the
  2375. * rest in "extra". */
  2376. {
  2377. smartlist_t *entries = smartlist_new();
  2378. strmap_t *vals = strmap_new(); // Maps keyword to location
  2379. #define FIELD(f) \
  2380. strmap_set(vals, #f, &f);
  2381. FIELD(in);
  2382. FIELD(rsa_id);
  2383. FIELD(nickname);
  2384. FIELD(sampled_on);
  2385. FIELD(sampled_by);
  2386. FIELD(unlisted_since);
  2387. FIELD(listed);
  2388. FIELD(confirmed_on);
  2389. FIELD(confirmed_idx);
  2390. FIELD(bridge_addr);
  2391. FIELD(pb_use_attempts);
  2392. FIELD(pb_use_successes);
  2393. FIELD(pb_circ_attempts);
  2394. FIELD(pb_circ_successes);
  2395. FIELD(pb_successful_circuits_closed);
  2396. FIELD(pb_collapsed_circuits);
  2397. FIELD(pb_unusable_circuits);
  2398. FIELD(pb_timeouts);
  2399. #undef FIELD
  2400. smartlist_split_string(entries, s, " ",
  2401. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2402. SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
  2403. const char *eq = strchr(entry, '=');
  2404. if (!eq) {
  2405. smartlist_add(extra, entry);
  2406. continue;
  2407. }
  2408. char *key = tor_strndup(entry, eq-entry);
  2409. char **target = strmap_get(vals, key);
  2410. if (target == NULL || *target != NULL) {
  2411. /* unrecognized or already set */
  2412. smartlist_add(extra, entry);
  2413. tor_free(key);
  2414. continue;
  2415. }
  2416. *target = tor_strdup(eq+1);
  2417. tor_free(key);
  2418. tor_free(entry);
  2419. } SMARTLIST_FOREACH_END(entry);
  2420. smartlist_free(entries);
  2421. strmap_free(vals, NULL);
  2422. }
  2423. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  2424. guard->is_persistent = 1;
  2425. if (in == NULL) {
  2426. log_warn(LD_CIRC, "Guard missing 'in' field");
  2427. goto err;
  2428. }
  2429. guard->selection_name = in;
  2430. in = NULL;
  2431. if (rsa_id == NULL) {
  2432. log_warn(LD_CIRC, "Guard missing RSA ID field");
  2433. goto err;
  2434. }
  2435. /* Process the identity and nickname. */
  2436. if (base16_decode(guard->identity, sizeof(guard->identity),
  2437. rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
  2438. log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
  2439. goto err;
  2440. }
  2441. if (nickname) {
  2442. strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  2443. } else {
  2444. guard->nickname[0]='$';
  2445. base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
  2446. guard->identity, DIGEST_LEN);
  2447. }
  2448. if (bridge_addr) {
  2449. tor_addr_port_t res;
  2450. memset(&res, 0, sizeof(res));
  2451. int r = tor_addr_port_parse(LOG_WARN, bridge_addr,
  2452. &res.addr, &res.port, -1);
  2453. if (r == 0)
  2454. guard->bridge_addr = tor_memdup(&res, sizeof(res));
  2455. /* On error, we already warned. */
  2456. }
  2457. /* Process the various time fields. */
  2458. #define HANDLE_TIME(field) do { \
  2459. if (field) { \
  2460. int r = parse_iso_time_nospace(field, &field ## _time); \
  2461. if (r < 0) { \
  2462. log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
  2463. #field, escaped(field)); \
  2464. field##_time = -1; \
  2465. } \
  2466. } \
  2467. } while (0)
  2468. time_t sampled_on_time = 0;
  2469. time_t unlisted_since_time = 0;
  2470. time_t confirmed_on_time = 0;
  2471. HANDLE_TIME(sampled_on);
  2472. HANDLE_TIME(unlisted_since);
  2473. HANDLE_TIME(confirmed_on);
  2474. if (sampled_on_time <= 0)
  2475. sampled_on_time = approx_time();
  2476. if (unlisted_since_time < 0)
  2477. unlisted_since_time = 0;
  2478. if (confirmed_on_time < 0)
  2479. confirmed_on_time = 0;
  2480. #undef HANDLE_TIME
  2481. guard->sampled_on_date = sampled_on_time;
  2482. guard->unlisted_since_date = unlisted_since_time;
  2483. guard->confirmed_on_date = confirmed_on_time;
  2484. /* Take sampled_by_version verbatim. */
  2485. guard->sampled_by_version = sampled_by;
  2486. sampled_by = NULL; /* prevent free */
  2487. /* Listed is a boolean */
  2488. if (listed && strcmp(listed, "0"))
  2489. guard->currently_listed = 1;
  2490. /* The index is a nonnegative integer. */
  2491. guard->confirmed_idx = -1;
  2492. if (confirmed_idx) {
  2493. int ok=1;
  2494. long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
  2495. if (! ok) {
  2496. log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
  2497. escaped(confirmed_idx));
  2498. } else {
  2499. guard->confirmed_idx = (int)idx;
  2500. }
  2501. }
  2502. /* Anything we didn't recognize gets crammed together */
  2503. if (smartlist_len(extra) > 0) {
  2504. guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
  2505. }
  2506. /* initialize non-persistent fields */
  2507. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  2508. #define PB_FIELD(field) \
  2509. do { \
  2510. if (pb_ ## field) { \
  2511. int ok = 1; \
  2512. double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
  2513. if (! ok) { \
  2514. log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
  2515. #field, pb_ ## field); \
  2516. } else { \
  2517. guard->pb.field = r; \
  2518. } \
  2519. } \
  2520. } while (0)
  2521. PB_FIELD(use_attempts);
  2522. PB_FIELD(use_successes);
  2523. PB_FIELD(circ_attempts);
  2524. PB_FIELD(circ_successes);
  2525. PB_FIELD(successful_circuits_closed);
  2526. PB_FIELD(collapsed_circuits);
  2527. PB_FIELD(unusable_circuits);
  2528. PB_FIELD(timeouts);
  2529. #undef PB_FIELD
  2530. pathbias_check_use_success_count(guard);
  2531. pathbias_check_close_success_count(guard);
  2532. /* We update everything on this guard later, after we've parsed
  2533. * everything. */
  2534. goto done;
  2535. err:
  2536. // only consider it an error if the guard state was totally unparseable.
  2537. entry_guard_free(guard);
  2538. guard = NULL;
  2539. done:
  2540. tor_free(in);
  2541. tor_free(rsa_id);
  2542. tor_free(nickname);
  2543. tor_free(sampled_on);
  2544. tor_free(sampled_by);
  2545. tor_free(unlisted_since);
  2546. tor_free(listed);
  2547. tor_free(confirmed_on);
  2548. tor_free(confirmed_idx);
  2549. tor_free(bridge_addr);
  2550. tor_free(pb_use_attempts);
  2551. tor_free(pb_use_successes);
  2552. tor_free(pb_circ_attempts);
  2553. tor_free(pb_circ_successes);
  2554. tor_free(pb_successful_circuits_closed);
  2555. tor_free(pb_collapsed_circuits);
  2556. tor_free(pb_unusable_circuits);
  2557. tor_free(pb_timeouts);
  2558. SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
  2559. smartlist_free(extra);
  2560. return guard;
  2561. }
  2562. /**
  2563. * Replace the Guards entries in <b>state</b> with a list of all our sampled
  2564. * guards.
  2565. */
  2566. static void
  2567. entry_guards_update_guards_in_state(or_state_t *state)
  2568. {
  2569. if (!guard_contexts)
  2570. return;
  2571. config_line_t *lines = NULL;
  2572. config_line_t **nextline = &lines;
  2573. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2574. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  2575. if (guard->is_persistent == 0)
  2576. continue;
  2577. *nextline = tor_malloc_zero(sizeof(config_line_t));
  2578. (*nextline)->key = tor_strdup("Guard");
  2579. (*nextline)->value = entry_guard_encode_for_state(guard);
  2580. nextline = &(*nextline)->next;
  2581. } SMARTLIST_FOREACH_END(guard);
  2582. } SMARTLIST_FOREACH_END(gs);
  2583. config_free_lines(state->Guard);
  2584. state->Guard = lines;
  2585. }
  2586. /**
  2587. * Replace our sampled guards from the Guards entries in <b>state</b>. Return 0
  2588. * on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only
  2589. * check whether replacing would work.)
  2590. */
  2591. static int
  2592. entry_guards_load_guards_from_state(or_state_t *state, int set)
  2593. {
  2594. const config_line_t *line = state->Guard;
  2595. int n_errors = 0;
  2596. if (!guard_contexts)
  2597. guard_contexts = smartlist_new();
  2598. /* Wipe all our existing guard info. (we shouldn't have any, but
  2599. * let's be safe.) */
  2600. if (set) {
  2601. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2602. guard_selection_free(gs);
  2603. if (curr_guard_context == gs)
  2604. curr_guard_context = NULL;
  2605. SMARTLIST_DEL_CURRENT(guard_contexts, gs);
  2606. } SMARTLIST_FOREACH_END(gs);
  2607. }
  2608. for ( ; line != NULL; line = line->next) {
  2609. entry_guard_t *guard = entry_guard_parse_from_state(line->value);
  2610. if (guard == NULL) {
  2611. ++n_errors;
  2612. continue;
  2613. }
  2614. tor_assert(guard->selection_name);
  2615. if (!strcmp(guard->selection_name, "legacy")) {
  2616. ++n_errors;
  2617. entry_guard_free(guard);
  2618. continue;
  2619. }
  2620. if (set) {
  2621. guard_selection_t *gs;
  2622. gs = get_guard_selection_by_name(guard->selection_name,
  2623. GS_TYPE_INFER, 1);
  2624. tor_assert(gs);
  2625. smartlist_add(gs->sampled_entry_guards, guard);
  2626. guard->in_selection = gs;
  2627. } else {
  2628. entry_guard_free(guard);
  2629. }
  2630. }
  2631. if (set) {
  2632. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2633. entry_guards_update_all(gs);
  2634. } SMARTLIST_FOREACH_END(gs);
  2635. }
  2636. return n_errors ? -1 : 0;
  2637. }
  2638. /** If <b>digest</b> matches the identity of any node in the
  2639. * entry_guards list for the provided guard selection state,
  2640. return that node. Else return NULL. */
  2641. entry_guard_t *
  2642. entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
  2643. const char *digest)
  2644. {
  2645. return get_sampled_guard_with_id(gs, (const uint8_t*)digest);
  2646. }
  2647. /** Return the node_t associated with a single entry_guard_t. May
  2648. * return NULL if the guard is not currently in the consensus. */
  2649. const node_t *
  2650. entry_guard_find_node(const entry_guard_t *guard)
  2651. {
  2652. tor_assert(guard);
  2653. return node_get_by_id(guard->identity);
  2654. }
  2655. /** If <b>digest</b> matches the identity of any node in the
  2656. * entry_guards list for the default guard selection state,
  2657. return that node. Else return NULL. */
  2658. entry_guard_t *
  2659. entry_guard_get_by_id_digest(const char *digest)
  2660. {
  2661. return entry_guard_get_by_id_digest_for_guard_selection(
  2662. get_guard_selection_info(), digest);
  2663. }
  2664. /** We are about to connect to bridge with identity <b>digest</b> to fetch its
  2665. * descriptor. Create a new guard state for this connection and return it. */
  2666. circuit_guard_state_t *
  2667. get_guard_state_for_bridge_desc_fetch(const char *digest)
  2668. {
  2669. circuit_guard_state_t *guard_state = NULL;
  2670. entry_guard_t *guard = NULL;
  2671. guard = entry_guard_get_by_id_digest_for_guard_selection(
  2672. get_guard_selection_info(), digest);
  2673. if (!guard) {
  2674. return NULL;
  2675. }
  2676. /* Update the guard last_tried_to_connect time since it's checked by the
  2677. * guard susbsystem. */
  2678. guard->last_tried_to_connect = approx_time();
  2679. /* Create the guard state */
  2680. guard_state = circuit_guard_state_new(guard,
  2681. GUARD_CIRC_STATE_USABLE_ON_COMPLETION,
  2682. NULL);
  2683. return guard_state;
  2684. }
  2685. /** Release all storage held by <b>e</b>. */
  2686. STATIC void
  2687. entry_guard_free(entry_guard_t *e)
  2688. {
  2689. if (!e)
  2690. return;
  2691. entry_guard_handles_clear(e);
  2692. tor_free(e->sampled_by_version);
  2693. tor_free(e->extra_state_fields);
  2694. tor_free(e->selection_name);
  2695. tor_free(e->bridge_addr);
  2696. tor_free(e);
  2697. }
  2698. /** Return 0 if we're fine adding arbitrary routers out of the
  2699. * directory to our entry guard list, or return 1 if we have a
  2700. * list already and we must stick to it.
  2701. */
  2702. int
  2703. entry_list_is_constrained(const or_options_t *options)
  2704. {
  2705. // XXXX #21425 look at the current selection.
  2706. if (options->EntryNodes)
  2707. return 1;
  2708. if (options->UseBridges)
  2709. return 1;
  2710. return 0;
  2711. }
  2712. /** Return the number of bridges that have descriptors that are marked with
  2713. * purpose 'bridge' and are running.
  2714. */
  2715. int
  2716. num_bridges_usable(void)
  2717. {
  2718. int n_options = 0;
  2719. tor_assert(get_options()->UseBridges);
  2720. guard_selection_t *gs = get_guard_selection_info();
  2721. tor_assert(gs->type == GS_TYPE_BRIDGE);
  2722. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  2723. if (guard->is_reachable == GUARD_REACHABLE_NO)
  2724. continue;
  2725. if (tor_digest_is_zero(guard->identity))
  2726. continue;
  2727. const node_t *node = node_get_by_id(guard->identity);
  2728. if (node && node->ri)
  2729. ++n_options;
  2730. } SMARTLIST_FOREACH_END(guard);
  2731. return n_options;
  2732. }
  2733. /** Check the pathbias use success count of <b>node</b> and disable it if it
  2734. * goes over our thresholds. */
  2735. static void
  2736. pathbias_check_use_success_count(entry_guard_t *node)
  2737. {
  2738. const or_options_t *options = get_options();
  2739. const double EPSILON = 1.0e-9;
  2740. /* Note: We rely on the < comparison here to allow us to set a 0
  2741. * rate and disable the feature entirely. If refactoring, don't
  2742. * change to <= */
  2743. if (node->pb.use_attempts > EPSILON &&
  2744. pathbias_get_use_success_count(node)/node->pb.use_attempts
  2745. < pathbias_get_extreme_use_rate(options) &&
  2746. pathbias_get_dropguards(options)) {
  2747. node->pb.path_bias_disabled = 1;
  2748. log_info(LD_GENERAL,
  2749. "Path use bias is too high (%f/%f); disabling node %s",
  2750. node->pb.circ_successes, node->pb.circ_attempts,
  2751. node->nickname);
  2752. }
  2753. }
  2754. /** Check the pathbias close count of <b>node</b> and disable it if it goes
  2755. * over our thresholds. */
  2756. static void
  2757. pathbias_check_close_success_count(entry_guard_t *node)
  2758. {
  2759. const or_options_t *options = get_options();
  2760. const double EPSILON = 1.0e-9;
  2761. /* Note: We rely on the < comparison here to allow us to set a 0
  2762. * rate and disable the feature entirely. If refactoring, don't
  2763. * change to <= */
  2764. if (node->pb.circ_attempts > EPSILON &&
  2765. pathbias_get_close_success_count(node)/node->pb.circ_attempts
  2766. < pathbias_get_extreme_rate(options) &&
  2767. pathbias_get_dropguards(options)) {
  2768. node->pb.path_bias_disabled = 1;
  2769. log_info(LD_GENERAL,
  2770. "Path bias is too high (%f/%f); disabling node %s",
  2771. node->pb.circ_successes, node->pb.circ_attempts,
  2772. node->nickname);
  2773. }
  2774. }
  2775. /** Parse <b>state</b> and learn about the entry guards it describes.
  2776. * If <b>set</b> is true, and there are no errors, replace the guard
  2777. * list in the default guard selection context with what we find.
  2778. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  2779. * describing the error, and return -1.
  2780. */
  2781. int
  2782. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  2783. {
  2784. entry_guards_dirty = 0;
  2785. int r1 = entry_guards_load_guards_from_state(state, set);
  2786. entry_guards_dirty = 0;
  2787. if (r1 < 0) {
  2788. if (msg && *msg == NULL) {
  2789. *msg = tor_strdup("parsing error");
  2790. }
  2791. return -1;
  2792. }
  2793. return 0;
  2794. }
  2795. /** How long will we let a change in our guard nodes stay un-saved
  2796. * when we are trying to avoid disk writes? */
  2797. #define SLOW_GUARD_STATE_FLUSH_TIME 600
  2798. /** How long will we let a change in our guard nodes stay un-saved
  2799. * when we are not trying to avoid disk writes? */
  2800. #define FAST_GUARD_STATE_FLUSH_TIME 30
  2801. /** Our list of entry guards has changed for a particular guard selection
  2802. * context, or some element of one of our entry guards has changed for one.
  2803. * Write the changes to disk within the next few minutes.
  2804. */
  2805. void
  2806. entry_guards_changed_for_guard_selection(guard_selection_t *gs)
  2807. {
  2808. time_t when;
  2809. tor_assert(gs != NULL);
  2810. entry_guards_dirty = 1;
  2811. if (get_options()->AvoidDiskWrites)
  2812. when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
  2813. else
  2814. when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
  2815. /* or_state_save() will call entry_guards_update_state() and
  2816. entry_guards_update_guards_in_state()
  2817. */
  2818. or_state_mark_dirty(get_or_state(), when);
  2819. }
  2820. /** Our list of entry guards has changed for the default guard selection
  2821. * context, or some element of one of our entry guards has changed. Write
  2822. * the changes to disk within the next few minutes.
  2823. */
  2824. void
  2825. entry_guards_changed(void)
  2826. {
  2827. entry_guards_changed_for_guard_selection(get_guard_selection_info());
  2828. }
  2829. /** If the entry guard info has not changed, do nothing and return.
  2830. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  2831. * a new one out of the global entry_guards list, and then mark
  2832. * <b>state</b> dirty so it will get saved to disk.
  2833. */
  2834. void
  2835. entry_guards_update_state(or_state_t *state)
  2836. {
  2837. entry_guards_dirty = 0;
  2838. // Handles all guard info.
  2839. entry_guards_update_guards_in_state(state);
  2840. entry_guards_dirty = 0;
  2841. if (!get_options()->AvoidDiskWrites)
  2842. or_state_mark_dirty(get_or_state(), 0);
  2843. entry_guards_dirty = 0;
  2844. }
  2845. /**
  2846. * Format a single entry guard in the format expected by the controller.
  2847. * Return a newly allocated string.
  2848. */
  2849. STATIC char *
  2850. getinfo_helper_format_single_entry_guard(const entry_guard_t *e)
  2851. {
  2852. const char *status = NULL;
  2853. time_t when = 0;
  2854. const node_t *node;
  2855. char tbuf[ISO_TIME_LEN+1];
  2856. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  2857. /* This is going to be a bit tricky, since the status
  2858. * codes weren't really intended for prop271 guards.
  2859. *
  2860. * XXXX use a more appropriate format for exporting this information
  2861. */
  2862. if (e->confirmed_idx < 0) {
  2863. status = "never-connected";
  2864. } else if (! e->currently_listed) {
  2865. when = e->unlisted_since_date;
  2866. status = "unusable";
  2867. } else if (! e->is_filtered_guard) {
  2868. status = "unusable";
  2869. } else if (e->is_reachable == GUARD_REACHABLE_NO) {
  2870. when = e->failing_since;
  2871. status = "down";
  2872. } else {
  2873. status = "up";
  2874. }
  2875. node = entry_guard_find_node(e);
  2876. if (node) {
  2877. node_get_verbose_nickname(node, nbuf);
  2878. } else {
  2879. nbuf[0] = '$';
  2880. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  2881. /* e->nickname field is not very reliable if we don't know about
  2882. * this router any longer; don't include it. */
  2883. }
  2884. char *result = NULL;
  2885. if (when) {
  2886. format_iso_time(tbuf, when);
  2887. tor_asprintf(&result, "%s %s %s\n", nbuf, status, tbuf);
  2888. } else {
  2889. tor_asprintf(&result, "%s %s\n", nbuf, status);
  2890. }
  2891. return result;
  2892. }
  2893. /** If <b>question</b> is the string "entry-guards", then dump
  2894. * to *<b>answer</b> a newly allocated string describing all of
  2895. * the nodes in the global entry_guards list. See control-spec.txt
  2896. * for details.
  2897. * For backward compatibility, we also handle the string "helper-nodes".
  2898. *
  2899. * XXX this should be totally redesigned after prop 271 too, and that's
  2900. * going to take some control spec work.
  2901. * */
  2902. int
  2903. getinfo_helper_entry_guards(control_connection_t *conn,
  2904. const char *question, char **answer,
  2905. const char **errmsg)
  2906. {
  2907. guard_selection_t *gs = get_guard_selection_info();
  2908. tor_assert(gs != NULL);
  2909. (void) conn;
  2910. (void) errmsg;
  2911. if (!strcmp(question,"entry-guards") ||
  2912. !strcmp(question,"helper-nodes")) {
  2913. const smartlist_t *guards;
  2914. guards = gs->sampled_entry_guards;
  2915. smartlist_t *sl = smartlist_new();
  2916. SMARTLIST_FOREACH_BEGIN(guards, const entry_guard_t *, e) {
  2917. char *cp = getinfo_helper_format_single_entry_guard(e);
  2918. smartlist_add(sl, cp);
  2919. } SMARTLIST_FOREACH_END(e);
  2920. *answer = smartlist_join_strings(sl, "", 0, NULL);
  2921. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  2922. smartlist_free(sl);
  2923. }
  2924. return 0;
  2925. }
  2926. /* Given the original bandwidth of a guard and its guardfraction,
  2927. * calculate how much bandwidth the guard should have as a guard and
  2928. * as a non-guard.
  2929. *
  2930. * Quoting from proposal236:
  2931. *
  2932. * Let Wpf denote the weight from the 'bandwidth-weights' line a
  2933. * client would apply to N for position p if it had the guard
  2934. * flag, Wpn the weight if it did not have the guard flag, and B the
  2935. * measured bandwidth of N in the consensus. Then instead of choosing
  2936. * N for position p proportionally to Wpf*B or Wpn*B, clients should
  2937. * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
  2938. *
  2939. * This function fills the <b>guardfraction_bw</b> structure. It sets
  2940. * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
  2941. */
  2942. void
  2943. guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
  2944. int orig_bandwidth,
  2945. uint32_t guardfraction_percentage)
  2946. {
  2947. double guardfraction_fraction;
  2948. /* Turn the percentage into a fraction. */
  2949. tor_assert(guardfraction_percentage <= 100);
  2950. guardfraction_fraction = guardfraction_percentage / 100.0;
  2951. long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
  2952. tor_assert(guard_bw <= INT_MAX);
  2953. guardfraction_bw->guard_bw = (int) guard_bw;
  2954. guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
  2955. }
  2956. /** Helper: Update the status of all entry guards, in whatever algorithm
  2957. * is used. Return true if we should stop using all previously generated
  2958. * circuits, by calling circuit_mark_all_unused_circs() and
  2959. * circuit_mark_all_dirty_circs_as_unusable().
  2960. */
  2961. int
  2962. guards_update_all(void)
  2963. {
  2964. int mark_circuits = 0;
  2965. if (update_guard_selection_choice(get_options()))
  2966. mark_circuits = 1;
  2967. tor_assert(curr_guard_context);
  2968. if (entry_guards_update_all(curr_guard_context))
  2969. mark_circuits = 1;
  2970. return mark_circuits;
  2971. }
  2972. /** Helper: pick a guard for a circuit, with whatever algorithm is
  2973. used. */
  2974. const node_t *
  2975. guards_choose_guard(cpath_build_state_t *state,
  2976. circuit_guard_state_t **guard_state_out)
  2977. {
  2978. const node_t *r = NULL;
  2979. const uint8_t *exit_id = NULL;
  2980. entry_guard_restriction_t *rst = NULL;
  2981. if (state && (exit_id = build_state_get_exit_rsa_id(state))) {
  2982. /* We're building to a targeted exit node, so that node can't be
  2983. * chosen as our guard for this circuit. Remember that fact in a
  2984. * restriction. */
  2985. rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
  2986. memcpy(rst->exclude_id, exit_id, DIGEST_LEN);
  2987. }
  2988. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  2989. GUARD_USAGE_TRAFFIC,
  2990. rst,
  2991. &r,
  2992. guard_state_out) < 0) {
  2993. tor_assert(r == NULL);
  2994. }
  2995. return r;
  2996. }
  2997. /** Remove all currently listed entry guards for a given guard selection
  2998. * context. This frees and replaces <b>gs</b>, so don't use <b>gs</b>
  2999. * after calling this function. */
  3000. void
  3001. remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
  3002. {
  3003. // This function shouldn't exist. XXXX
  3004. tor_assert(gs != NULL);
  3005. char *old_name = tor_strdup(gs->name);
  3006. guard_selection_type_t old_type = gs->type;
  3007. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry, {
  3008. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3009. });
  3010. if (gs == curr_guard_context) {
  3011. curr_guard_context = NULL;
  3012. }
  3013. smartlist_remove(guard_contexts, gs);
  3014. guard_selection_free(gs);
  3015. gs = get_guard_selection_by_name(old_name, old_type, 1);
  3016. entry_guards_changed_for_guard_selection(gs);
  3017. tor_free(old_name);
  3018. }
  3019. /** Remove all currently listed entry guards, so new ones will be chosen.
  3020. *
  3021. * XXXX This function shouldn't exist -- it's meant to support the DROPGUARDS
  3022. * command, which is deprecated.
  3023. */
  3024. void
  3025. remove_all_entry_guards(void)
  3026. {
  3027. remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
  3028. }
  3029. /** Helper: pick a directory guard, with whatever algorithm is used. */
  3030. const node_t *
  3031. guards_choose_dirguard(circuit_guard_state_t **guard_state_out)
  3032. {
  3033. const node_t *r = NULL;
  3034. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  3035. GUARD_USAGE_DIRGUARD,
  3036. NULL,
  3037. &r,
  3038. guard_state_out) < 0) {
  3039. tor_assert(r == NULL);
  3040. }
  3041. return r;
  3042. }
  3043. /**
  3044. * If we're running with a constrained guard set, then maybe mark our guards
  3045. * usable. Return 1 if we do; 0 if we don't.
  3046. */
  3047. int
  3048. guards_retry_optimistic(const or_options_t *options)
  3049. {
  3050. if (! entry_list_is_constrained(options))
  3051. return 0;
  3052. mark_primary_guards_maybe_reachable(get_guard_selection_info());
  3053. return 1;
  3054. }
  3055. /**
  3056. * Check if we are missing any crucial dirinfo for the guard subsystem to
  3057. * work. Return NULL if everything went well, otherwise return a newly
  3058. * allocated string with an informative error message. In the latter case, use
  3059. * the genreal descriptor information <b>using_mds</b>, <b>num_present</b> and
  3060. * <b>num_usable</b> to improve the error message. */
  3061. char *
  3062. guard_selection_get_dir_info_status_str(guard_selection_t *gs,
  3063. int using_mds,
  3064. int num_present, int num_usable)
  3065. {
  3066. if (!gs->primary_guards_up_to_date)
  3067. entry_guards_update_primary(gs);
  3068. char *ret_str = NULL;
  3069. int n_missing_descriptors = 0;
  3070. int n_considered = 0;
  3071. int num_primary_to_check;
  3072. /* We want to check for the descriptor of at least the first two primary
  3073. * guards in our list, since these are the guards that we typically use for
  3074. * circuits. */
  3075. num_primary_to_check = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC);
  3076. num_primary_to_check++;
  3077. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  3078. entry_guard_consider_retry(guard);
  3079. if (guard->is_reachable == GUARD_REACHABLE_NO)
  3080. continue;
  3081. n_considered++;
  3082. if (!guard_has_descriptor(guard))
  3083. n_missing_descriptors++;
  3084. if (n_considered >= num_primary_to_check)
  3085. break;
  3086. } SMARTLIST_FOREACH_END(guard);
  3087. /* If we are not missing any descriptors, return NULL. */
  3088. if (!n_missing_descriptors) {
  3089. return NULL;
  3090. }
  3091. /* otherwise return a helpful error string */
  3092. tor_asprintf(&ret_str, "We're missing descriptors for %d/%d of our "
  3093. "primary entry guards (total %sdescriptors: %d/%d).",
  3094. n_missing_descriptors, num_primary_to_check,
  3095. using_mds?"micro":"", num_present, num_usable);
  3096. return ret_str;
  3097. }
  3098. /** As guard_selection_have_enough_dir_info_to_build_circuits, but uses
  3099. * the default guard selection. */
  3100. char *
  3101. entry_guards_get_dir_info_status_str(int using_mds,
  3102. int num_present, int num_usable)
  3103. {
  3104. return guard_selection_get_dir_info_status_str(get_guard_selection_info(),
  3105. using_mds,
  3106. num_present, num_usable);
  3107. }
  3108. /** Free one guard selection context */
  3109. STATIC void
  3110. guard_selection_free(guard_selection_t *gs)
  3111. {
  3112. if (!gs) return;
  3113. tor_free(gs->name);
  3114. if (gs->sampled_entry_guards) {
  3115. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
  3116. entry_guard_free(e));
  3117. smartlist_free(gs->sampled_entry_guards);
  3118. gs->sampled_entry_guards = NULL;
  3119. }
  3120. smartlist_free(gs->confirmed_entry_guards);
  3121. smartlist_free(gs->primary_entry_guards);
  3122. tor_free(gs);
  3123. }
  3124. /** Release all storage held by the list of entry guards and related
  3125. * memory structs. */
  3126. void
  3127. entry_guards_free_all(void)
  3128. {
  3129. /* Null out the default */
  3130. curr_guard_context = NULL;
  3131. /* Free all the guard contexts */
  3132. if (guard_contexts != NULL) {
  3133. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  3134. guard_selection_free(gs);
  3135. } SMARTLIST_FOREACH_END(gs);
  3136. smartlist_free(guard_contexts);
  3137. guard_contexts = NULL;
  3138. }
  3139. circuit_build_times_free_timeouts(get_circuit_build_times_mutable());
  3140. }