entrynodes.c 109 KB

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