entrynodes.c 124 KB

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