entrynodes.c 120 KB

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