entrynodes.c 120 KB

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