entrynodes.c 109 KB

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