entrynodes.c 110 KB

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