entrynodes.c 130 KB

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