entrynodes.c 127 KB

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