entrynodes.c 109 KB

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