entrynodes.c 120 KB

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