entrynodes.c 127 KB

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