entrynodes.c 143 KB

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