entrynodes.c 134 KB

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