entrynodes.c 138 KB

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