entrynodes.c 122 KB

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