entrynodes.c 119 KB

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