entrynodes.c 120 KB

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