entrynodes.c 120 KB

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