entrynodes.c 109 KB

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