entrynodes.c 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file entrynodes.c
  8. * \brief Code to manage our fixed first nodes for various functions.
  9. *
  10. * Entry nodes can be guards (for general use) or bridges (for censorship
  11. * circumvention).
  12. *
  13. * XXXX prop271 This module is in flux, since I'm currently in the middle of
  14. * implementation proposal 271. The module documentation here will describe
  15. * the new algorithm and data structures; the old ones should get removed as
  16. * proposal 271 is completed.
  17. *
  18. * In general, we use entry guards to prevent traffic-sampling attacks:
  19. * if we chose every circuit independently, an adversary controlling
  20. * some fraction of paths on the network would observe a sample of every
  21. * user's traffic. Using guards gives users a chance of not being
  22. * profiled.
  23. *
  24. * The current entry guard selection code is designed to try to avoid
  25. * _ever_ trying every guard on the network, to try to stick to guards
  26. * that we've used before, to handle hostile/broken networks, and
  27. * to behave sanely when the network goes up and down.
  28. *
  29. * Our algorithm works as follows: First, we maintain a SAMPLE of guards
  30. * we've seen in the networkstatus consensus. We maintain this sample
  31. * over time, and store it persistently; it is chosen without reference
  32. * to our configuration or firewall rules. Guards remain in the sample
  33. * as they enter and leave the consensus. We expand this sample as
  34. * needed, up to a maximum size.
  35. *
  36. * As a subset of the sample, we maintain a FILTERED SET of the guards
  37. * that we would be willing to use if we could connect to them. The
  38. * filter removes all the guards that we're excluding because they're
  39. * bridges (or not bridges), because we have restrictive firewall rules,
  40. * because of ExcludeNodes, because we of path bias restrictions,
  41. * because they're absent from the network at present, and so on.
  42. *
  43. * As a subset of the filtered set, we keep a REACHABLE FILTERED SET
  44. * (also called a "usable filtered set") of those guards that we call
  45. * "reachable" or "maybe reachable". A guard is reachable if we've
  46. * connected to it more recently than we've failed. A guard is "maybe
  47. * reachable" if we have never tried to connect to it, or if we
  48. * failed to connect to it so long ago that we no longer think our
  49. * failure means it's down.
  50. *
  51. * As a persistent ordered list whose elements are taken from the
  52. * sampled set, we track a CONFIRMED GUARDS LIST. A guard becomes
  53. * confirmed when we successfully build a circuit through it, and decide
  54. * to use that circuit. We order the guards on this list by the order
  55. * in which they became confirmed.
  56. *
  57. * And as a final group, we have an ordered list of PRIMARY GUARDS,
  58. * whose elements are taken from the filtered set. We prefer
  59. * confirmed guards to non-confirmed guards for this list, and place
  60. * other restrictions on it. The primary guards are the ones that we
  61. * connect to "when nothing is wrong" -- circuits through them can be used
  62. * immediately.
  63. *
  64. * To build circuits, we take a primary guard if possible -- or a
  65. * reachable filtered confirmed guard if no primary guard is possible --
  66. * or a random reachable filtered guard otherwise. If the guard is
  67. * primary, we can use the circuit immediately on success. Otherwise,
  68. * the guard is now "pending" -- we won't use its circuit unless all
  69. * of the circuits we're trying to build through better guards have
  70. * definitely failed.
  71. *
  72. * While we're building circuits, we track a little "guard state" for
  73. * each circuit. We use this to keep track of whether the circuit is
  74. * one that we can use as soon as its done, or whether it's one that
  75. * we should keep around to see if we can do better. In the latter case,
  76. * a periodic call to entry_guards_upgrade_waiting_circuits() will
  77. * eventually upgrade it.
  78. **/
  79. /* DOCDOC -- expand this.
  80. *
  81. * Information invariants:
  82. *
  83. * [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
  84. *
  85. * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
  86. * flag is set, set its usable_filtered flag.
  87. *
  88. * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
  89. *
  90. * [x] Whenever the configuration changes in a relevant way, update the
  91. * filtered/usable flags. (LATER.)
  92. *
  93. * [x] Whenever we add a guard to the sample, make sure its filtered/usable
  94. * flags are set as possible.
  95. *
  96. * [x] Whenever we remove a guard from the sample, remove it from the primary
  97. * and confirmed lists.
  98. *
  99. * [x] When we make a guard confirmed, update the primary list.
  100. *
  101. * [x] When we make a guard filtered or unfiltered, update the primary list.
  102. *
  103. * [x] When we are about to pick a guard, make sure that the primary list is
  104. * full.
  105. *
  106. * [x] Before calling sample_reachable_filtered_entry_guards(), make sure
  107. * that the filtered, primary, and confirmed flags are up-to-date.
  108. *
  109. * [x] Call entry_guard_consider_retry every time we are about to check
  110. * is_usable_filtered or is_reachable, and every time we set
  111. * is_filtered to 1.
  112. *
  113. * [x] Call entry_guards_changed_for_guard_selection() whenever we update
  114. * a persistent field.
  115. */
  116. #define ENTRYNODES_PRIVATE
  117. #include "or.h"
  118. #include "bridges.h"
  119. #include "circpathbias.h"
  120. #include "circuitbuild.h"
  121. #include "circuitlist.h"
  122. #include "circuitstats.h"
  123. #include "config.h"
  124. #include "confparse.h"
  125. #include "connection.h"
  126. #include "connection_or.h"
  127. #include "control.h"
  128. #include "directory.h"
  129. #include "entrynodes.h"
  130. #include "main.h"
  131. #include "microdesc.h"
  132. #include "networkstatus.h"
  133. #include "nodelist.h"
  134. #include "policies.h"
  135. #include "router.h"
  136. #include "routerlist.h"
  137. #include "routerparse.h"
  138. #include "routerset.h"
  139. #include "transports.h"
  140. #include "statefile.h"
  141. static smartlist_t *guard_contexts = NULL;
  142. static guard_selection_t *curr_guard_context = NULL;
  143. /** A value of 1 means that at least one context has changed,
  144. * and those changes need to be flushed to disk. */
  145. static int entry_guards_dirty = 0;
  146. static const node_t *choose_random_entry_impl(guard_selection_t *gs,
  147. cpath_build_state_t *state,
  148. int for_directory,
  149. dirinfo_type_t dirtype,
  150. int *n_options_out);
  151. static void entry_guard_set_filtered_flags(const or_options_t *options,
  152. guard_selection_t *gs,
  153. entry_guard_t *guard);
  154. static void pathbias_check_use_success_count(entry_guard_t *guard);
  155. static void pathbias_check_close_success_count(entry_guard_t *guard);
  156. /** Return 0 if we should apply guardfraction information found in the
  157. * consensus. A specific consensus can be specified with the
  158. * <b>ns</b> argument, if NULL the most recent one will be picked.*/
  159. int
  160. should_apply_guardfraction(const networkstatus_t *ns)
  161. {
  162. /* We need to check the corresponding torrc option and the consensus
  163. * parameter if we need to. */
  164. const or_options_t *options = get_options();
  165. /* If UseGuardFraction is 'auto' then check the same-named consensus
  166. * parameter. If the consensus parameter is not present, default to
  167. * "off". */
  168. if (options->UseGuardFraction == -1) {
  169. return networkstatus_get_param(ns, "UseGuardFraction",
  170. 0, /* default to "off" */
  171. 0, 1);
  172. }
  173. return options->UseGuardFraction;
  174. }
  175. /**
  176. * Allocate and return a new guard_selection_t, with the name <b>name</b>.
  177. */
  178. STATIC guard_selection_t *
  179. guard_selection_new(const char *name)
  180. {
  181. guard_selection_t *gs;
  182. gs = tor_malloc_zero(sizeof(*gs));
  183. gs->name = tor_strdup(name);
  184. gs->chosen_entry_guards = smartlist_new();
  185. gs->sampled_entry_guards = smartlist_new();
  186. gs->confirmed_entry_guards = smartlist_new();
  187. gs->primary_entry_guards = smartlist_new();
  188. return gs;
  189. }
  190. /**
  191. * Return the guard selection called <b>name</b>. If there is none, and
  192. * <b>create_if_absent</b> is true, then create and return it. If there
  193. * is none, and <b>create_if_absent</b> is false, then return NULL.
  194. */
  195. STATIC guard_selection_t *
  196. get_guard_selection_by_name(const char *name, int create_if_absent)
  197. {
  198. if (!guard_contexts) {
  199. guard_contexts = smartlist_new();
  200. }
  201. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  202. if (!strcmp(gs->name, name))
  203. return gs;
  204. } SMARTLIST_FOREACH_END(gs);
  205. if (! create_if_absent)
  206. return NULL;
  207. guard_selection_t *new_selection = guard_selection_new(name);
  208. smartlist_add(guard_contexts, new_selection);
  209. const char *default_name = get_options()->UseDeprecatedGuardAlgorithm ?
  210. "legacy" : "default";
  211. if (!strcmp(name, default_name))
  212. curr_guard_context = new_selection;
  213. return new_selection;
  214. }
  215. /** Get current default guard_selection_t, creating it if necessary */
  216. guard_selection_t *
  217. get_guard_selection_info(void)
  218. {
  219. if (!guard_contexts) {
  220. guard_contexts = smartlist_new();
  221. }
  222. if (!curr_guard_context) {
  223. const char *name = get_options()->UseDeprecatedGuardAlgorithm ?
  224. "legacy" : "default";
  225. curr_guard_context = guard_selection_new(name);
  226. smartlist_add(guard_contexts, curr_guard_context);
  227. }
  228. return curr_guard_context;
  229. }
  230. /** Return the list of entry guards for a guard_selection_t, creating it
  231. * if necessary. */
  232. const smartlist_t *
  233. get_entry_guards_for_guard_selection(guard_selection_t *gs)
  234. {
  235. tor_assert(gs != NULL);
  236. tor_assert(gs->chosen_entry_guards != NULL);
  237. return gs->chosen_entry_guards;
  238. }
  239. /** Return the list of entry guards for the default guard_selection_t,
  240. * creating it if necessary. */
  241. const smartlist_t *
  242. get_entry_guards(void)
  243. {
  244. return get_entry_guards_for_guard_selection(get_guard_selection_info());
  245. }
  246. /** Helper: mark an entry guard as not usable. */
  247. void
  248. entry_guard_mark_bad(entry_guard_t *guard)
  249. {
  250. guard->bad_since = approx_time();
  251. entry_guards_changed();
  252. }
  253. /** Return a statically allocated human-readable description of <b>guard</b>
  254. */
  255. const char *
  256. entry_guard_describe(const entry_guard_t *guard)
  257. {
  258. static char buf[256];
  259. tor_snprintf(buf, sizeof(buf),
  260. "%s ($%s)",
  261. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  262. return buf;
  263. }
  264. /** Return <b>guard</b>'s 20-byte RSA identity digest */
  265. const char *
  266. entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
  267. {
  268. return guard->identity;
  269. }
  270. /** Return the pathbias state associated with <b>guard</b>. */
  271. guard_pathbias_t *
  272. entry_guard_get_pathbias_state(entry_guard_t *guard)
  273. {
  274. return &guard->pb;
  275. }
  276. HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC)
  277. /** Return an interval betweeen 'now' and 'max_backdate' seconds in the past,
  278. * chosen uniformly at random. We use this before recording persistent
  279. * dates, so that we aren't leaking exactly when we recorded it.
  280. */
  281. MOCK_IMPL(STATIC time_t,
  282. randomize_time,(time_t now, time_t max_backdate))
  283. {
  284. tor_assert(max_backdate > 0);
  285. time_t earliest = now - max_backdate;
  286. time_t latest = now;
  287. if (earliest <= 0)
  288. earliest = 1;
  289. if (latest <= earliest)
  290. latest = earliest + 1;
  291. return crypto_rand_time_range(earliest, latest);
  292. }
  293. /**
  294. * Return true iff <b>node</b> has all the flags needed for us to consider it
  295. * a possible guard when sampling guards.
  296. */
  297. static int
  298. node_is_possible_guard(guard_selection_t *gs, const node_t *node)
  299. {
  300. /* The "GUARDS" set is all nodes in the nodelist for which this predicate
  301. * holds. */
  302. /* XXXX -- prop271 spec deviation. We require node_is_dir() here. */
  303. (void)gs;
  304. tor_assert(node);
  305. return (node->is_possible_guard &&
  306. node->is_stable &&
  307. node->is_fast &&
  308. node->is_valid &&
  309. node_is_dir(node));
  310. }
  311. /**
  312. * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
  313. * NULL if we don't have one. */
  314. STATIC entry_guard_t *
  315. get_sampled_guard_with_id(guard_selection_t *gs,
  316. const uint8_t *rsa_id)
  317. {
  318. tor_assert(gs);
  319. tor_assert(rsa_id);
  320. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  321. if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN))
  322. return guard;
  323. } SMARTLIST_FOREACH_END(guard);
  324. return NULL;
  325. }
  326. /**
  327. * Return true iff we have a sampled guard with the RSA identity digest
  328. * <b>rsa_id</b>. */
  329. static inline int
  330. have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
  331. {
  332. return get_sampled_guard_with_id(gs, rsa_id) != NULL;
  333. }
  334. /**
  335. * Allocate a new entry_guard_t object for <b>node</b>, add it to the
  336. * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
  337. * not currently be a sampled guard in <b>gs</b>.
  338. */
  339. STATIC entry_guard_t *
  340. entry_guard_add_to_sample(guard_selection_t *gs,
  341. const node_t *node)
  342. {
  343. const int GUARD_LIFETIME = GUARD_LIFETIME_DAYS * 86400;
  344. tor_assert(gs);
  345. tor_assert(node);
  346. log_info(LD_GUARD, "Adding %s as to the entry guard sample set.",
  347. node_describe(node));
  348. // XXXX prop271 take ed25519 identity here too.
  349. /* make sure that the guard is not already sampled. */
  350. if (BUG(have_sampled_guard_with_id(gs, (uint8_t*)node->identity)))
  351. return NULL; // LCOV_EXCL_LINE
  352. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  353. /* persistent fields */
  354. guard->selection_name = tor_strdup(gs->name);
  355. memcpy(guard->identity, node->identity, DIGEST_LEN);
  356. strlcpy(guard->nickname, node_get_nickname(node), sizeof(guard->nickname));
  357. guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  358. tor_free(guard->sampled_by_version);
  359. guard->sampled_by_version = tor_strdup(VERSION);
  360. guard->currently_listed = 1;
  361. guard->confirmed_idx = -1;
  362. /* non-persistent fields */
  363. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  364. smartlist_add(gs->sampled_entry_guards, guard);
  365. entry_guard_set_filtered_flags(get_options(), gs, guard);
  366. entry_guards_changed_for_guard_selection(gs);
  367. return guard;
  368. }
  369. /**
  370. * Return the number of sampled guards in <b>gs</b> that are "filtered"
  371. * (that is, we're willing to connect to them) and that are "usable"
  372. * (that is, either "reachable" or "maybe reachable"). */
  373. STATIC int
  374. num_reachable_filtered_guards(guard_selection_t *gs)
  375. {
  376. int n_reachable_filtered_guards = 0;
  377. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  378. entry_guard_consider_retry(guard);
  379. if (guard->is_usable_filtered_guard)
  380. ++n_reachable_filtered_guards;
  381. } SMARTLIST_FOREACH_END(guard);
  382. return n_reachable_filtered_guards;
  383. }
  384. /**
  385. * Add new guards to the sampled guards in <b>gs</b> until there are
  386. * enough usable filtered guards, but never grow the sample beyond its
  387. * maximum size. Return the last guard added, or NULL if none were
  388. * added.
  389. */
  390. STATIC entry_guard_t *
  391. entry_guards_expand_sample(guard_selection_t *gs)
  392. {
  393. tor_assert(gs);
  394. int n_sampled = smartlist_len(gs->sampled_entry_guards);
  395. entry_guard_t *added_guard = NULL;
  396. smartlist_t *nodes = nodelist_get_list();
  397. /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
  398. smartlist_t *eligible_guards = smartlist_new();
  399. int n_guards = 0; // total size of "GUARDS"
  400. int n_usable_filtered_guards = num_reachable_filtered_guards(gs);
  401. {
  402. /* Build a bloom filter of our current guards: let's keep this O(N). */
  403. digestset_t *sampled_guard_ids = digestset_new(n_sampled);
  404. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *,
  405. guard) {
  406. digestset_add(sampled_guard_ids, guard->identity);
  407. } SMARTLIST_FOREACH_END(guard);
  408. SMARTLIST_FOREACH_BEGIN(nodes, node_t *, node) {
  409. if (! node_is_possible_guard(gs, node))
  410. continue;
  411. ++n_guards;
  412. if (digestset_contains(sampled_guard_ids, node->identity))
  413. continue;
  414. smartlist_add(eligible_guards, node);
  415. } SMARTLIST_FOREACH_END(node);
  416. /* Now we can free that bloom filter. */
  417. digestset_free(sampled_guard_ids);
  418. }
  419. /* Is there at least one guard we haven't sampled? */
  420. if (! smartlist_len(eligible_guards))
  421. goto done;
  422. const int max_sample = (int)(n_guards * MAX_SAMPLE_THRESHOLD);
  423. const int min_filtered_sample = MIN_FILTERED_SAMPLE_SIZE;
  424. log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
  425. "in the sample, and %d eligible guards to extend it with.",
  426. n_sampled, smartlist_len(eligible_guards));
  427. while (n_usable_filtered_guards < min_filtered_sample) {
  428. /* Has our sample grown too large to expand? */
  429. if (n_sampled >= max_sample) {
  430. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  431. "just hit the maximum sample threshold of %d",
  432. max_sample);
  433. goto done;
  434. }
  435. /* Did we run out of guards? */
  436. if (smartlist_len(eligible_guards) == 0) {
  437. /* LCOV_EXCL_START
  438. As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
  439. allow all guards to be sampled, this can't be reached.
  440. */
  441. log_info(LD_GUARD, "Not expanding the guard sample any further; "
  442. "just ran out of eligible guards");
  443. goto done;
  444. /* LCOV_EXCL_STOP */
  445. }
  446. /* Otherwise we can add at least one new guard. */
  447. const node_t *node =
  448. node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD);
  449. if (BUG(! node))
  450. goto done; // LCOV_EXCL_LINE -- should be impossible.
  451. added_guard = entry_guard_add_to_sample(gs, node);
  452. if (!added_guard)
  453. goto done; // LCOV_EXCL_LINE -- only fails on BUG.
  454. ++n_sampled;
  455. if (added_guard->is_usable_filtered_guard)
  456. ++n_usable_filtered_guards;
  457. smartlist_remove(eligible_guards, node);
  458. }
  459. done:
  460. smartlist_free(eligible_guards);
  461. return added_guard;
  462. }
  463. /**
  464. * Helper: <b>guard</b> has just been removed from the sampled guards:
  465. * also remove it from primary and confirmed. */
  466. static void
  467. remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs,
  468. entry_guard_t *guard)
  469. {
  470. if (guard->is_primary) {
  471. guard->is_primary = 0;
  472. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  473. } else {
  474. if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
  475. smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  476. }
  477. }
  478. if (guard->confirmed_idx >= 0) {
  479. entry_guard_t *found_guard = NULL;
  480. if (guard->confirmed_idx < smartlist_len(gs->confirmed_entry_guards))
  481. found_guard = smartlist_get(gs->confirmed_entry_guards,
  482. guard->confirmed_idx);
  483. if (BUG(guard != found_guard)) {
  484. // LCOV_EXCL_START
  485. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  486. // LCOV_EXCL_STOP
  487. } else {
  488. smartlist_del_keeporder(gs->confirmed_entry_guards,
  489. guard->confirmed_idx);
  490. }
  491. guard->confirmed_idx = -1;
  492. guard->confirmed_on_date = 0;
  493. } else {
  494. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
  495. // LCOV_EXCL_START
  496. smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
  497. // LCOV_EXCL_STOP
  498. }
  499. }
  500. }
  501. /**
  502. * Update the status of all sampled guards based on the arrival of a
  503. * new consensus networkstatus document. This will include marking
  504. * some guards as listed or unlisted, and removing expired guards. */
  505. STATIC void
  506. sampled_guards_update_from_consensus(guard_selection_t *gs)
  507. {
  508. tor_assert(gs);
  509. const int REMOVE_UNLISTED_GUARDS_AFTER =
  510. (REMOVE_UNLISTED_GUARDS_AFTER_DAYS * 86400);
  511. const int unlisted_since_slop = REMOVE_UNLISTED_GUARDS_AFTER / 5;
  512. // It's important to use only a live consensus here; we don't want to
  513. // make changes based on anything expired or old.
  514. networkstatus_t *ns = networkstatus_get_live_consensus(approx_time());
  515. log_info(LD_GUARD, "Updating sampled guard status based on received "
  516. "consensus.");
  517. if (! ns || ns->valid_until < approx_time()) {
  518. log_info(LD_GUARD, "Hey, that consensus isn't still valid. Ignoring.");
  519. return;
  520. }
  521. int n_changes = 0;
  522. /* First: Update listed/unlisted. */
  523. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  524. /* XXXX prop271 handle bridges right? */
  525. /* XXXX prop271 check ed ID too */
  526. const node_t *node = node_get_by_id(guard->identity);
  527. const unsigned is_listed = node && node_is_possible_guard(gs, node);
  528. if (is_listed && ! guard->currently_listed) {
  529. ++n_changes;
  530. guard->currently_listed = 1;
  531. guard->unlisted_since_date = 0;
  532. log_info(LD_GUARD, "Sampled guard %s is now listed again.",
  533. entry_guard_describe(guard));
  534. } else if (!is_listed && guard->currently_listed) {
  535. ++n_changes;
  536. guard->currently_listed = 0;
  537. guard->unlisted_since_date = randomize_time(approx_time(),
  538. unlisted_since_slop);
  539. log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
  540. entry_guard_describe(guard));
  541. } else if (is_listed && guard->currently_listed) {
  542. log_debug(LD_GUARD, "Sampled guard %s is still listed.",
  543. entry_guard_describe(guard));
  544. } else {
  545. tor_assert(! is_listed && ! guard->currently_listed);
  546. log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
  547. entry_guard_describe(guard));
  548. }
  549. /* Clean up unlisted_since_date, just in case. */
  550. if (guard->currently_listed && guard->unlisted_since_date) {
  551. ++n_changes;
  552. guard->unlisted_since_date = 0;
  553. log_warn(LD_BUG, "Sampled guard %s was listed, but with "
  554. "unlisted_since_date set. Fixing.",
  555. entry_guard_describe(guard));
  556. } else if (!guard->currently_listed && ! guard->unlisted_since_date) {
  557. ++n_changes;
  558. guard->unlisted_since_date = randomize_time(approx_time(),
  559. unlisted_since_slop);
  560. log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
  561. "unlisted_since_date unset. Fixing.",
  562. entry_guard_describe(guard));
  563. }
  564. } SMARTLIST_FOREACH_END(guard);
  565. const time_t remove_if_unlisted_since =
  566. approx_time() - REMOVE_UNLISTED_GUARDS_AFTER;
  567. const time_t maybe_remove_if_sampled_before =
  568. approx_time() - (GUARD_LIFETIME_DAYS * 86400);
  569. const time_t remove_if_confirmed_before =
  570. approx_time() - (GUARD_CONFIRMED_MIN_LIFETIME_DAYS * 86400);
  571. /* Then: remove the ones that have been junk for too long */
  572. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  573. /* XXXX prop271 handle bridges right? */
  574. int remove = 0;
  575. if (guard->currently_listed == 0 &&
  576. guard->unlisted_since_date < remove_if_unlisted_since) {
  577. /*
  578. "We have a live consensus, and {IS_LISTED} is false, and
  579. {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}
  580. days in the past."
  581. */
  582. log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
  583. "for over %d days", entry_guard_describe(guard),
  584. REMOVE_UNLISTED_GUARDS_AFTER_DAYS);
  585. remove = 1;
  586. } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
  587. /* We have a live consensus, and {ADDED_ON_DATE} is over
  588. {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
  589. "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
  590. */
  591. if (guard->confirmed_on_date == 0) {
  592. remove = 1;
  593. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  594. "over %d days ago, but never confirmed.",
  595. entry_guard_describe(guard),
  596. GUARD_LIFETIME_DAYS);
  597. } else if (guard->confirmed_on_date < remove_if_confirmed_before) {
  598. remove = 1;
  599. log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
  600. "over %d days ago, and confirmed over %d days ago.",
  601. entry_guard_describe(guard),
  602. GUARD_LIFETIME_DAYS, GUARD_CONFIRMED_MIN_LIFETIME_DAYS);
  603. }
  604. }
  605. if (remove) {
  606. ++n_changes;
  607. SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard);
  608. remove_guard_from_confirmed_and_primary_lists(gs, guard);
  609. entry_guard_free(guard);
  610. }
  611. } SMARTLIST_FOREACH_END(guard);
  612. if (n_changes) {
  613. gs->primary_guards_up_to_date = 0;
  614. entry_guards_update_filtered_sets(gs);
  615. /* We don't need to rebuild the confirmed list right here -- we may have
  616. * removed confirmed guards above, but we can't have added any new
  617. * confirmed guards.
  618. */
  619. entry_guards_changed_for_guard_selection(gs);
  620. }
  621. }
  622. /**
  623. * Return true iff <b>node</b> is a Tor relay that we are configured to
  624. * be able to connect to. */
  625. static int
  626. node_passes_guard_filter(const or_options_t *options, guard_selection_t *gs,
  627. const node_t *node)
  628. {
  629. /* NOTE: Make sure that this function stays in sync with
  630. * options_transition_affects_entry_guards */
  631. (void)gs;
  632. if (routerset_contains_node(options->ExcludeNodes, node))
  633. return 0;
  634. /* XXXX -- prop271 spec deviation -- add entrynodes to spec. */
  635. if (options->EntryNodes &&
  636. !options->UseBridges &&
  637. !routerset_contains_node(options->EntryNodes, node))
  638. return 0;
  639. if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
  640. return 0;
  641. if (bool_neq(options->UseBridges, node_is_a_configured_bridge(node)))
  642. return 0;
  643. return 1;
  644. }
  645. /**
  646. * Return true iff <b>guard</b> is a Tor relay that we are configured to
  647. * be able to connect to, and we haven't disabled it for omission from
  648. * the consensus or path bias issues. */
  649. static int
  650. entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
  651. entry_guard_t *guard)
  652. {
  653. if (guard->currently_listed == 0)
  654. return 0;
  655. if (guard->pb.path_bias_disabled)
  656. return 0;
  657. const node_t *node = node_get_by_id(guard->identity);
  658. if (node == NULL) {
  659. // This can happen when currently_listed is true, and we're not updating
  660. // it because we don't have a live consensus.
  661. return 0;
  662. }
  663. return node_passes_guard_filter(options, gs, node);
  664. }
  665. /**
  666. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  667. * flags on <b>guard</b>. */
  668. void
  669. entry_guard_set_filtered_flags(const or_options_t *options,
  670. guard_selection_t *gs,
  671. entry_guard_t *guard)
  672. {
  673. unsigned was_filtered = guard->is_filtered_guard;
  674. guard->is_filtered_guard = 0;
  675. guard->is_usable_filtered_guard = 0;
  676. if (entry_guard_passes_filter(options, gs, guard)) {
  677. guard->is_filtered_guard = 1;
  678. if (guard->is_reachable != GUARD_REACHABLE_NO)
  679. guard->is_usable_filtered_guard = 1;
  680. entry_guard_consider_retry(guard);
  681. }
  682. log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
  683. "reachable_filtered=%d.", entry_guard_describe(guard),
  684. guard->is_filtered_guard, guard->is_usable_filtered_guard);
  685. if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
  686. /* This guard might now be primary or nonprimary. */
  687. gs->primary_guards_up_to_date = 0;
  688. }
  689. }
  690. /**
  691. * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
  692. * flag on every guard in <b>gs</b>. */
  693. STATIC void
  694. entry_guards_update_filtered_sets(guard_selection_t *gs)
  695. {
  696. const or_options_t *options = get_options();
  697. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  698. entry_guard_set_filtered_flags(options, gs, guard);
  699. } SMARTLIST_FOREACH_END(guard);
  700. }
  701. /**
  702. * Return a random guard from the reachable filtered sample guards
  703. * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
  704. * Return NULL if no such guard can be found.
  705. *
  706. * Make sure that the sample is big enough, and that all the filter flags
  707. * are set correctly, before calling this function.
  708. **/
  709. STATIC entry_guard_t *
  710. sample_reachable_filtered_entry_guards(guard_selection_t *gs,
  711. unsigned flags)
  712. {
  713. tor_assert(gs);
  714. entry_guard_t *result = NULL;
  715. const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
  716. const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
  717. const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
  718. const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
  719. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  720. entry_guard_consider_retry(guard);
  721. } SMARTLIST_FOREACH_END(guard);
  722. const int n_reachable_filtered = num_reachable_filtered_guards(gs);
  723. log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
  724. "in the USABLE_FILTERED set.", n_reachable_filtered);
  725. if (n_reachable_filtered < MIN_FILTERED_SAMPLE_SIZE) {
  726. log_info(LD_GUARD, " (That isn't enough. Trying to expand the sample.)");
  727. entry_guards_expand_sample(gs);
  728. }
  729. if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
  730. entry_guards_update_primary(gs);
  731. /* Build the set of reachable filtered guards. */
  732. smartlist_t *reachable_filtered_sample = smartlist_new();
  733. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  734. entry_guard_consider_retry(guard);// redundant, but cheap.
  735. if (! guard->is_usable_filtered_guard)
  736. continue;
  737. if (exclude_confirmed && guard->confirmed_idx >= 0)
  738. continue;
  739. if (exclude_primary && guard->is_primary)
  740. continue;
  741. if (exclude_pending && guard->is_pending)
  742. continue;
  743. smartlist_add(reachable_filtered_sample, guard);
  744. } SMARTLIST_FOREACH_END(guard);
  745. log_info(LD_GUARD, " (After filters [%x], we have %d guards to consider.)",
  746. flags, smartlist_len(reachable_filtered_sample));
  747. if (smartlist_len(reachable_filtered_sample)) {
  748. result = smartlist_choose(reachable_filtered_sample);
  749. log_info(LD_GUARD, " (Selected %s.)",
  750. result ? entry_guard_describe(result) : "<null>");
  751. }
  752. smartlist_free(reachable_filtered_sample);
  753. return result;
  754. }
  755. /**
  756. * Helper: compare two entry_guard_t by their confirmed_idx values.
  757. * Used to sort the confirmed list.
  758. */
  759. static int
  760. compare_guards_by_confirmed_idx(const void **a_, const void **b_)
  761. {
  762. const entry_guard_t *a = *a_, *b = *b_;
  763. if (a->confirmed_idx < b->confirmed_idx)
  764. return -1;
  765. else if (a->confirmed_idx > b->confirmed_idx)
  766. return 1;
  767. else
  768. return 0;
  769. }
  770. /**
  771. * Find the confirmed guards from among the sampled guards in <b>gs</b>,
  772. * and put them in confirmed_entry_guards in the correct
  773. * order. Recalculate their indices.
  774. */
  775. STATIC void
  776. entry_guards_update_confirmed(guard_selection_t *gs)
  777. {
  778. smartlist_clear(gs->confirmed_entry_guards);
  779. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  780. if (guard->confirmed_idx >= 0)
  781. smartlist_add(gs->confirmed_entry_guards, guard);
  782. } SMARTLIST_FOREACH_END(guard);
  783. smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
  784. int any_changed = 0;
  785. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  786. if (guard->confirmed_idx != guard_sl_idx) {
  787. any_changed = 1;
  788. guard->confirmed_idx = guard_sl_idx;
  789. }
  790. } SMARTLIST_FOREACH_END(guard);
  791. gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
  792. if (any_changed) {
  793. entry_guards_changed_for_guard_selection(gs);
  794. }
  795. }
  796. /**
  797. * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
  798. * connected to, and intend to use again.
  799. */
  800. STATIC void
  801. make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
  802. {
  803. if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
  804. return; // LCOV_EXCL_LINE
  805. if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
  806. return; // LCOV_EXCL_LINE
  807. const int GUARD_LIFETIME = GUARD_LIFETIME_DAYS * 86400;
  808. guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  809. log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
  810. entry_guard_describe(guard),
  811. gs->next_confirmed_idx);
  812. guard->confirmed_idx = gs->next_confirmed_idx++;
  813. smartlist_add(gs->confirmed_entry_guards, guard);
  814. // This confirmed guard might kick something else out of the primary
  815. // guards.
  816. gs->primary_guards_up_to_date = 0;
  817. entry_guards_changed_for_guard_selection(gs);
  818. }
  819. /**
  820. * Recalculate the list of primary guards (the ones we'd prefer to use) from
  821. * the filtered sample and the confirmed list.
  822. */
  823. STATIC void
  824. entry_guards_update_primary(guard_selection_t *gs)
  825. {
  826. tor_assert(gs);
  827. // prevent recursion. Recursion is potentially very bad here.
  828. static int running = 0;
  829. tor_assert(!running);
  830. running = 1;
  831. smartlist_t *new_primary_guards = smartlist_new();
  832. smartlist_t *old_primary_guards = smartlist_new();
  833. smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
  834. /* Set this flag now, to prevent the calls below from recursing. */
  835. gs->primary_guards_up_to_date = 1;
  836. /* First, can we fill it up with confirmed guards? */
  837. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  838. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  839. break;
  840. if (! guard->is_filtered_guard)
  841. continue;
  842. guard->is_primary = 1;
  843. smartlist_add(new_primary_guards, guard);
  844. } SMARTLIST_FOREACH_END(guard);
  845. /* Can we keep any older primary guards? First remove all the ones
  846. * that we already kept. */
  847. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  848. if (smartlist_contains(new_primary_guards, guard)) {
  849. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  850. }
  851. } SMARTLIST_FOREACH_END(guard);
  852. /* Now add any that are still good. */
  853. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  854. if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
  855. break;
  856. if (! guard->is_filtered_guard)
  857. continue;
  858. guard->is_primary = 1;
  859. smartlist_add(new_primary_guards, guard);
  860. SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
  861. } SMARTLIST_FOREACH_END(guard);
  862. /* Mark the remaining previous primary guards as non-primary */
  863. SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
  864. guard->is_primary = 0;
  865. } SMARTLIST_FOREACH_END(guard);
  866. /* Finally, fill out the list with sampled guards. */
  867. while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
  868. entry_guard_t *guard = sample_reachable_filtered_entry_guards(gs,
  869. SAMPLE_EXCLUDE_CONFIRMED|
  870. SAMPLE_EXCLUDE_PRIMARY|
  871. SAMPLE_NO_UPDATE_PRIMARY);
  872. if (!guard)
  873. break;
  874. guard->is_primary = 1;
  875. smartlist_add(new_primary_guards, guard);
  876. }
  877. #if 1
  878. /* Debugging. */
  879. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
  880. tor_assert_nonfatal(
  881. bool_eq(guard->is_primary,
  882. smartlist_contains(new_primary_guards, guard)));
  883. });
  884. #endif
  885. int any_change = 0;
  886. if (smartlist_len(gs->primary_entry_guards) !=
  887. smartlist_len(new_primary_guards)) {
  888. any_change = 1;
  889. } else {
  890. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, g) {
  891. if (g != smartlist_get(new_primary_guards, g_sl_idx)) {
  892. any_change = 1;
  893. }
  894. } SMARTLIST_FOREACH_END(g);
  895. }
  896. if (any_change) {
  897. log_info(LD_GUARD, "Primary entry guards have changed. "
  898. "New primary guard list is: ");
  899. int n = smartlist_len(new_primary_guards);
  900. SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
  901. log_info(LD_GUARD, " %d/%d: %s%s%s",
  902. g_sl_idx+1, n, entry_guard_describe(g),
  903. g->confirmed_idx >= 0 ? " (confirmed)" : "",
  904. g->is_filtered_guard ? "" : " (excluded by filter)");
  905. } SMARTLIST_FOREACH_END(g);
  906. }
  907. smartlist_free(old_primary_guards);
  908. smartlist_free(gs->primary_entry_guards);
  909. gs->primary_entry_guards = new_primary_guards;
  910. gs->primary_guards_up_to_date = 1;
  911. running = 0;
  912. }
  913. /**
  914. * Return the number of seconds after the last attempt at which we should
  915. * retry a guard that has been failing since <b>failing_since</b>.
  916. */
  917. static unsigned
  918. get_retry_schedule(time_t failing_since, time_t now,
  919. int is_primary)
  920. {
  921. const unsigned SIX_HOURS = 6 * 3600;
  922. const unsigned FOUR_DAYS = 4 * 86400;
  923. const unsigned SEVEN_DAYS = 7 * 86400;
  924. time_t tdiff;
  925. if (now > failing_since) {
  926. tdiff = now - failing_since;
  927. } else {
  928. tdiff = 0;
  929. }
  930. const struct {
  931. time_t maximum; int primary_delay; int nonprimary_delay;
  932. } delays[] = {
  933. { SIX_HOURS, 30*60, 1*60*60 },
  934. { FOUR_DAYS, 2*60*60, 4*60*60 },
  935. { SEVEN_DAYS, 4*60*60, 18*60*60 },
  936. { TIME_MAX, 9*60*60, 36*60*60 }
  937. };
  938. unsigned i;
  939. for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
  940. if (tdiff <= delays[i].maximum) {
  941. return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
  942. }
  943. }
  944. /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
  945. tor_assert_nonfatal_unreached();
  946. return 36*60*60;
  947. /* LCOV_EXCL_STOP */
  948. }
  949. /**
  950. * If <b>guard</b> is unreachable, consider whether enough time has passed
  951. * to consider it maybe-reachable again.
  952. */
  953. STATIC void
  954. entry_guard_consider_retry(entry_guard_t *guard)
  955. {
  956. if (guard->is_reachable != GUARD_REACHABLE_NO)
  957. return; /* No retry needed. */
  958. const time_t now = approx_time();
  959. const unsigned delay =
  960. get_retry_schedule(guard->failing_since, now, guard->is_primary);
  961. const time_t last_attempt = guard->last_tried_to_connect;
  962. if (BUG(last_attempt == 0) ||
  963. now >= last_attempt + delay) {
  964. /* We should mark this retriable. */
  965. char tbuf[ISO_TIME_LEN+1];
  966. format_local_iso_time(tbuf, last_attempt);
  967. log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
  968. "haven't tried to use it since %s.",
  969. guard->is_primary?"primary ":"",
  970. guard->confirmed_idx>=0?"confirmed ":"",
  971. entry_guard_describe(guard),
  972. tbuf);
  973. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  974. if (guard->is_filtered_guard)
  975. guard->is_usable_filtered_guard = 1;
  976. }
  977. }
  978. /** Tell the entry guards subsystem that we have confirmed that as of
  979. * just now, we're on the internet. */
  980. void
  981. entry_guards_note_internet_connectivity(guard_selection_t *gs)
  982. {
  983. gs->last_time_on_internet = approx_time();
  984. }
  985. /**
  986. * Get a guard for use with a circuit. Prefer to pick a running primary
  987. * guard; then a non-pending running filtered confirmed guard; then a
  988. * non-pending runnable filtered guard. Update the
  989. * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
  990. * guard as appropriate. Set <b>state_out</b> to the new guard-state
  991. * of the circuit.
  992. */
  993. STATIC entry_guard_t *
  994. select_entry_guard_for_circuit(guard_selection_t *gs, unsigned *state_out)
  995. {
  996. tor_assert(gs);
  997. tor_assert(state_out);
  998. if (!gs->primary_guards_up_to_date)
  999. entry_guards_update_primary(gs);
  1000. /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
  1001. <maybe> or <yes>, return the first such guard." */
  1002. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1003. entry_guard_consider_retry(guard);
  1004. if (guard->is_reachable != GUARD_REACHABLE_NO) {
  1005. *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
  1006. guard->last_tried_to_connect = approx_time();
  1007. log_info(LD_GUARD, "Selected primary guard %s for circuit.",
  1008. entry_guard_describe(guard));
  1009. return guard;
  1010. }
  1011. } SMARTLIST_FOREACH_END(guard);
  1012. /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
  1013. and {USABLE_FILTERED_GUARDS} is nonempty, return the first
  1014. entry in that intersection that has {is_pending} set to
  1015. false." */
  1016. SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
  1017. if (guard->is_primary)
  1018. continue; /* we already considered this one. */
  1019. entry_guard_consider_retry(guard);
  1020. if (guard->is_usable_filtered_guard && ! guard->is_pending) {
  1021. guard->is_pending = 1;
  1022. guard->last_tried_to_connect = approx_time();
  1023. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1024. log_info(LD_GUARD, "No primary guards available. Selected confirmed "
  1025. "guard %s for circuit. Will try other guards before using "
  1026. "this circuit.",
  1027. entry_guard_describe(guard));
  1028. return guard;
  1029. }
  1030. } SMARTLIST_FOREACH_END(guard);
  1031. /* "Otherwise, if there is no such entry, select a member at
  1032. random from {USABLE_FILTERED_GUARDS}." */
  1033. {
  1034. entry_guard_t *guard;
  1035. guard = sample_reachable_filtered_entry_guards(gs,
  1036. SAMPLE_EXCLUDE_CONFIRMED |
  1037. SAMPLE_EXCLUDE_PRIMARY |
  1038. SAMPLE_EXCLUDE_PENDING);
  1039. if (guard == NULL) {
  1040. log_info(LD_GUARD, "Absolutely no sampled guards were available.");
  1041. return NULL;
  1042. }
  1043. guard->is_pending = 1;
  1044. guard->last_tried_to_connect = approx_time();
  1045. *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  1046. log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
  1047. "random guard %s for circuit. Will try other guards before "
  1048. "using this circuit.",
  1049. entry_guard_describe(guard));
  1050. return guard;
  1051. }
  1052. }
  1053. /**
  1054. * Note that we failed to connect to or build circuits through <b>guard</b>.
  1055. * Use with a guard returned by select_entry_guards_for_circuit().
  1056. */
  1057. STATIC void
  1058. entry_guards_note_guard_failure(guard_selection_t *gs,
  1059. entry_guard_t *guard)
  1060. {
  1061. tor_assert(gs);
  1062. guard->is_reachable = GUARD_REACHABLE_NO;
  1063. guard->is_usable_filtered_guard = 0;
  1064. guard->is_pending = 0;
  1065. if (guard->failing_since == 0)
  1066. guard->failing_since = approx_time();
  1067. log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
  1068. guard->is_primary?"primary ":"",
  1069. guard->confirmed_idx>=0?"confirmed ":"",
  1070. entry_guard_describe(guard));
  1071. }
  1072. /**
  1073. * Called when the network comes up after having seemed to be down for
  1074. * a while: Mark the primary guards as maybe-reachable so that we'll
  1075. * try them again.
  1076. */
  1077. STATIC void
  1078. mark_primary_guards_maybe_reachable(guard_selection_t *gs)
  1079. {
  1080. if (!gs->primary_guards_up_to_date)
  1081. entry_guards_update_primary(gs);
  1082. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1083. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1084. continue;
  1085. /* Note that we do not clear failing_since: this guard is now only
  1086. * _maybe-reachable_. */
  1087. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  1088. if (guard->is_filtered_guard)
  1089. guard->is_usable_filtered_guard = 1;
  1090. } SMARTLIST_FOREACH_END(guard);
  1091. }
  1092. /**
  1093. * Note that we successfully connected to, and built a circuit through
  1094. * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
  1095. * return the new guard-state of the circuit.
  1096. *
  1097. * Be aware: the circuit is only usable when its guard-state becomes
  1098. * GUARD_CIRC_STATE_COMPLETE.
  1099. **/
  1100. STATIC unsigned
  1101. entry_guards_note_guard_success(guard_selection_t *gs,
  1102. entry_guard_t *guard,
  1103. unsigned old_state)
  1104. {
  1105. tor_assert(gs);
  1106. /* Save this, since we're about to overwrite it. */
  1107. const time_t last_time_on_internet = gs->last_time_on_internet;
  1108. gs->last_time_on_internet = approx_time();
  1109. guard->is_reachable = GUARD_REACHABLE_YES;
  1110. guard->failing_since = 0;
  1111. guard->is_pending = 0;
  1112. if (guard->is_filtered_guard)
  1113. guard->is_usable_filtered_guard = 1;
  1114. if (guard->confirmed_idx < 0) {
  1115. make_guard_confirmed(gs, guard);
  1116. }
  1117. unsigned new_state;
  1118. if (old_state == GUARD_CIRC_STATE_USABLE_ON_COMPLETION) {
  1119. new_state = GUARD_CIRC_STATE_COMPLETE;
  1120. } else {
  1121. tor_assert_nonfatal(
  1122. old_state == GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
  1123. new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
  1124. if (last_time_on_internet + INTERNET_LIKELY_DOWN_INTERVAL
  1125. < approx_time()) {
  1126. mark_primary_guards_maybe_reachable(gs);
  1127. }
  1128. }
  1129. log_info(LD_GUARD, "Recorded success for %s%sguard %s",
  1130. guard->is_primary?"primary ":"",
  1131. guard->confirmed_idx>=0?"confirmed ":"",
  1132. entry_guard_describe(guard));
  1133. return new_state;
  1134. }
  1135. /**
  1136. * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
  1137. */
  1138. STATIC int
  1139. entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
  1140. {
  1141. tor_assert(a && b);
  1142. if (a == b)
  1143. return 0;
  1144. /* Confirmed is always better than unconfirmed; lower index better
  1145. than higher */
  1146. if (a->confirmed_idx < 0) {
  1147. if (b->confirmed_idx >= 0)
  1148. return 0;
  1149. } else {
  1150. if (b->confirmed_idx < 0)
  1151. return 1;
  1152. /* Lower confirmed_idx is better than higher. */
  1153. return (a->confirmed_idx < b->confirmed_idx);
  1154. }
  1155. /* If we reach this point, both are unconfirmed. If one is pending, it
  1156. * has higher priority. */
  1157. if (a->is_pending) {
  1158. if (! b->is_pending)
  1159. return 1;
  1160. /* Both are pending: earlier last_tried_connect wins. */
  1161. return a->last_tried_to_connect < b->last_tried_to_connect;
  1162. } else {
  1163. if (b->is_pending)
  1164. return 0;
  1165. /* Neither is pending: priorities are equal. */
  1166. return 0; // XXXX prop271 return a tristate instead?
  1167. }
  1168. }
  1169. /**
  1170. * Release all storage held in <b>state</b>.
  1171. */
  1172. void
  1173. circuit_guard_state_free(circuit_guard_state_t *state)
  1174. {
  1175. /* XXXX prop271 -- do we want to inline this structure? */
  1176. if (!state)
  1177. return;
  1178. entry_guard_handle_free(state->guard);
  1179. tor_free(state);
  1180. }
  1181. /**
  1182. * Pick a suitable entry guard for a circuit in, and place that guard
  1183. * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
  1184. * state object that will record whether the circuit is ready to be used
  1185. * or not. Return 0 on success; on failure, return -1.
  1186. */
  1187. int
  1188. entry_guard_pick_for_circuit(guard_selection_t *gs,
  1189. const node_t **chosen_node_out,
  1190. circuit_guard_state_t **guard_state_out)
  1191. {
  1192. tor_assert(gs);
  1193. tor_assert(chosen_node_out);
  1194. tor_assert(guard_state_out);
  1195. *chosen_node_out = NULL;
  1196. *guard_state_out = NULL;
  1197. unsigned state = 0;
  1198. entry_guard_t *guard = select_entry_guard_for_circuit(gs, &state);
  1199. if (! guard)
  1200. return -1;
  1201. if (BUG(state == 0))
  1202. return -1;
  1203. const node_t *node = node_get_by_id(guard->identity);
  1204. // XXXX prop271 check Ed ID.
  1205. if (! node)
  1206. return -1;
  1207. *chosen_node_out = node;
  1208. *guard_state_out = tor_malloc_zero(sizeof(circuit_guard_state_t));
  1209. (*guard_state_out)->guard = entry_guard_handle_new(guard);
  1210. (*guard_state_out)->state = state;
  1211. (*guard_state_out)->state_set_at = approx_time();
  1212. return 0;
  1213. }
  1214. /**
  1215. * Called by the circuit building module when a circuit has succeeded:
  1216. * informs the guards code that the guard in *<b>guard_state_p</b> is
  1217. * working, and advances the state of the guard module. On a -1 return
  1218. * value, the circuit is broken and should not be used. On a 1 return
  1219. * value, the circuit is ready to use. On a 0 return value, the circuit
  1220. * should not be used until we find out whether preferred guards will
  1221. * work for us.
  1222. *
  1223. * XXXXX prop271 tristates are ugly; reconsider that interface.
  1224. */
  1225. int
  1226. entry_guard_succeeded(guard_selection_t *gs,
  1227. circuit_guard_state_t **guard_state_p)
  1228. {
  1229. if (get_options()->UseDeprecatedGuardAlgorithm)
  1230. return 1;
  1231. if (BUG(*guard_state_p == NULL))
  1232. return -1;
  1233. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1234. if (! guard)
  1235. return -1;
  1236. unsigned newstate =
  1237. entry_guards_note_guard_success(gs, guard, (*guard_state_p)->state);
  1238. (*guard_state_p)->state = newstate;
  1239. (*guard_state_p)->state_set_at = approx_time();
  1240. if (newstate == GUARD_CIRC_STATE_COMPLETE) {
  1241. return 1;
  1242. } else {
  1243. return 0;
  1244. }
  1245. }
  1246. /** Cancel the selection of *<b>guard_state_p</b> without declaring
  1247. * success or failure. It is safe to call this function if success or
  1248. * failure _has_ already been declared. */
  1249. void
  1250. entry_guard_cancel(guard_selection_t *gs,
  1251. circuit_guard_state_t **guard_state_p)
  1252. {
  1253. (void) gs;
  1254. if (get_options()->UseDeprecatedGuardAlgorithm)
  1255. return;
  1256. if (BUG(*guard_state_p == NULL))
  1257. return;
  1258. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1259. if (! guard)
  1260. return;
  1261. /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
  1262. * function will only get called in "bug" cases anyway. */
  1263. guard->is_pending = 0;
  1264. circuit_guard_state_free(*guard_state_p);
  1265. *guard_state_p = NULL;
  1266. }
  1267. /**
  1268. * Called by the circuit building module when a circuit has succeeded:
  1269. * informs the guards code that the guard in *<b>guard_state_p</b> is
  1270. * not working, and advances the state of the guard module.
  1271. */
  1272. void
  1273. entry_guard_failed(guard_selection_t *gs,
  1274. circuit_guard_state_t **guard_state_p)
  1275. {
  1276. if (get_options()->UseDeprecatedGuardAlgorithm)
  1277. return;
  1278. if (BUG(*guard_state_p == NULL))
  1279. return;
  1280. entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  1281. if (! guard)
  1282. return;
  1283. entry_guards_note_guard_failure(gs, guard);
  1284. (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
  1285. (*guard_state_p)->state_set_at = approx_time();
  1286. }
  1287. /**
  1288. * Run the entry_guard_failed() function on every circuit that is
  1289. * pending on <b>chan</b>.
  1290. */
  1291. void
  1292. entry_guard_chan_failed(guard_selection_t *gs,
  1293. channel_t *chan)
  1294. {
  1295. tor_assert(gs);
  1296. if (!chan)
  1297. return;
  1298. if (get_options()->UseDeprecatedGuardAlgorithm)
  1299. return;
  1300. smartlist_t *pending = smartlist_new();
  1301. circuit_get_all_pending_on_channel(pending, chan);
  1302. SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
  1303. if (!CIRCUIT_IS_ORIGIN(circ))
  1304. continue;
  1305. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1306. entry_guard_failed(gs, &origin_circ->guard_state);
  1307. } SMARTLIST_FOREACH_END(circ);
  1308. smartlist_free(pending);
  1309. }
  1310. /**
  1311. * Return true iff every primary guard in <b>gs</b> is believed to
  1312. * be unreachable.
  1313. */
  1314. static int
  1315. entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
  1316. {
  1317. tor_assert(gs);
  1318. if (!gs->primary_guards_up_to_date)
  1319. entry_guards_update_primary(gs);
  1320. SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
  1321. entry_guard_consider_retry(guard);
  1322. if (guard->is_reachable != GUARD_REACHABLE_NO)
  1323. return 0;
  1324. } SMARTLIST_FOREACH_END(guard);
  1325. return 1;
  1326. }
  1327. /** Wrapper for entry_guard_has_higher_priority that compares the
  1328. * guard-priorities of a pair of circuits. */
  1329. static int
  1330. circ_state_has_higher_priority(origin_circuit_t *a,
  1331. origin_circuit_t *b)
  1332. {
  1333. circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
  1334. circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);
  1335. tor_assert(state_a);
  1336. tor_assert(state_b);
  1337. entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
  1338. entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);
  1339. if (! guard_a) {
  1340. /* Unknown guard -- never higher priority. */
  1341. return 0;
  1342. } else if (! guard_b) {
  1343. /* Known guard -- higher priority than any unknown guard. */
  1344. return 1;
  1345. } else {
  1346. /* Both known -- compare.*/
  1347. return entry_guard_has_higher_priority(guard_a, guard_b);
  1348. }
  1349. }
  1350. /**
  1351. * Look at all of the origin_circuit_t * objects in <b>all_circuits</b>,
  1352. * and see if any of them that were previously not ready to use for
  1353. * guard-related reasons are now ready to use. Place those circuits
  1354. * in <b>newly_complete_out</b>, and mark them COMPLETE.
  1355. *
  1356. * Return 1 if we upgraded any circuits, and 0 otherwise.
  1357. */
  1358. int
  1359. entry_guards_upgrade_waiting_circuits(guard_selection_t *gs,
  1360. const smartlist_t *all_circuits,
  1361. smartlist_t *newly_complete_out)
  1362. {
  1363. tor_assert(gs);
  1364. tor_assert(all_circuits);
  1365. tor_assert(newly_complete_out);
  1366. if (! entry_guards_all_primary_guards_are_down(gs)) {
  1367. /* We only upgrade a waiting circuit if the primary guards are all
  1368. * down. */
  1369. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  1370. "but not all primary guards were definitely down.");
  1371. return 0;
  1372. }
  1373. int n_waiting = 0;
  1374. int n_complete = 0;
  1375. origin_circuit_t *best_waiting_circuit = NULL;
  1376. origin_circuit_t *best_complete_circuit = NULL;
  1377. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  1378. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  1379. if (state == NULL)
  1380. continue;
  1381. if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
  1382. ++n_waiting;
  1383. if (! best_waiting_circuit ||
  1384. circ_state_has_higher_priority(circ, best_waiting_circuit)) {
  1385. best_waiting_circuit = circ;
  1386. }
  1387. } else if (state->state == GUARD_CIRC_STATE_COMPLETE) {
  1388. ++n_complete;
  1389. if (! best_complete_circuit ||
  1390. circ_state_has_higher_priority(circ, best_complete_circuit)) {
  1391. best_complete_circuit = circ;
  1392. }
  1393. }
  1394. } SMARTLIST_FOREACH_END(circ);
  1395. if (! best_waiting_circuit) {
  1396. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
  1397. "but didn't find any.");
  1398. return 0;
  1399. }
  1400. if (best_complete_circuit) {
  1401. if (circ_state_has_higher_priority(best_complete_circuit,
  1402. best_waiting_circuit)) {
  1403. /* "If any circuit is <complete>, then do not use any
  1404. <waiting_for_better_guard> or <usable_if_no_better_guard> circuits
  1405. circuits whose guards have lower priority." */
  1406. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  1407. "%d complete and %d guard-stalled. At least one complete "
  1408. "circuit had higher priority, so not upgrading.",
  1409. n_complete, n_waiting);
  1410. /* XXXX prop271 implement: "(Time them out after a
  1411. {NONPRIMARY_GUARD_IDLE_TIMEOUT} seconds.)"
  1412. */
  1413. return 0;
  1414. }
  1415. }
  1416. /* "If any circuit is <waiting_for_better_guard>, and every currently
  1417. {is_pending} circuit whose guard has higher priority has been in
  1418. state <usable_if_no_better_guard> for at least
  1419. {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds, and all primary guards
  1420. have reachable status of <no>, then call that circuit <complete>."
  1421. XXXX --- prop271 deviation. there's no such thing in the spec as
  1422. an {is_pending circuit}; fix the spec.
  1423. */
  1424. int n_blockers_found = 0;
  1425. const time_t state_set_at_cutoff =
  1426. approx_time() - NONPRIMARY_GUARD_CONNECT_TIMEOUT;
  1427. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  1428. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  1429. if (state == NULL)
  1430. continue;
  1431. if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
  1432. continue;
  1433. if (state->state_set_at > state_set_at_cutoff &&
  1434. circ_state_has_higher_priority(circ, best_waiting_circuit))
  1435. ++n_blockers_found;
  1436. } SMARTLIST_FOREACH_END(circ);
  1437. if (n_blockers_found) {
  1438. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  1439. "%d guard-stalled, but %d pending circuit(s) had higher "
  1440. "guard priority, so not upgrading.",
  1441. n_waiting, n_blockers_found);
  1442. return 0;
  1443. }
  1444. /* Okay. We have a best waiting circuit, and we aren't waiting for
  1445. anything better. Add all circuits with that priority to the
  1446. list, and call them COMPLETE. */
  1447. int n_succeeded = 0;
  1448. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  1449. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  1450. if (state == NULL)
  1451. continue;
  1452. if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
  1453. continue;
  1454. if (circ_state_has_higher_priority(best_waiting_circuit, circ))
  1455. continue;
  1456. state->state = GUARD_CIRC_STATE_COMPLETE;
  1457. state->state_set_at = approx_time();
  1458. smartlist_add(newly_complete_out, circ);
  1459. ++n_succeeded;
  1460. } SMARTLIST_FOREACH_END(circ);
  1461. log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  1462. "%d guard-stalled, %d complete. %d of the guard-stalled "
  1463. "circuit(s) had high enough priority to upgrade.",
  1464. n_waiting, n_complete, n_succeeded);
  1465. tor_assert_nonfatal(n_succeeded >= 1);
  1466. return 1;
  1467. }
  1468. /**
  1469. * Update all derived pieces of the guard selection state in <b>gs</b>.
  1470. * Return true iff we should stop using all previously generated circuits.
  1471. */
  1472. int
  1473. entry_guards_update_all(guard_selection_t *gs)
  1474. {
  1475. sampled_guards_update_from_consensus(gs);
  1476. entry_guards_update_filtered_sets(gs);
  1477. entry_guards_update_confirmed(gs);
  1478. entry_guards_update_primary(gs);
  1479. return 0;
  1480. }
  1481. /**
  1482. * Return a newly allocated string for encoding the persistent parts of
  1483. * <b>guard</b> to the state file.
  1484. */
  1485. STATIC char *
  1486. entry_guard_encode_for_state(entry_guard_t *guard)
  1487. {
  1488. /*
  1489. * The meta-format we use is K=V K=V K=V... where K can be any
  1490. * characters excepts space and =, and V can be any characters except
  1491. * space. The order of entries is not allowed to matter.
  1492. * Unrecognized K=V entries are persisted; recognized but erroneous
  1493. * entries are corrected.
  1494. */
  1495. smartlist_t *result = smartlist_new();
  1496. char tbuf[ISO_TIME_LEN+1];
  1497. tor_assert(guard);
  1498. smartlist_add_asprintf(result, "in=%s", guard->selection_name);
  1499. smartlist_add_asprintf(result, "rsa_id=%s",
  1500. hex_str(guard->identity, DIGEST_LEN));
  1501. if (strlen(guard->nickname)) {
  1502. smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
  1503. }
  1504. format_iso_time_nospace(tbuf, guard->sampled_on_date);
  1505. smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
  1506. if (guard->sampled_by_version) {
  1507. smartlist_add_asprintf(result, "sampled_by=%s",
  1508. guard->sampled_by_version);
  1509. }
  1510. if (guard->unlisted_since_date > 0) {
  1511. format_iso_time_nospace(tbuf, guard->unlisted_since_date);
  1512. smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
  1513. }
  1514. smartlist_add_asprintf(result, "listed=%d",
  1515. (int)guard->currently_listed);
  1516. if (guard->confirmed_idx >= 0) {
  1517. format_iso_time_nospace(tbuf, guard->confirmed_on_date);
  1518. smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
  1519. smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
  1520. }
  1521. const double EPSILON = 1.0e-6;
  1522. /* Make a copy of the pathbias object, since we will want to update
  1523. some of them */
  1524. guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
  1525. pb->use_successes = pathbias_get_use_success_count(guard);
  1526. pb->successful_circuits_closed = pathbias_get_close_success_count(guard);
  1527. #define PB_FIELD(field) do { \
  1528. if (pb->field >= EPSILON) { \
  1529. smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
  1530. } \
  1531. } while (0)
  1532. PB_FIELD(use_attempts);
  1533. PB_FIELD(use_successes);
  1534. PB_FIELD(circ_attempts);
  1535. PB_FIELD(circ_successes);
  1536. PB_FIELD(successful_circuits_closed);
  1537. PB_FIELD(collapsed_circuits);
  1538. PB_FIELD(unusable_circuits);
  1539. PB_FIELD(timeouts);
  1540. tor_free(pb);
  1541. #undef PB_FIELD
  1542. if (guard->extra_state_fields)
  1543. smartlist_add_strdup(result, guard->extra_state_fields);
  1544. char *joined = smartlist_join_strings(result, " ", 0, NULL);
  1545. SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
  1546. smartlist_free(result);
  1547. return joined;
  1548. }
  1549. /**
  1550. * Given a string generated by entry_guard_encode_for_state(), parse it
  1551. * (if possible) and return an entry_guard_t object for it. Return NULL
  1552. * on complete failure.
  1553. */
  1554. STATIC entry_guard_t *
  1555. entry_guard_parse_from_state(const char *s)
  1556. {
  1557. /* Unrecognized entries get put in here. */
  1558. smartlist_t *extra = smartlist_new();
  1559. /* These fields get parsed from the string. */
  1560. char *in = NULL;
  1561. char *rsa_id = NULL;
  1562. char *nickname = NULL;
  1563. char *sampled_on = NULL;
  1564. char *sampled_by = NULL;
  1565. char *unlisted_since = NULL;
  1566. char *listed = NULL;
  1567. char *confirmed_on = NULL;
  1568. char *confirmed_idx = NULL;
  1569. // pathbias
  1570. char *pb_use_attempts = NULL;
  1571. char *pb_use_successes = NULL;
  1572. char *pb_circ_attempts = NULL;
  1573. char *pb_circ_successes = NULL;
  1574. char *pb_successful_circuits_closed = NULL;
  1575. char *pb_collapsed_circuits = NULL;
  1576. char *pb_unusable_circuits = NULL;
  1577. char *pb_timeouts = NULL;
  1578. /* Split up the entries. Put the ones we know about in strings and the
  1579. * rest in "extra". */
  1580. {
  1581. smartlist_t *entries = smartlist_new();
  1582. strmap_t *vals = strmap_new(); // Maps keyword to location
  1583. #define FIELD(f) \
  1584. strmap_set(vals, #f, &f);
  1585. FIELD(in);
  1586. FIELD(rsa_id);
  1587. FIELD(nickname);
  1588. FIELD(sampled_on);
  1589. FIELD(sampled_by);
  1590. FIELD(unlisted_since);
  1591. FIELD(listed);
  1592. FIELD(confirmed_on);
  1593. FIELD(confirmed_idx);
  1594. FIELD(pb_use_attempts);
  1595. FIELD(pb_use_successes);
  1596. FIELD(pb_circ_attempts);
  1597. FIELD(pb_circ_successes);
  1598. FIELD(pb_successful_circuits_closed);
  1599. FIELD(pb_collapsed_circuits);
  1600. FIELD(pb_unusable_circuits);
  1601. FIELD(pb_timeouts);
  1602. #undef FIELD
  1603. smartlist_split_string(entries, s, " ",
  1604. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1605. SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
  1606. const char *eq = strchr(entry, '=');
  1607. if (!eq) {
  1608. smartlist_add(extra, entry);
  1609. continue;
  1610. }
  1611. char *key = tor_strndup(entry, eq-entry);
  1612. char **target = strmap_get(vals, key);
  1613. if (target == NULL || *target != NULL) {
  1614. /* unrecognized or already set */
  1615. smartlist_add(extra, entry);
  1616. tor_free(key);
  1617. continue;
  1618. }
  1619. *target = tor_strdup(eq+1);
  1620. tor_free(key);
  1621. tor_free(entry);
  1622. } SMARTLIST_FOREACH_END(entry);
  1623. smartlist_free(entries);
  1624. strmap_free(vals, NULL);
  1625. }
  1626. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  1627. if (in == NULL) {
  1628. log_warn(LD_CIRC, "Guard missing 'in' field");
  1629. goto err;
  1630. }
  1631. guard->selection_name = in;
  1632. in = NULL;
  1633. if (rsa_id == NULL) {
  1634. log_warn(LD_CIRC, "Guard missing RSA ID field");
  1635. goto err;
  1636. }
  1637. /* Process the identity and nickname. */
  1638. if (base16_decode(guard->identity, sizeof(guard->identity),
  1639. rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
  1640. log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
  1641. goto err;
  1642. }
  1643. if (nickname) {
  1644. strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  1645. } else {
  1646. guard->nickname[0]='$';
  1647. base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
  1648. guard->identity, DIGEST_LEN);
  1649. }
  1650. /* Process the various time fields. */
  1651. #define HANDLE_TIME(field) do { \
  1652. if (field) { \
  1653. int r = parse_iso_time_nospace(field, &field ## _time); \
  1654. if (r < 0) { \
  1655. log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
  1656. #field, escaped(field)); \
  1657. field##_time = -1; \
  1658. } \
  1659. } \
  1660. } while (0)
  1661. time_t sampled_on_time = 0;
  1662. time_t unlisted_since_time = 0;
  1663. time_t confirmed_on_time = 0;
  1664. HANDLE_TIME(sampled_on);
  1665. HANDLE_TIME(unlisted_since);
  1666. HANDLE_TIME(confirmed_on);
  1667. if (sampled_on_time <= 0)
  1668. sampled_on_time = approx_time();
  1669. if (unlisted_since_time < 0)
  1670. unlisted_since_time = 0;
  1671. if (confirmed_on_time < 0)
  1672. confirmed_on_time = 0;
  1673. #undef HANDLE_TIME
  1674. guard->sampled_on_date = sampled_on_time;
  1675. guard->unlisted_since_date = unlisted_since_time;
  1676. guard->confirmed_on_date = confirmed_on_time;
  1677. /* Take sampled_by_version verbatim. */
  1678. guard->sampled_by_version = sampled_by;
  1679. sampled_by = NULL; /* prevent free */
  1680. // XXXX -- prop271 spec deviation -- we do not require sampled_by_version
  1681. /* Listed is a boolean */
  1682. if (listed && strcmp(listed, "0"))
  1683. guard->currently_listed = 1;
  1684. /* The index is a nonnegative integer. */
  1685. guard->confirmed_idx = -1;
  1686. if (confirmed_idx) {
  1687. int ok=1;
  1688. long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
  1689. if (! ok) {
  1690. log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
  1691. escaped(confirmed_idx));
  1692. } else {
  1693. guard->confirmed_idx = (int)idx;
  1694. }
  1695. }
  1696. /* Anything we didn't recognize gets crammed together */
  1697. if (smartlist_len(extra) > 0) {
  1698. guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
  1699. }
  1700. /* initialize non-persistent fields */
  1701. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  1702. #define PB_FIELD(field) \
  1703. do { \
  1704. if (pb_ ## field) { \
  1705. int ok = 1; \
  1706. double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
  1707. if (! ok) { \
  1708. log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
  1709. #field, pb_ ## field); \
  1710. } else { \
  1711. guard->pb.field = r; \
  1712. } \
  1713. } \
  1714. } while (0)
  1715. PB_FIELD(use_attempts);
  1716. PB_FIELD(use_successes);
  1717. PB_FIELD(circ_attempts);
  1718. PB_FIELD(circ_successes);
  1719. PB_FIELD(successful_circuits_closed);
  1720. PB_FIELD(collapsed_circuits);
  1721. PB_FIELD(unusable_circuits);
  1722. PB_FIELD(timeouts);
  1723. #undef PB_FIELD
  1724. pathbias_check_use_success_count(guard);
  1725. pathbias_check_close_success_count(guard);
  1726. /* We update everything on this guard later, after we've parsed
  1727. * everything. */
  1728. goto done;
  1729. err:
  1730. // only consider it an error if the guard state was totally unparseable.
  1731. entry_guard_free(guard);
  1732. guard = NULL;
  1733. done:
  1734. tor_free(in);
  1735. tor_free(rsa_id);
  1736. tor_free(nickname);
  1737. tor_free(sampled_on);
  1738. tor_free(sampled_by);
  1739. tor_free(unlisted_since);
  1740. tor_free(listed);
  1741. tor_free(confirmed_on);
  1742. tor_free(confirmed_idx);
  1743. tor_free(pb_use_attempts);
  1744. tor_free(pb_use_successes);
  1745. tor_free(pb_circ_attempts);
  1746. tor_free(pb_circ_successes);
  1747. tor_free(pb_successful_circuits_closed);
  1748. tor_free(pb_collapsed_circuits);
  1749. tor_free(pb_unusable_circuits);
  1750. tor_free(pb_timeouts);
  1751. SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
  1752. smartlist_free(extra);
  1753. return guard;
  1754. }
  1755. /**
  1756. * Replace the Guards entries in <b>state</b> with a list of all our
  1757. * non-legacy sampled guards.
  1758. */
  1759. static void
  1760. entry_guards_update_guards_in_state(or_state_t *state)
  1761. {
  1762. if (!guard_contexts)
  1763. return;
  1764. config_line_t *lines = NULL;
  1765. config_line_t **nextline = &lines;
  1766. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  1767. if (!strcmp(gs->name, "legacy"))
  1768. continue; /* This is encoded differently. */
  1769. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1770. *nextline = tor_malloc_zero(sizeof(config_line_t));
  1771. (*nextline)->key = tor_strdup("Guard");
  1772. (*nextline)->value = entry_guard_encode_for_state(guard);
  1773. nextline = &(*nextline)->next;
  1774. } SMARTLIST_FOREACH_END(guard);
  1775. } SMARTLIST_FOREACH_END(gs);
  1776. config_free_lines(state->Guard);
  1777. state->Guard = lines;
  1778. }
  1779. /**
  1780. * Replace our non-legacy sampled guards from the Guards entries in
  1781. * <b>state</b>. Return 0 on success, -1 on failure. (If <b>set</b> is
  1782. * true, replace nothing -- only check whether replacing would work.)
  1783. */
  1784. static int
  1785. entry_guards_load_guards_from_state(or_state_t *state, int set)
  1786. {
  1787. const config_line_t *line = state->Guard;
  1788. int n_errors = 0;
  1789. if (!guard_contexts)
  1790. guard_contexts = smartlist_new();
  1791. /* Wipe all our existing guard info. (we shouldn't have any, but
  1792. * let's be safe.) */
  1793. if (set) {
  1794. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  1795. if (!strcmp(gs->name, "legacy"))
  1796. continue;
  1797. guard_selection_free(gs);
  1798. if (curr_guard_context == gs)
  1799. curr_guard_context = NULL;
  1800. SMARTLIST_DEL_CURRENT(guard_contexts, gs);
  1801. } SMARTLIST_FOREACH_END(gs);
  1802. }
  1803. for ( ; line != NULL; line = line->next) {
  1804. entry_guard_t *guard = entry_guard_parse_from_state(line->value);
  1805. if (guard == NULL) {
  1806. ++n_errors;
  1807. continue;
  1808. }
  1809. tor_assert(guard->selection_name);
  1810. if (!strcmp(guard->selection_name, "legacy")) {
  1811. ++n_errors;
  1812. entry_guard_free(guard);
  1813. continue;
  1814. }
  1815. if (set) {
  1816. guard_selection_t *gs;
  1817. gs = get_guard_selection_by_name(guard->selection_name, 1);
  1818. tor_assert(gs);
  1819. smartlist_add(gs->sampled_entry_guards, guard);
  1820. } else {
  1821. entry_guard_free(guard);
  1822. }
  1823. }
  1824. if (set) {
  1825. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  1826. if (!strcmp(gs->name, "legacy"))
  1827. continue;
  1828. entry_guards_update_all(gs);
  1829. } SMARTLIST_FOREACH_END(gs);
  1830. }
  1831. return n_errors ? -1 : 0;
  1832. }
  1833. /* XXXXX ----------------------------------------------- */
  1834. /* XXXXX prop271 ----- end of new-for-prop271 code ----- */
  1835. /* XXXXX ----------------------------------------------- */
  1836. /**
  1837. * @name Constants for old (pre-prop271) guard selection algorithm.
  1838. */
  1839. /**@{*/
  1840. /* Default number of entry guards in the case where the NumEntryGuards
  1841. * consensus parameter is not set */
  1842. #define DEFAULT_N_GUARDS 1
  1843. /* Minimum and maximum number of entry guards (in case the NumEntryGuards
  1844. * consensus parameter is set). */
  1845. #define MIN_N_GUARDS 1
  1846. #define MAX_N_GUARDS 10
  1847. /** Largest amount that we'll backdate chosen_on_date */
  1848. #define CHOSEN_ON_DATE_SLOP (30*86400)
  1849. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  1850. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  1851. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  1852. /**}@*/
  1853. /**
  1854. * @name Networkstatus parameters for old (pre-prop271) guard selection
  1855. */
  1856. /**@}*/
  1857. /** Choose how many entry guards or directory guards we'll use. If
  1858. * <b>for_directory</b> is true, we return how many directory guards to
  1859. * use; else we return how many entry guards to use. */
  1860. STATIC int
  1861. decide_num_guards(const or_options_t *options, int for_directory)
  1862. {
  1863. if (for_directory) {
  1864. int answer;
  1865. if (options->NumDirectoryGuards != 0)
  1866. return options->NumDirectoryGuards;
  1867. answer = networkstatus_get_param(NULL, "NumDirectoryGuards", 0, 0, 10);
  1868. if (answer) /* non-zero means use the consensus value */
  1869. return answer;
  1870. }
  1871. if (options->NumEntryGuards)
  1872. return options->NumEntryGuards;
  1873. /* Use the value from the consensus, or 3 if no guidance. */
  1874. return networkstatus_get_param(NULL, "NumEntryGuards", DEFAULT_N_GUARDS,
  1875. MIN_N_GUARDS, MAX_N_GUARDS);
  1876. }
  1877. /** Check whether the entry guard <b>e</b> is usable, given the directory
  1878. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  1879. * configuration (in <b>options</b>). Set <b>e</b>->bad_since
  1880. * accordingly. Return true iff the entry guard's status changes.
  1881. *
  1882. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  1883. */
  1884. static int
  1885. entry_guard_set_status(entry_guard_t *e, const node_t *node,
  1886. time_t now, const or_options_t *options,
  1887. const char **reason)
  1888. {
  1889. char buf[HEX_DIGEST_LEN+1];
  1890. int changed = 0;
  1891. *reason = NULL;
  1892. /* Do we want to mark this guard as bad? */
  1893. if (!node)
  1894. *reason = "unlisted";
  1895. else if (!node->is_running)
  1896. *reason = "down";
  1897. else if (options->UseBridges && (!node->ri ||
  1898. node->ri->purpose != ROUTER_PURPOSE_BRIDGE))
  1899. *reason = "not a bridge";
  1900. else if (options->UseBridges && !node_is_a_configured_bridge(node))
  1901. *reason = "not a configured bridge";
  1902. else if (!options->UseBridges && !node->is_possible_guard &&
  1903. !routerset_contains_node(options->EntryNodes,node))
  1904. *reason = "not recommended as a guard";
  1905. else if (routerset_contains_node(options->ExcludeNodes, node))
  1906. *reason = "excluded";
  1907. /* We only care about OR connection connectivity for entry guards. */
  1908. else if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
  1909. *reason = "unreachable by config";
  1910. else if (e->pb.path_bias_disabled)
  1911. *reason = "path-biased";
  1912. if (*reason && ! e->bad_since) {
  1913. /* Router is newly bad. */
  1914. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1915. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  1916. e->nickname, buf, *reason);
  1917. e->bad_since = now;
  1918. control_event_guard(e->nickname, e->identity, "BAD");
  1919. changed = 1;
  1920. } else if (!*reason && e->bad_since) {
  1921. /* There's nothing wrong with the router any more. */
  1922. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1923. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  1924. "marking as ok.", e->nickname, buf);
  1925. e->bad_since = 0;
  1926. control_event_guard(e->nickname, e->identity, "GOOD");
  1927. changed = 1;
  1928. }
  1929. if (node) {
  1930. int is_dir = node_is_dir(node);
  1931. if (options->UseBridges && node_is_a_configured_bridge(node))
  1932. is_dir = 1;
  1933. if (e->is_dir_cache != is_dir) {
  1934. e->is_dir_cache = is_dir;
  1935. changed = 1;
  1936. }
  1937. }
  1938. return changed;
  1939. }
  1940. /** Return true iff enough time has passed since we last tried to connect
  1941. * to the unreachable guard <b>e</b> that we're willing to try again. */
  1942. STATIC int
  1943. entry_is_time_to_retry(const entry_guard_t *e, time_t now)
  1944. {
  1945. struct guard_retry_period_s {
  1946. time_t period_duration;
  1947. time_t interval_during_period;
  1948. };
  1949. struct guard_retry_period_s periods[] = {
  1950. { 6*60*60, 60*60 }, /* For first 6 hrs., retry hourly; */
  1951. { 3*24*60*60, 4*60*60 }, /* Then retry every 4 hrs. until the
  1952. 3-day mark; */
  1953. { 7*24*60*60, 18*60*60 }, /* After 3 days, retry every 18 hours until
  1954. 1 week mark. */
  1955. { TIME_MAX, 36*60*60 } /* After 1 week, retry every 36 hours. */
  1956. };
  1957. time_t ith_deadline_for_retry;
  1958. time_t unreachable_for;
  1959. unsigned i;
  1960. if (e->last_attempted < e->unreachable_since)
  1961. return 1;
  1962. unreachable_for = now - e->unreachable_since;
  1963. for (i = 0; i < ARRAY_LENGTH(periods); i++) {
  1964. if (unreachable_for <= periods[i].period_duration) {
  1965. ith_deadline_for_retry = e->last_attempted +
  1966. periods[i].interval_during_period;
  1967. return (now > ith_deadline_for_retry);
  1968. }
  1969. }
  1970. return 0;
  1971. }
  1972. /** Return the node corresponding to <b>e</b>, if <b>e</b> is
  1973. * working well enough that we are willing to use it as an entry
  1974. * right now. (Else return NULL.) In particular, it must be
  1975. * - Listed as either up or never yet contacted;
  1976. * - Present in the routerlist;
  1977. * - Listed as 'stable' or 'fast' by the current dirserver consensus,
  1978. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
  1979. * (unless it's a configured EntryNode);
  1980. * - Allowed by our current ReachableORAddresses config option; and
  1981. * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
  1982. * is true).
  1983. *
  1984. * If the answer is no, set *<b>msg</b> to an explanation of why.
  1985. *
  1986. * If need_descriptor is true, only return the node if we currently have
  1987. * a descriptor (routerinfo or microdesc) for it.
  1988. */
  1989. STATIC const node_t *
  1990. entry_is_live(const entry_guard_t *e, entry_is_live_flags_t flags,
  1991. const char **msg)
  1992. {
  1993. const node_t *node;
  1994. const or_options_t *options = get_options();
  1995. int need_uptime = (flags & ENTRY_NEED_UPTIME) != 0;
  1996. int need_capacity = (flags & ENTRY_NEED_CAPACITY) != 0;
  1997. const int assume_reachable = (flags & ENTRY_ASSUME_REACHABLE) != 0;
  1998. const int need_descriptor = (flags & ENTRY_NEED_DESCRIPTOR) != 0;
  1999. tor_assert(msg);
  2000. if (e->pb.path_bias_disabled) {
  2001. *msg = "path-biased";
  2002. return NULL;
  2003. }
  2004. if (e->bad_since) {
  2005. *msg = "bad";
  2006. return NULL;
  2007. }
  2008. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  2009. if (!assume_reachable && !e->can_retry &&
  2010. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
  2011. *msg = "unreachable";
  2012. return NULL;
  2013. }
  2014. node = node_get_by_id(e->identity);
  2015. if (!node) {
  2016. *msg = "no node info";
  2017. return NULL;
  2018. }
  2019. if (need_descriptor && !node_has_descriptor(node)) {
  2020. *msg = "no descriptor";
  2021. return NULL;
  2022. }
  2023. if (get_options()->UseBridges) {
  2024. if (node_get_purpose(node) != ROUTER_PURPOSE_BRIDGE) {
  2025. *msg = "not a bridge";
  2026. return NULL;
  2027. }
  2028. if (!node_is_a_configured_bridge(node)) {
  2029. *msg = "not a configured bridge";
  2030. return NULL;
  2031. }
  2032. } else { /* !get_options()->UseBridges */
  2033. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  2034. *msg = "not general-purpose";
  2035. return NULL;
  2036. }
  2037. }
  2038. if (routerset_contains_node(options->EntryNodes, node)) {
  2039. /* they asked for it, they get it */
  2040. need_uptime = need_capacity = 0;
  2041. }
  2042. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  2043. *msg = "not fast/stable";
  2044. return NULL;
  2045. }
  2046. if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0)) {
  2047. *msg = "unreachable by config";
  2048. return NULL;
  2049. }
  2050. return node;
  2051. }
  2052. /** Return the number of entry guards that we think are usable, in the
  2053. * context of the given guard_selection_t */
  2054. int
  2055. num_live_entry_guards_for_guard_selection(guard_selection_t *gs,
  2056. int for_directory)
  2057. {
  2058. int n = 0;
  2059. const char *msg;
  2060. tor_assert(gs != NULL);
  2061. /* Set the entry node attributes we are interested in. */
  2062. entry_is_live_flags_t entry_flags = ENTRY_NEED_CAPACITY;
  2063. if (!for_directory) {
  2064. entry_flags |= ENTRY_NEED_DESCRIPTOR;
  2065. }
  2066. if (!(gs->chosen_entry_guards)) {
  2067. return 0;
  2068. }
  2069. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, entry) {
  2070. if (for_directory && !entry->is_dir_cache)
  2071. continue;
  2072. if (entry_is_live(entry, entry_flags, &msg))
  2073. ++n;
  2074. } SMARTLIST_FOREACH_END(entry);
  2075. return n;
  2076. }
  2077. /** Return the number of entry guards that we think are usable, for the
  2078. * default guard selection */
  2079. int
  2080. num_live_entry_guards(int for_directory)
  2081. {
  2082. return num_live_entry_guards_for_guard_selection(
  2083. get_guard_selection_info(), for_directory);
  2084. }
  2085. /** If <b>digest</b> matches the identity of any node in the
  2086. * entry_guards list for the provided guard selection state,
  2087. return that node. Else return NULL. */
  2088. entry_guard_t *
  2089. entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
  2090. const char *digest)
  2091. {
  2092. tor_assert(gs != NULL);
  2093. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry,
  2094. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  2095. return entry;
  2096. );
  2097. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, entry,
  2098. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  2099. return entry;
  2100. );
  2101. return NULL;
  2102. }
  2103. /** Return the node_t associated with a single entry_guard_t. May
  2104. * return NULL if the guard is not currently in the consensus. */
  2105. const node_t *
  2106. entry_guard_find_node(const entry_guard_t *guard)
  2107. {
  2108. tor_assert(guard);
  2109. return node_get_by_id(guard->identity);
  2110. }
  2111. /** If <b>digest</b> matches the identity of any node in the
  2112. * entry_guards list for the default guard selection state,
  2113. return that node. Else return NULL. */
  2114. entry_guard_t *
  2115. entry_guard_get_by_id_digest(const char *digest)
  2116. {
  2117. return entry_guard_get_by_id_digest_for_guard_selection(
  2118. get_guard_selection_info(), digest);
  2119. }
  2120. /** Dump a description of our list of entry guards in the given guard
  2121. * selection context to the log at level <b>severity</b>. */
  2122. static void
  2123. log_entry_guards_for_guard_selection(guard_selection_t *gs, int severity)
  2124. {
  2125. smartlist_t *elements = smartlist_new();
  2126. char *s;
  2127. /*
  2128. * TODO this should probably log more info about prop-271 state too
  2129. * when it's implemented.
  2130. */
  2131. tor_assert(gs != NULL);
  2132. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e)
  2133. {
  2134. const char *msg = NULL;
  2135. if (entry_is_live(e, ENTRY_NEED_CAPACITY, &msg))
  2136. smartlist_add_asprintf(elements, "%s [%s] (up %s)",
  2137. e->nickname,
  2138. hex_str(e->identity, DIGEST_LEN),
  2139. e->made_contact ? "made-contact" : "never-contacted");
  2140. else
  2141. smartlist_add_asprintf(elements, "%s [%s] (%s, %s)",
  2142. e->nickname,
  2143. hex_str(e->identity, DIGEST_LEN),
  2144. msg,
  2145. e->made_contact ? "made-contact" : "never-contacted");
  2146. }
  2147. SMARTLIST_FOREACH_END(e);
  2148. s = smartlist_join_strings(elements, ",", 0, NULL);
  2149. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  2150. smartlist_free(elements);
  2151. log_fn(severity,LD_CIRC,"%s",s);
  2152. tor_free(s);
  2153. }
  2154. /** Called when one or more guards that we would previously have used for some
  2155. * purpose are no longer in use because a higher-priority guard has become
  2156. * usable again. */
  2157. static void
  2158. control_event_guard_deferred(void)
  2159. {
  2160. /* XXXX We don't actually have a good way to figure out _how many_ entries
  2161. * are live for some purpose. We need an entry_is_even_slightly_live()
  2162. * function for this to work right. NumEntryGuards isn't reliable: if we
  2163. * need guards with weird properties, we can have more than that number
  2164. * live.
  2165. **/
  2166. #if 0
  2167. int n = 0;
  2168. const char *msg;
  2169. const or_options_t *options = get_options();
  2170. if (!entry_guards)
  2171. return;
  2172. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2173. {
  2174. if (entry_is_live(entry, 0, 1, 0, &msg)) {
  2175. if (n++ == options->NumEntryGuards) {
  2176. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  2177. return;
  2178. }
  2179. }
  2180. });
  2181. #endif
  2182. }
  2183. /** Add a new (preferably stable and fast) router to our chosen_entry_guards
  2184. * list for the supplied guard selection. Return a pointer to the router if
  2185. * we succeed, or NULL if we can't find any more suitable entries.
  2186. *
  2187. * If <b>chosen</b> is defined, use that one, and if it's not
  2188. * already in our entry_guards list, put it at the *beginning*.
  2189. * Else, put the one we pick at the end of the list. */
  2190. STATIC const node_t *
  2191. add_an_entry_guard(guard_selection_t *gs,
  2192. const node_t *chosen, int reset_status, int prepend,
  2193. int for_discovery, int for_directory)
  2194. {
  2195. const node_t *node;
  2196. entry_guard_t *entry;
  2197. tor_assert(gs != NULL);
  2198. tor_assert(gs->chosen_entry_guards != NULL);
  2199. if (chosen) {
  2200. node = chosen;
  2201. entry = entry_guard_get_by_id_digest_for_guard_selection(gs,
  2202. node->identity);
  2203. if (entry) {
  2204. if (reset_status) {
  2205. entry->bad_since = 0;
  2206. entry->can_retry = 1;
  2207. }
  2208. entry->is_dir_cache = node_is_dir(node);
  2209. if (get_options()->UseBridges && node_is_a_configured_bridge(node))
  2210. entry->is_dir_cache = 1;
  2211. return NULL;
  2212. }
  2213. } else if (!for_directory) {
  2214. node = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL, NULL);
  2215. if (!node)
  2216. return NULL;
  2217. } else {
  2218. const routerstatus_t *rs;
  2219. rs = router_pick_directory_server(MICRODESC_DIRINFO|V3_DIRINFO,
  2220. PDS_FOR_GUARD);
  2221. if (!rs)
  2222. return NULL;
  2223. node = node_get_by_id(rs->identity_digest);
  2224. if (!node)
  2225. return NULL;
  2226. }
  2227. if (entry_guard_get_by_id_digest_for_guard_selection(gs, node->identity)
  2228. != NULL) {
  2229. log_info(LD_CIRC, "I was about to add a duplicate entry guard.");
  2230. /* This can happen if we choose a guard, then the node goes away, then
  2231. * comes back. */
  2232. return NULL;
  2233. }
  2234. entry = tor_malloc_zero(sizeof(entry_guard_t));
  2235. log_info(LD_CIRC, "Chose %s as new entry guard.",
  2236. node_describe(node));
  2237. strlcpy(entry->nickname, node_get_nickname(node), sizeof(entry->nickname));
  2238. memcpy(entry->identity, node->identity, DIGEST_LEN);
  2239. entry->is_dir_cache = node_is_dir(node);
  2240. if (get_options()->UseBridges && node_is_a_configured_bridge(node))
  2241. entry->is_dir_cache = 1;
  2242. /* Choose expiry time smudged over the past month. The goal here
  2243. * is to a) spread out when Tor clients rotate their guards, so they
  2244. * don't all select them on the same day, and b) avoid leaving a
  2245. * precise timestamp in the state file about when we first picked
  2246. * this guard. For details, see the Jan 2010 or-dev thread. */
  2247. time_t now = time(NULL);
  2248. entry->chosen_on_date = crypto_rand_time_range(now - 3600*24*30, now);
  2249. entry->chosen_by_version = tor_strdup(VERSION);
  2250. /* Are we picking this guard because all of our current guards are
  2251. * down so we need another one (for_discovery is 1), or because we
  2252. * decided we need more variety in our guard list (for_discovery is 0)?
  2253. *
  2254. * Currently we hack this behavior into place by setting "made_contact"
  2255. * for guards of the latter variety, so we'll be willing to use any of
  2256. * them right off the bat.
  2257. */
  2258. if (!for_discovery)
  2259. entry->made_contact = 1;
  2260. if (prepend)
  2261. smartlist_insert(gs->chosen_entry_guards, 0, entry);
  2262. else
  2263. smartlist_add(gs->chosen_entry_guards, entry);
  2264. control_event_guard(entry->nickname, entry->identity, "NEW");
  2265. control_event_guard_deferred();
  2266. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2267. return node;
  2268. }
  2269. /** Entry point for bridges.c to add a bridge as guard.
  2270. *
  2271. * XXXX prop271 refactor.*/
  2272. void
  2273. add_bridge_as_entry_guard(guard_selection_t *gs,
  2274. const node_t *chosen)
  2275. {
  2276. add_an_entry_guard(gs, chosen, 1, 1, 0, 0);
  2277. }
  2278. /**
  2279. * Return the minimum lifetime of working entry guard, in seconds,
  2280. * as given in the consensus networkstatus. (Plus CHOSEN_ON_DATE_SLOP,
  2281. * so that we can do the chosen_on_date randomization while achieving the
  2282. * desired minimum lifetime.)
  2283. */
  2284. static int32_t
  2285. guards_get_lifetime(void)
  2286. {
  2287. const or_options_t *options = get_options();
  2288. #define DFLT_GUARD_LIFETIME (86400 * 60) /* Two months. */
  2289. #define MIN_GUARD_LIFETIME (86400 * 30) /* One months. */
  2290. #define MAX_GUARD_LIFETIME (86400 * 1826) /* Five years. */
  2291. if (options->GuardLifetime >= 1) {
  2292. return CLAMP(MIN_GUARD_LIFETIME,
  2293. options->GuardLifetime,
  2294. MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
  2295. }
  2296. return networkstatus_get_param(NULL, "GuardLifetime",
  2297. DFLT_GUARD_LIFETIME,
  2298. MIN_GUARD_LIFETIME,
  2299. MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
  2300. }
  2301. /** If the use of entry guards is configured, choose more entry guards
  2302. * until we have enough in the list. */
  2303. static void
  2304. pick_entry_guards(guard_selection_t *gs,
  2305. const or_options_t *options,
  2306. int for_directory)
  2307. {
  2308. int changed = 0;
  2309. const int num_needed = decide_num_guards(options, for_directory);
  2310. tor_assert(gs != NULL);
  2311. tor_assert(gs->chosen_entry_guards != NULL);
  2312. while (num_live_entry_guards_for_guard_selection(gs, for_directory)
  2313. < num_needed) {
  2314. if (!add_an_entry_guard(gs, NULL, 0, 0, 0, for_directory))
  2315. break;
  2316. changed = 1;
  2317. }
  2318. if (changed)
  2319. entry_guards_changed_for_guard_selection(gs);
  2320. }
  2321. /** Release all storage held by <b>e</b>. */
  2322. STATIC void
  2323. entry_guard_free(entry_guard_t *e)
  2324. {
  2325. if (!e)
  2326. return;
  2327. entry_guard_handles_clear(e);
  2328. tor_free(e->chosen_by_version);
  2329. tor_free(e->sampled_by_version);
  2330. tor_free(e->extra_state_fields);
  2331. tor_free(e->selection_name);
  2332. tor_free(e);
  2333. }
  2334. /** Remove from a guard selection context any entry guard which was selected
  2335. * by an unknown version of Tor, or which was selected by a version of Tor
  2336. * that's known to select entry guards badly, or which was selected more 2
  2337. * months ago. */
  2338. /* XXXX The "obsolete guards" and "chosen long ago guards" things should
  2339. * probably be different functions. */
  2340. static int
  2341. remove_obsolete_entry_guards(guard_selection_t *gs, time_t now)
  2342. {
  2343. int changed = 0, i;
  2344. int32_t guard_lifetime = guards_get_lifetime();
  2345. tor_assert(gs != NULL);
  2346. if (!(gs->chosen_entry_guards)) goto done;
  2347. for (i = 0; i < smartlist_len(gs->chosen_entry_guards); ++i) {
  2348. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, i);
  2349. const char *ver = entry->chosen_by_version;
  2350. const char *msg = NULL;
  2351. tor_version_t v;
  2352. int version_is_bad = 0, date_is_bad = 0;
  2353. if (!ver) {
  2354. msg = "does not say what version of Tor it was selected by";
  2355. version_is_bad = 1;
  2356. } else if (tor_version_parse(ver, &v)) {
  2357. msg = "does not seem to be from any recognized version of Tor";
  2358. version_is_bad = 1;
  2359. }
  2360. if (!version_is_bad && entry->chosen_on_date + guard_lifetime < now) {
  2361. /* It's been too long since the date listed in our state file. */
  2362. msg = "was selected several months ago";
  2363. date_is_bad = 1;
  2364. }
  2365. if (version_is_bad || date_is_bad) { /* we need to drop it */
  2366. char dbuf[HEX_DIGEST_LEN+1];
  2367. tor_assert(msg);
  2368. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2369. log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
  2370. "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
  2371. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  2372. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2373. entry_guard_free(entry);
  2374. smartlist_del_keeporder(gs->chosen_entry_guards, i--);
  2375. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2376. changed = 1;
  2377. }
  2378. }
  2379. done:
  2380. return changed ? 1 : 0;
  2381. }
  2382. /** Remove all entry guards from this guard selection context that have
  2383. * been down or unlisted for so long that we don't think they'll come up
  2384. * again. Return 1 if we removed any, or 0 if we did nothing. */
  2385. static int
  2386. remove_dead_entry_guards(guard_selection_t *gs, time_t now)
  2387. {
  2388. char dbuf[HEX_DIGEST_LEN+1];
  2389. char tbuf[ISO_TIME_LEN+1];
  2390. int i;
  2391. int changed = 0;
  2392. tor_assert(gs != NULL);
  2393. if (!(gs->chosen_entry_guards)) goto done;
  2394. for (i = 0; i < smartlist_len(gs->chosen_entry_guards); ) {
  2395. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, i);
  2396. if (entry->bad_since &&
  2397. ! entry->pb.path_bias_disabled &&
  2398. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  2399. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2400. format_local_iso_time(tbuf, entry->bad_since);
  2401. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  2402. "since %s local time; removing.",
  2403. entry->nickname, dbuf, tbuf);
  2404. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2405. entry_guard_free(entry);
  2406. smartlist_del_keeporder(gs->chosen_entry_guards, i);
  2407. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2408. changed = 1;
  2409. } else
  2410. ++i;
  2411. }
  2412. done:
  2413. return changed ? 1 : 0;
  2414. }
  2415. /** Remove all currently listed entry guards for a given guard selection
  2416. * context */
  2417. void
  2418. remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
  2419. {
  2420. char dbuf[HEX_DIGEST_LEN+1];
  2421. tor_assert(gs != NULL);
  2422. if (gs->chosen_entry_guards) {
  2423. while (smartlist_len(gs->chosen_entry_guards)) {
  2424. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, 0);
  2425. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2426. log_info(LD_CIRC, "Entry guard '%s' (%s) has been dropped.",
  2427. entry->nickname, dbuf);
  2428. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2429. entry_guard_free(entry);
  2430. smartlist_del(gs->chosen_entry_guards, 0);
  2431. }
  2432. }
  2433. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2434. entry_guards_changed_for_guard_selection(gs);
  2435. }
  2436. /** Remove all currently listed entry guards. So new ones will be chosen. */
  2437. void
  2438. remove_all_entry_guards(void)
  2439. {
  2440. remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
  2441. }
  2442. /** A new directory or router-status has arrived; update the down/listed
  2443. * status of the entry guards.
  2444. *
  2445. * An entry is 'down' if the directory lists it as nonrunning.
  2446. * An entry is 'unlisted' if the directory doesn't include it.
  2447. *
  2448. * Don't call this on startup; only on a fresh download. Otherwise we'll
  2449. * think that things are unlisted.
  2450. */
  2451. void
  2452. entry_guards_compute_status_for_guard_selection(guard_selection_t *gs,
  2453. const or_options_t *options,
  2454. time_t now)
  2455. {
  2456. int changed = 0;
  2457. digestmap_t *reasons;
  2458. if ((!gs) || !(gs->chosen_entry_guards))
  2459. return;
  2460. if (!get_options()->UseDeprecatedGuardAlgorithm)
  2461. return;
  2462. if (options->EntryNodes) /* reshuffle the entry guard list if needed */
  2463. entry_nodes_should_be_added();
  2464. reasons = digestmap_new();
  2465. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, entry)
  2466. {
  2467. const node_t *r = node_get_by_id(entry->identity);
  2468. const char *reason = NULL;
  2469. if (entry_guard_set_status(entry, r, now, options, &reason))
  2470. changed = 1;
  2471. if (entry->bad_since)
  2472. tor_assert(reason);
  2473. if (reason)
  2474. digestmap_set(reasons, entry->identity, (char*)reason);
  2475. }
  2476. SMARTLIST_FOREACH_END(entry);
  2477. if (remove_dead_entry_guards(gs, now))
  2478. changed = 1;
  2479. if (remove_obsolete_entry_guards(gs, now))
  2480. changed = 1;
  2481. if (changed) {
  2482. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *,
  2483. entry) {
  2484. const char *reason = digestmap_get(reasons, entry->identity);
  2485. const char *live_msg = "";
  2486. const node_t *r = entry_is_live(entry, ENTRY_NEED_CAPACITY, &live_msg);
  2487. log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
  2488. entry->nickname,
  2489. hex_str(entry->identity, DIGEST_LEN),
  2490. entry->unreachable_since ? "unreachable" : "reachable",
  2491. entry->bad_since ? "unusable" : "usable",
  2492. reason ? ", ": "",
  2493. reason ? reason : "",
  2494. r ? "live" : "not live / ",
  2495. r ? "" : live_msg);
  2496. } SMARTLIST_FOREACH_END(entry);
  2497. log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
  2498. num_live_entry_guards_for_guard_selection(gs, 0),
  2499. smartlist_len(gs->chosen_entry_guards));
  2500. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2501. entry_guards_changed_for_guard_selection(gs);
  2502. }
  2503. digestmap_free(reasons, NULL);
  2504. }
  2505. /** A new directory or router-status has arrived; update the down/listed
  2506. * status of the entry guards.
  2507. *
  2508. * An entry is 'down' if the directory lists it as nonrunning.
  2509. * An entry is 'unlisted' if the directory doesn't include it.
  2510. *
  2511. * Don't call this on startup; only on a fresh download. Otherwise we'll
  2512. * think that things are unlisted.
  2513. */
  2514. void
  2515. entry_guards_compute_status(const or_options_t *options, time_t now)
  2516. {
  2517. entry_guards_compute_status_for_guard_selection(get_guard_selection_info(),
  2518. options, now);
  2519. }
  2520. /** Called when a connection to an OR with the identity digest <b>digest</b>
  2521. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  2522. * If the OR is an entry, change that entry's up/down status.
  2523. * Return 0 normally, or -1 if we want to tear down the new connection.
  2524. *
  2525. * If <b>mark_relay_status</b>, also call router_set_status() on this
  2526. * relay.
  2527. */
  2528. /* XXX We could change succeeded and mark_relay_status into 'int flags'.
  2529. * Too many boolean arguments is a recipe for confusion.
  2530. */
  2531. int
  2532. entry_guard_register_connect_status_for_guard_selection(
  2533. guard_selection_t *gs, const char *digest, int succeeded,
  2534. int mark_relay_status, time_t now)
  2535. {
  2536. int changed = 0;
  2537. int refuse_conn = 0;
  2538. int first_contact = 0;
  2539. entry_guard_t *entry = NULL;
  2540. int idx = -1;
  2541. char buf[HEX_DIGEST_LEN+1];
  2542. if (!(gs) || !(gs->chosen_entry_guards)) {
  2543. return 0;
  2544. }
  2545. if (! get_options()->UseDeprecatedGuardAlgorithm) {
  2546. return 0;
  2547. }
  2548. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  2549. tor_assert(e);
  2550. if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
  2551. entry = e;
  2552. idx = e_sl_idx;
  2553. break;
  2554. }
  2555. } SMARTLIST_FOREACH_END(e);
  2556. if (!entry)
  2557. return 0;
  2558. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  2559. if (succeeded) {
  2560. if (entry->unreachable_since) {
  2561. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  2562. entry->nickname, buf);
  2563. entry->can_retry = 0;
  2564. entry->unreachable_since = 0;
  2565. entry->last_attempted = now;
  2566. control_event_guard(entry->nickname, entry->identity, "UP");
  2567. changed = 1;
  2568. }
  2569. if (!entry->made_contact) {
  2570. entry->made_contact = 1;
  2571. first_contact = changed = 1;
  2572. }
  2573. } else { /* ! succeeded */
  2574. if (!entry->made_contact) {
  2575. /* We've never connected to this one. */
  2576. log_info(LD_CIRC,
  2577. "Connection to never-contacted entry guard '%s' (%s) failed. "
  2578. "Removing from the list. %d/%d entry guards usable/new.",
  2579. entry->nickname, buf,
  2580. num_live_entry_guards_for_guard_selection(gs, 0) - 1,
  2581. smartlist_len(gs->chosen_entry_guards)-1);
  2582. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2583. entry_guard_free(entry);
  2584. smartlist_del_keeporder(gs->chosen_entry_guards, idx);
  2585. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2586. changed = 1;
  2587. } else if (!entry->unreachable_since) {
  2588. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  2589. "Marking as unreachable.", entry->nickname, buf);
  2590. entry->unreachable_since = entry->last_attempted = now;
  2591. control_event_guard(entry->nickname, entry->identity, "DOWN");
  2592. changed = 1;
  2593. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2594. } else {
  2595. char tbuf[ISO_TIME_LEN+1];
  2596. format_iso_time(tbuf, entry->unreachable_since);
  2597. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  2598. "'%s' (%s). It has been unreachable since %s.",
  2599. entry->nickname, buf, tbuf);
  2600. entry->last_attempted = now;
  2601. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2602. }
  2603. }
  2604. /* if the caller asked us to, also update the is_running flags for this
  2605. * relay */
  2606. if (mark_relay_status)
  2607. router_set_status(digest, succeeded);
  2608. if (first_contact) {
  2609. /* We've just added a new long-term entry guard. Perhaps the network just
  2610. * came back? We should give our earlier entries another try too,
  2611. * and close this connection so we don't use it before we've given
  2612. * the others a shot. */
  2613. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  2614. if (e == entry)
  2615. break;
  2616. if (e->made_contact) {
  2617. const char *msg;
  2618. const node_t *r = entry_is_live(e,
  2619. ENTRY_NEED_CAPACITY | ENTRY_ASSUME_REACHABLE,
  2620. &msg);
  2621. if (r && e->unreachable_since) {
  2622. refuse_conn = 1;
  2623. e->can_retry = 1;
  2624. }
  2625. }
  2626. } SMARTLIST_FOREACH_END(e);
  2627. if (refuse_conn) {
  2628. log_info(LD_CIRC,
  2629. "Connected to new entry guard '%s' (%s). Marking earlier "
  2630. "entry guards up. %d/%d entry guards usable/new.",
  2631. entry->nickname, buf,
  2632. num_live_entry_guards_for_guard_selection(gs, 0),
  2633. smartlist_len(gs->chosen_entry_guards));
  2634. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2635. changed = 1;
  2636. }
  2637. }
  2638. if (changed)
  2639. entry_guards_changed_for_guard_selection(gs);
  2640. return refuse_conn ? -1 : 0;
  2641. }
  2642. /** Called when a connection to an OR with the identity digest <b>digest</b>
  2643. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  2644. * If the OR is an entry, change that entry's up/down status in the default
  2645. * guard selection context.
  2646. * Return 0 normally, or -1 if we want to tear down the new connection.
  2647. *
  2648. * If <b>mark_relay_status</b>, also call router_set_status() on this
  2649. * relay.
  2650. */
  2651. int
  2652. entry_guard_register_connect_status(const char *digest, int succeeded,
  2653. int mark_relay_status, time_t now)
  2654. {
  2655. return entry_guard_register_connect_status_for_guard_selection(
  2656. get_guard_selection_info(), digest, succeeded, mark_relay_status, now);
  2657. }
  2658. /** Called when the value of EntryNodes changes in our configuration. */
  2659. void
  2660. entry_nodes_should_be_added_for_guard_selection(guard_selection_t *gs)
  2661. {
  2662. tor_assert(gs != NULL);
  2663. log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
  2664. "relays at the front of the entry guard list.");
  2665. gs->should_add_entry_nodes = 1;
  2666. }
  2667. /** Called when the value of EntryNodes changes in our configuration. */
  2668. void
  2669. entry_nodes_should_be_added(void)
  2670. {
  2671. entry_nodes_should_be_added_for_guard_selection(
  2672. get_guard_selection_info());
  2673. }
  2674. /** Adjust the entry guards list so that it only contains entries from
  2675. * EntryNodes, adding new entries from EntryNodes to the list as needed. */
  2676. STATIC void
  2677. entry_guards_set_from_config(guard_selection_t *gs,
  2678. const or_options_t *options)
  2679. {
  2680. smartlist_t *entry_nodes, *worse_entry_nodes, *entry_fps;
  2681. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  2682. const int numentryguards = decide_num_guards(options, 0);
  2683. tor_assert(gs != NULL);
  2684. tor_assert(gs->chosen_entry_guards != NULL);
  2685. gs->should_add_entry_nodes = 0;
  2686. if (!options->EntryNodes) {
  2687. /* It's possible that a controller set EntryNodes, thus making
  2688. * should_add_entry_nodes set, then cleared it again, all before the
  2689. * call to choose_random_entry() that triggered us. If so, just return.
  2690. */
  2691. return;
  2692. }
  2693. {
  2694. char *string = routerset_to_string(options->EntryNodes);
  2695. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
  2696. tor_free(string);
  2697. }
  2698. entry_nodes = smartlist_new();
  2699. worse_entry_nodes = smartlist_new();
  2700. entry_fps = smartlist_new();
  2701. old_entry_guards_on_list = smartlist_new();
  2702. old_entry_guards_not_on_list = smartlist_new();
  2703. /* Split entry guards into those on the list and those not. */
  2704. routerset_get_all_nodes(entry_nodes, options->EntryNodes,
  2705. options->ExcludeNodes, 0);
  2706. SMARTLIST_FOREACH(entry_nodes, const node_t *,node,
  2707. smartlist_add(entry_fps, (void*)node->identity));
  2708. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e, {
  2709. if (smartlist_contains_digest(entry_fps, e->identity))
  2710. smartlist_add(old_entry_guards_on_list, e);
  2711. else
  2712. smartlist_add(old_entry_guards_not_on_list, e);
  2713. });
  2714. /* Remove all currently configured guard nodes, excluded nodes, unreachable
  2715. * nodes, or non-Guard nodes from entry_nodes. */
  2716. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  2717. if (entry_guard_get_by_id_digest_for_guard_selection(gs,
  2718. node->identity)) {
  2719. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  2720. continue;
  2721. } else if (routerset_contains_node(options->ExcludeNodes, node)) {
  2722. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  2723. continue;
  2724. } else if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION,
  2725. 0)) {
  2726. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  2727. continue;
  2728. } else if (! node->is_possible_guard) {
  2729. smartlist_add(worse_entry_nodes, (node_t*)node);
  2730. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  2731. }
  2732. } SMARTLIST_FOREACH_END(node);
  2733. /* Now build the new entry_guards list. */
  2734. smartlist_clear(gs->chosen_entry_guards);
  2735. /* First, the previously configured guards that are in EntryNodes. */
  2736. smartlist_add_all(gs->chosen_entry_guards, old_entry_guards_on_list);
  2737. /* Next, scramble the rest of EntryNodes, putting the guards first. */
  2738. smartlist_shuffle(entry_nodes);
  2739. smartlist_shuffle(worse_entry_nodes);
  2740. smartlist_add_all(entry_nodes, worse_entry_nodes);
  2741. /* Next, the rest of EntryNodes */
  2742. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  2743. add_an_entry_guard(gs, node, 0, 0, 1, 0);
  2744. if (smartlist_len(gs->chosen_entry_guards) > numentryguards * 10)
  2745. break;
  2746. } SMARTLIST_FOREACH_END(node);
  2747. log_notice(LD_GENERAL, "%d entries in guards",
  2748. smartlist_len(gs->chosen_entry_guards));
  2749. /* Finally, free the remaining previously configured guards that are not in
  2750. * EntryNodes. */
  2751. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  2752. entry_guard_free(e));
  2753. smartlist_free(entry_nodes);
  2754. smartlist_free(worse_entry_nodes);
  2755. smartlist_free(entry_fps);
  2756. smartlist_free(old_entry_guards_on_list);
  2757. smartlist_free(old_entry_guards_not_on_list);
  2758. entry_guards_changed_for_guard_selection(gs);
  2759. }
  2760. /** Return 0 if we're fine adding arbitrary routers out of the
  2761. * directory to our entry guard list, or return 1 if we have a
  2762. * list already and we must stick to it.
  2763. */
  2764. int
  2765. entry_list_is_constrained(const or_options_t *options)
  2766. {
  2767. if (options->EntryNodes)
  2768. return 1;
  2769. if (options->UseBridges)
  2770. return 1;
  2771. return 0;
  2772. }
  2773. /** Pick a live (up and listed) entry guard from entry_guards. If
  2774. * <b>state</b> is non-NULL, this is for a specific circuit --
  2775. * make sure not to pick this circuit's exit or any node in the
  2776. * exit's family. If <b>state</b> is NULL, we're looking for a random
  2777. * guard (likely a bridge). If <b>dirinfo</b> is not NO_DIRINFO (zero),
  2778. * then only select from nodes that know how to answer directory questions
  2779. * of that type. */
  2780. const node_t *
  2781. choose_random_entry(cpath_build_state_t *state)
  2782. {
  2783. tor_assert(get_options()->UseDeprecatedGuardAlgorithm);
  2784. return choose_random_entry_impl(get_guard_selection_info(),
  2785. state, 0, NO_DIRINFO, NULL);
  2786. }
  2787. /** Pick a live (up and listed) directory guard from entry_guards for
  2788. * downloading information of type <b>type</b>. */
  2789. const node_t *
  2790. choose_random_dirguard(dirinfo_type_t type)
  2791. {
  2792. tor_assert(get_options()->UseDeprecatedGuardAlgorithm);
  2793. return choose_random_entry_impl(get_guard_selection_info(),
  2794. NULL, 1, type, NULL);
  2795. }
  2796. /** Return the number of bridges that have descriptors that are marked with
  2797. * purpose 'bridge' and are running.
  2798. */
  2799. int
  2800. num_bridges_usable(void)
  2801. {
  2802. tor_assert(get_options()->UseDeprecatedGuardAlgorithm);
  2803. int n_options = 0;
  2804. tor_assert(get_options()->UseBridges);
  2805. (void) choose_random_entry_impl(get_guard_selection_info(),
  2806. NULL, 0, 0, &n_options);
  2807. return n_options;
  2808. }
  2809. /** Filter <b>all_entry_guards</b> for usable entry guards and put them
  2810. * in <b>live_entry_guards</b>. We filter based on whether the node is
  2811. * currently alive, and on whether it satisfies the restrictions
  2812. * imposed by the other arguments of this function.
  2813. *
  2814. * We don't place more guards than NumEntryGuards in <b>live_entry_guards</b>.
  2815. *
  2816. * If <b>chosen_exit</b> is set, it contains the exit node of this
  2817. * circuit. Make sure to not use it or its family as an entry guard.
  2818. *
  2819. * If <b>need_uptime</b> is set, we are looking for a stable entry guard.
  2820. * if <b>need_capacity</b> is set, we are looking for a fast entry guard.
  2821. *
  2822. * The rest of the arguments are the same as in choose_random_entry_impl().
  2823. *
  2824. * Return 1 if we should choose a guard right away. Return 0 if we
  2825. * should try to add more nodes to our list before deciding on a
  2826. * guard.
  2827. */
  2828. STATIC int
  2829. populate_live_entry_guards(smartlist_t *live_entry_guards,
  2830. const smartlist_t *all_entry_guards,
  2831. const node_t *chosen_exit,
  2832. dirinfo_type_t dirinfo_type,
  2833. int for_directory,
  2834. int need_uptime, int need_capacity)
  2835. {
  2836. const or_options_t *options = get_options();
  2837. const node_t *node = NULL;
  2838. const int num_needed = decide_num_guards(options, for_directory);
  2839. smartlist_t *exit_family = smartlist_new();
  2840. int retval = 0;
  2841. entry_is_live_flags_t entry_flags = 0;
  2842. (void) dirinfo_type;
  2843. { /* Set the flags we want our entry node to have */
  2844. if (need_uptime) {
  2845. entry_flags |= ENTRY_NEED_UPTIME;
  2846. }
  2847. if (need_capacity) {
  2848. entry_flags |= ENTRY_NEED_CAPACITY;
  2849. }
  2850. if (!for_directory) {
  2851. entry_flags |= ENTRY_NEED_DESCRIPTOR;
  2852. }
  2853. }
  2854. tor_assert(all_entry_guards);
  2855. if (chosen_exit) {
  2856. nodelist_add_node_and_family(exit_family, chosen_exit);
  2857. }
  2858. SMARTLIST_FOREACH_BEGIN(all_entry_guards, const entry_guard_t *, entry) {
  2859. const char *msg;
  2860. node = entry_is_live(entry, entry_flags, &msg);
  2861. if (!node)
  2862. continue; /* down, no point */
  2863. if (for_directory) {
  2864. if (!entry->is_dir_cache)
  2865. continue; /* We need a directory and didn't get one. */
  2866. }
  2867. if (node == chosen_exit)
  2868. continue; /* don't pick the same node for entry and exit */
  2869. if (smartlist_contains(exit_family, node))
  2870. continue; /* avoid relays that are family members of our exit */
  2871. smartlist_add(live_entry_guards, (void*)node);
  2872. if (!entry->made_contact) {
  2873. /* Always start with the first not-yet-contacted entry
  2874. * guard. Otherwise we might add several new ones, pick
  2875. * the second new one, and now we've expanded our entry
  2876. * guard list without needing to. */
  2877. retval = 1;
  2878. goto done;
  2879. }
  2880. if (smartlist_len(live_entry_guards) >= num_needed) {
  2881. retval = 1;
  2882. goto done; /* We picked enough entry guards. Done! */
  2883. }
  2884. } SMARTLIST_FOREACH_END(entry);
  2885. done:
  2886. smartlist_free(exit_family);
  2887. return retval;
  2888. }
  2889. /** Pick a node to be used as the entry guard of a circuit, relative to
  2890. * a supplied guard selection context.
  2891. *
  2892. * If <b>state</b> is set, it contains the information we know about
  2893. * the upcoming circuit.
  2894. *
  2895. * If <b>for_directory</b> is set, we are looking for a directory guard.
  2896. *
  2897. * <b>dirinfo_type</b> contains the kind of directory information we
  2898. * are looking for in our node, or NO_DIRINFO (zero) if we are not
  2899. * looking for any particular directory information (when set to
  2900. * NO_DIRINFO, the <b>dirinfo_type</b> filter is ignored).
  2901. *
  2902. * If <b>n_options_out</b> is set, we set it to the number of
  2903. * candidate guard nodes we had before picking a specific guard node.
  2904. *
  2905. * On success, return the node that should be used as the entry guard
  2906. * of the circuit. Return NULL if no such node could be found.
  2907. *
  2908. * Helper for choose_random{entry,dirguard}.
  2909. */
  2910. static const node_t *
  2911. choose_random_entry_impl(guard_selection_t *gs,
  2912. cpath_build_state_t *state, int for_directory,
  2913. dirinfo_type_t dirinfo_type, int *n_options_out)
  2914. {
  2915. const or_options_t *options = get_options();
  2916. smartlist_t *live_entry_guards = smartlist_new();
  2917. const node_t *chosen_exit =
  2918. state?build_state_get_exit_node(state) : NULL;
  2919. const node_t *node = NULL;
  2920. int need_uptime = state ? state->need_uptime : 0;
  2921. int need_capacity = state ? state->need_capacity : 0;
  2922. int preferred_min = 0;
  2923. const int num_needed = decide_num_guards(options, for_directory);
  2924. int retval = 0;
  2925. tor_assert(gs != NULL);
  2926. tor_assert(gs->chosen_entry_guards != NULL);
  2927. if (n_options_out)
  2928. *n_options_out = 0;
  2929. if (gs->should_add_entry_nodes)
  2930. entry_guards_set_from_config(gs, options);
  2931. if (!entry_list_is_constrained(options) &&
  2932. smartlist_len(gs->chosen_entry_guards) < num_needed)
  2933. pick_entry_guards(gs, options, for_directory);
  2934. retry:
  2935. smartlist_clear(live_entry_guards);
  2936. /* Populate the list of live entry guards so that we pick one of
  2937. them. */
  2938. retval = populate_live_entry_guards(live_entry_guards,
  2939. gs->chosen_entry_guards,
  2940. chosen_exit,
  2941. dirinfo_type,
  2942. for_directory,
  2943. need_uptime, need_capacity);
  2944. if (retval == 1) { /* We should choose a guard right now. */
  2945. goto choose_and_finish;
  2946. }
  2947. if (entry_list_is_constrained(options)) {
  2948. /* If we prefer the entry nodes we've got, and we have at least
  2949. * one choice, that's great. Use it. */
  2950. preferred_min = 1;
  2951. } else {
  2952. /* Try to have at least 2 choices available. This way we don't
  2953. * get stuck with a single live-but-crummy entry and just keep
  2954. * using it.
  2955. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  2956. preferred_min = 2;
  2957. }
  2958. if (smartlist_len(live_entry_guards) < preferred_min) {
  2959. if (!entry_list_is_constrained(options)) {
  2960. /* still no? try adding a new entry then */
  2961. /* XXX if guard doesn't imply fast and stable, then we need
  2962. * to tell add_an_entry_guard below what we want, or it might
  2963. * be a long time til we get it. -RD */
  2964. node = add_an_entry_guard(gs, NULL, 0, 0, 1, for_directory);
  2965. if (node) {
  2966. entry_guards_changed_for_guard_selection(gs);
  2967. /* XXX we start over here in case the new node we added shares
  2968. * a family with our exit node. There's a chance that we'll just
  2969. * load up on entry guards here, if the network we're using is
  2970. * one big family. Perhaps we should teach add_an_entry_guard()
  2971. * to understand nodes-to-avoid-if-possible? -RD */
  2972. goto retry;
  2973. }
  2974. }
  2975. if (!node && need_uptime) {
  2976. need_uptime = 0; /* try without that requirement */
  2977. goto retry;
  2978. }
  2979. if (!node && need_capacity) {
  2980. /* still no? last attempt, try without requiring capacity */
  2981. need_capacity = 0;
  2982. goto retry;
  2983. }
  2984. /* live_entry_guards may be empty below. Oh well, we tried. */
  2985. }
  2986. choose_and_finish:
  2987. if (entry_list_is_constrained(options)) {
  2988. /* We need to weight by bandwidth, because our bridges or entryguards
  2989. * were not already selected proportional to their bandwidth. */
  2990. node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  2991. } else {
  2992. /* We choose uniformly at random here, because choose_good_entry_server()
  2993. * already weights its choices by bandwidth, so we don't want to
  2994. * *double*-weight our guard selection. */
  2995. node = smartlist_choose(live_entry_guards);
  2996. }
  2997. if (n_options_out)
  2998. *n_options_out = smartlist_len(live_entry_guards);
  2999. smartlist_free(live_entry_guards);
  3000. return node;
  3001. }
  3002. static void
  3003. pathbias_check_use_success_count(entry_guard_t *node)
  3004. {
  3005. const or_options_t *options = get_options();
  3006. const double EPSILON = 1.0e-9;
  3007. /* Note: We rely on the < comparison here to allow us to set a 0
  3008. * rate and disable the feature entirely. If refactoring, don't
  3009. * change to <= */
  3010. if (node->pb.use_attempts > EPSILON &&
  3011. pathbias_get_use_success_count(node)/node->pb.use_attempts
  3012. < pathbias_get_extreme_use_rate(options) &&
  3013. pathbias_get_dropguards(options)) {
  3014. node->pb.path_bias_disabled = 1;
  3015. log_info(LD_GENERAL,
  3016. "Path use bias is too high (%f/%f); disabling node %s",
  3017. node->pb.circ_successes, node->pb.circ_attempts,
  3018. node->nickname);
  3019. }
  3020. }
  3021. static void
  3022. pathbias_check_close_success_count(entry_guard_t *node)
  3023. {
  3024. const or_options_t *options = get_options();
  3025. const double EPSILON = 1.0e-9;
  3026. /* Note: We rely on the < comparison here to allow us to set a 0
  3027. * rate and disable the feature entirely. If refactoring, don't
  3028. * change to <= */
  3029. if (node->pb.circ_attempts > EPSILON &&
  3030. pathbias_get_close_success_count(node)/node->pb.circ_attempts
  3031. < pathbias_get_extreme_rate(options) &&
  3032. pathbias_get_dropguards(options)) {
  3033. node->pb.path_bias_disabled = 1;
  3034. log_info(LD_GENERAL,
  3035. "Path bias is too high (%f/%f); disabling node %s",
  3036. node->pb.circ_successes, node->pb.circ_attempts,
  3037. node->nickname);
  3038. }
  3039. }
  3040. /** Parse <b>state</b> and learn about the entry guards it describes.
  3041. * If <b>set</b> is true, and there are no errors, replace the guard
  3042. * list in the provided guard selection context with what we find.
  3043. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  3044. * describing the error, and return -1.
  3045. */
  3046. int
  3047. entry_guards_parse_state_for_guard_selection(
  3048. guard_selection_t *gs,
  3049. or_state_t *state, int set, char **msg)
  3050. {
  3051. entry_guard_t *node = NULL;
  3052. smartlist_t *new_entry_guards = smartlist_new();
  3053. config_line_t *line;
  3054. time_t now = time(NULL);
  3055. const char *state_version = state->TorVersion;
  3056. digestmap_t *added_by = digestmap_new();
  3057. tor_assert(gs != NULL);
  3058. *msg = NULL;
  3059. for (line = state->EntryGuards; line; line = line->next) {
  3060. if (!strcasecmp(line->key, "EntryGuard")) {
  3061. smartlist_t *args = smartlist_new();
  3062. node = tor_malloc_zero(sizeof(entry_guard_t));
  3063. /* all entry guards on disk have been contacted */
  3064. node->made_contact = 1;
  3065. smartlist_add(new_entry_guards, node);
  3066. smartlist_split_string(args, line->value, " ",
  3067. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3068. if (smartlist_len(args)<2) {
  3069. *msg = tor_strdup("Unable to parse entry nodes: "
  3070. "Too few arguments to EntryGuard");
  3071. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  3072. *msg = tor_strdup("Unable to parse entry nodes: "
  3073. "Bad nickname for EntryGuard");
  3074. } else {
  3075. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  3076. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  3077. strlen(smartlist_get(args,1))) != DIGEST_LEN) {
  3078. *msg = tor_strdup("Unable to parse entry nodes: "
  3079. "Bad hex digest for EntryGuard");
  3080. }
  3081. }
  3082. if (smartlist_len(args) >= 3) {
  3083. const char *is_cache = smartlist_get(args, 2);
  3084. if (!strcasecmp(is_cache, "DirCache")) {
  3085. node->is_dir_cache = 1;
  3086. } else if (!strcasecmp(is_cache, "NoDirCache")) {
  3087. node->is_dir_cache = 0;
  3088. } else {
  3089. log_warn(LD_CONFIG, "Bogus third argument to EntryGuard line: %s",
  3090. escaped(is_cache));
  3091. }
  3092. }
  3093. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  3094. smartlist_free(args);
  3095. if (*msg)
  3096. break;
  3097. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  3098. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  3099. time_t when;
  3100. time_t last_try = 0;
  3101. if (!node) {
  3102. *msg = tor_strdup("Unable to parse entry nodes: "
  3103. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  3104. break;
  3105. }
  3106. if (parse_iso_time_(line->value, &when, 0, 0)<0) {
  3107. *msg = tor_strdup("Unable to parse entry nodes: "
  3108. "Bad time in EntryGuardDownSince/UnlistedSince");
  3109. break;
  3110. }
  3111. if (when > now) {
  3112. /* It's a bad idea to believe info in the future: you can wind
  3113. * up with timeouts that aren't allowed to happen for years. */
  3114. continue;
  3115. }
  3116. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  3117. /* ignore failure */
  3118. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  3119. }
  3120. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  3121. node->unreachable_since = when;
  3122. node->last_attempted = last_try;
  3123. } else {
  3124. node->bad_since = when;
  3125. }
  3126. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  3127. char d[DIGEST_LEN];
  3128. /* format is digest version date */
  3129. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  3130. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  3131. continue;
  3132. }
  3133. if (base16_decode(d, sizeof(d),
  3134. line->value, HEX_DIGEST_LEN) != sizeof(d) ||
  3135. line->value[HEX_DIGEST_LEN] != ' ') {
  3136. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  3137. "hex digest", escaped(line->value));
  3138. continue;
  3139. }
  3140. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  3141. } else if (!strcasecmp(line->key, "EntryGuardPathUseBias")) {
  3142. double use_cnt, success_cnt;
  3143. if (!node) {
  3144. *msg = tor_strdup("Unable to parse entry nodes: "
  3145. "EntryGuardPathUseBias without EntryGuard");
  3146. break;
  3147. }
  3148. if (tor_sscanf(line->value, "%lf %lf",
  3149. &use_cnt, &success_cnt) != 2) {
  3150. log_info(LD_GENERAL, "Malformed path use bias line for node %s",
  3151. node->nickname);
  3152. continue;
  3153. }
  3154. if (use_cnt < success_cnt) {
  3155. int severity = LOG_INFO;
  3156. /* If this state file was written by a Tor that would have
  3157. * already fixed it, then the overcounting bug is still there.. */
  3158. if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
  3159. severity = LOG_NOTICE;
  3160. }
  3161. log_fn(severity, LD_BUG,
  3162. "State file contains unexpectedly high usage success "
  3163. "counts %lf/%lf for Guard %s ($%s)",
  3164. success_cnt, use_cnt,
  3165. node->nickname, hex_str(node->identity, DIGEST_LEN));
  3166. success_cnt = use_cnt;
  3167. }
  3168. node->pb.use_attempts = use_cnt;
  3169. node->pb.use_successes = success_cnt;
  3170. log_info(LD_GENERAL, "Read %f/%f path use bias for node %s",
  3171. node->pb.use_successes, node->pb.use_attempts, node->nickname);
  3172. pathbias_check_use_success_count(node);
  3173. } else if (!strcasecmp(line->key, "EntryGuardPathBias")) {
  3174. double hop_cnt, success_cnt, timeouts, collapsed, successful_closed,
  3175. unusable;
  3176. if (!node) {
  3177. *msg = tor_strdup("Unable to parse entry nodes: "
  3178. "EntryGuardPathBias without EntryGuard");
  3179. break;
  3180. }
  3181. /* First try 3 params, then 2. */
  3182. /* In the long run: circuit_success ~= successful_circuit_close +
  3183. * collapsed_circuits +
  3184. * unusable_circuits */
  3185. if (tor_sscanf(line->value, "%lf %lf %lf %lf %lf %lf",
  3186. &hop_cnt, &success_cnt, &successful_closed,
  3187. &collapsed, &unusable, &timeouts) != 6) {
  3188. int old_success, old_hops;
  3189. if (tor_sscanf(line->value, "%u %u", &old_success, &old_hops) != 2) {
  3190. continue;
  3191. }
  3192. log_info(LD_GENERAL, "Reading old-style EntryGuardPathBias %s",
  3193. escaped(line->value));
  3194. success_cnt = old_success;
  3195. successful_closed = old_success;
  3196. hop_cnt = old_hops;
  3197. timeouts = 0;
  3198. collapsed = 0;
  3199. unusable = 0;
  3200. }
  3201. if (hop_cnt < success_cnt) {
  3202. int severity = LOG_INFO;
  3203. /* If this state file was written by a Tor that would have
  3204. * already fixed it, then the overcounting bug is still there.. */
  3205. if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
  3206. severity = LOG_NOTICE;
  3207. }
  3208. log_fn(severity, LD_BUG,
  3209. "State file contains unexpectedly high success counts "
  3210. "%lf/%lf for Guard %s ($%s)",
  3211. success_cnt, hop_cnt,
  3212. node->nickname, hex_str(node->identity, DIGEST_LEN));
  3213. success_cnt = hop_cnt;
  3214. }
  3215. node->pb.circ_attempts = hop_cnt;
  3216. node->pb.circ_successes = success_cnt;
  3217. node->pb.successful_circuits_closed = successful_closed;
  3218. node->pb.timeouts = timeouts;
  3219. node->pb.collapsed_circuits = collapsed;
  3220. node->pb.unusable_circuits = unusable;
  3221. log_info(LD_GENERAL, "Read %f/%f path bias for node %s",
  3222. node->pb.circ_successes, node->pb.circ_attempts,
  3223. node->nickname);
  3224. pathbias_check_close_success_count(node);
  3225. } else {
  3226. log_warn(LD_BUG, "Unexpected key %s", line->key);
  3227. }
  3228. }
  3229. SMARTLIST_FOREACH_BEGIN(new_entry_guards, entry_guard_t *, e) {
  3230. char *sp;
  3231. char *val = digestmap_get(added_by, e->identity);
  3232. if (val && (sp = strchr(val, ' '))) {
  3233. time_t when;
  3234. *sp++ = '\0';
  3235. if (parse_iso_time(sp, &when)<0) {
  3236. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  3237. } else {
  3238. e->chosen_by_version = tor_strdup(val);
  3239. e->chosen_on_date = when;
  3240. }
  3241. } else {
  3242. if (state_version) {
  3243. e->chosen_on_date = crypto_rand_time_range(now - 3600*24*30, now);
  3244. e->chosen_by_version = tor_strdup(state_version);
  3245. }
  3246. }
  3247. if (e->pb.path_bias_disabled && !e->bad_since)
  3248. e->bad_since = time(NULL);
  3249. }
  3250. SMARTLIST_FOREACH_END(e);
  3251. if (*msg || !set) {
  3252. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  3253. entry_guard_free(e));
  3254. smartlist_free(new_entry_guards);
  3255. } else { /* !err && set */
  3256. if (gs->chosen_entry_guards) {
  3257. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e,
  3258. entry_guard_free(e));
  3259. smartlist_free(gs->chosen_entry_guards);
  3260. }
  3261. gs->chosen_entry_guards = new_entry_guards;
  3262. /* XXX hand new_entry_guards to this func, and move it up a
  3263. * few lines, so we don't have to re-dirty it */
  3264. if (remove_obsolete_entry_guards(gs, now))
  3265. entry_guards_dirty = 1;
  3266. }
  3267. digestmap_free(added_by, tor_free_);
  3268. return *msg ? -1 : 0;
  3269. }
  3270. /** Parse <b>state</b> and learn about the entry guards it describes.
  3271. * If <b>set</b> is true, and there are no errors, replace the guard
  3272. * list in the default guard selection context with what we find.
  3273. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  3274. * describing the error, and return -1.
  3275. */
  3276. int
  3277. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  3278. {
  3279. entry_guards_dirty = 0;
  3280. int r1 = entry_guards_load_guards_from_state(state, set);
  3281. int r2 = entry_guards_parse_state_for_guard_selection(
  3282. get_guard_selection_by_name("legacy", 1),
  3283. state, set, msg);
  3284. entry_guards_dirty = 0;
  3285. if (r1 < 0 || r2 < 0) {
  3286. if (msg && *msg == NULL) {
  3287. *msg = tor_strdup("parsing error"); //xxxx prop271 should we try harder?
  3288. }
  3289. return -1;
  3290. }
  3291. return 0;
  3292. }
  3293. /** How long will we let a change in our guard nodes stay un-saved
  3294. * when we are trying to avoid disk writes? */
  3295. #define SLOW_GUARD_STATE_FLUSH_TIME 600
  3296. /** How long will we let a change in our guard nodes stay un-saved
  3297. * when we are not trying to avoid disk writes? */
  3298. #define FAST_GUARD_STATE_FLUSH_TIME 30
  3299. /** Our list of entry guards has changed for a particular guard selection
  3300. * context, or some element of one of our entry guards has changed for one.
  3301. * Write the changes to disk within the next few minutes.
  3302. */
  3303. void
  3304. entry_guards_changed_for_guard_selection(guard_selection_t *gs)
  3305. {
  3306. time_t when;
  3307. tor_assert(gs != NULL);
  3308. entry_guards_dirty = 1;
  3309. if (get_options()->AvoidDiskWrites)
  3310. when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
  3311. else
  3312. when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
  3313. /* or_state_save() will call entry_guards_update_state() and
  3314. entry_guards_update_guards_in_state()
  3315. */
  3316. or_state_mark_dirty(get_or_state(), when);
  3317. }
  3318. /** Our list of entry guards has changed for the default guard selection
  3319. * context, or some element of one of our entry guards has changed. Write
  3320. * the changes to disk within the next few minutes.
  3321. */
  3322. void
  3323. entry_guards_changed(void)
  3324. {
  3325. entry_guards_changed_for_guard_selection(get_guard_selection_info());
  3326. }
  3327. /** If the entry guard info has not changed, do nothing and return.
  3328. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  3329. * a new one out of the global entry_guards list, and then mark
  3330. * <b>state</b> dirty so it will get saved to disk.
  3331. */
  3332. void
  3333. entry_guards_update_state(or_state_t *state)
  3334. {
  3335. config_line_t **next, *line;
  3336. entry_guards_dirty = 0;
  3337. // Handles all non-legacy guard info.
  3338. entry_guards_update_guards_in_state(state);
  3339. entry_guards_dirty = 0;
  3340. guard_selection_t *gs = get_guard_selection_by_name("legacy", 0);
  3341. if (!gs)
  3342. return; // nothign to save.
  3343. tor_assert(gs->chosen_entry_guards != NULL);
  3344. config_free_lines(state->EntryGuards);
  3345. next = &state->EntryGuards;
  3346. *next = NULL;
  3347. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3348. char dbuf[HEX_DIGEST_LEN+1];
  3349. if (!e->made_contact)
  3350. continue; /* don't write this one to disk */
  3351. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3352. line->key = tor_strdup("EntryGuard");
  3353. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  3354. tor_asprintf(&line->value, "%s %s %sDirCache", e->nickname, dbuf,
  3355. e->is_dir_cache ? "" : "No");
  3356. next = &(line->next);
  3357. if (e->unreachable_since) {
  3358. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3359. line->key = tor_strdup("EntryGuardDownSince");
  3360. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  3361. format_iso_time(line->value, e->unreachable_since);
  3362. if (e->last_attempted) {
  3363. line->value[ISO_TIME_LEN] = ' ';
  3364. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  3365. }
  3366. next = &(line->next);
  3367. }
  3368. if (e->bad_since) {
  3369. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3370. line->key = tor_strdup("EntryGuardUnlistedSince");
  3371. line->value = tor_malloc(ISO_TIME_LEN+1);
  3372. format_iso_time(line->value, e->bad_since);
  3373. next = &(line->next);
  3374. }
  3375. if (e->chosen_on_date && e->chosen_by_version &&
  3376. !strchr(e->chosen_by_version, ' ')) {
  3377. char d[HEX_DIGEST_LEN+1];
  3378. char t[ISO_TIME_LEN+1];
  3379. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3380. line->key = tor_strdup("EntryGuardAddedBy");
  3381. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  3382. format_iso_time(t, e->chosen_on_date);
  3383. tor_asprintf(&line->value, "%s %s %s",
  3384. d, e->chosen_by_version, t);
  3385. next = &(line->next);
  3386. }
  3387. if (e->pb.circ_attempts > 0) {
  3388. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3389. line->key = tor_strdup("EntryGuardPathBias");
  3390. /* In the long run: circuit_success ~= successful_circuit_close +
  3391. * collapsed_circuits +
  3392. * unusable_circuits */
  3393. tor_asprintf(&line->value, "%f %f %f %f %f %f",
  3394. e->pb.circ_attempts, e->pb.circ_successes,
  3395. pathbias_get_close_success_count(e),
  3396. e->pb.collapsed_circuits,
  3397. e->pb.unusable_circuits, e->pb.timeouts);
  3398. next = &(line->next);
  3399. }
  3400. if (e->pb.use_attempts > 0) {
  3401. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3402. line->key = tor_strdup("EntryGuardPathUseBias");
  3403. tor_asprintf(&line->value, "%f %f",
  3404. e->pb.use_attempts,
  3405. pathbias_get_use_success_count(e));
  3406. next = &(line->next);
  3407. }
  3408. } SMARTLIST_FOREACH_END(e);
  3409. if (!get_options()->AvoidDiskWrites)
  3410. or_state_mark_dirty(get_or_state(), 0);
  3411. entry_guards_dirty = 0;
  3412. }
  3413. /** If <b>question</b> is the string "entry-guards", then dump
  3414. * to *<b>answer</b> a newly allocated string describing all of
  3415. * the nodes in the global entry_guards list. See control-spec.txt
  3416. * for details.
  3417. * For backward compatibility, we also handle the string "helper-nodes".
  3418. *
  3419. * XXX this should be totally redesigned after prop 271 too, and that's
  3420. * going to take some control spec work.
  3421. * */
  3422. int
  3423. getinfo_helper_entry_guards(control_connection_t *conn,
  3424. const char *question, char **answer,
  3425. const char **errmsg)
  3426. {
  3427. guard_selection_t *gs = get_guard_selection_info();
  3428. tor_assert(gs != NULL);
  3429. tor_assert(gs->chosen_entry_guards != NULL);
  3430. (void) conn;
  3431. (void) errmsg;
  3432. if (!strcmp(question,"entry-guards") ||
  3433. !strcmp(question,"helper-nodes")) {
  3434. smartlist_t *sl = smartlist_new();
  3435. char tbuf[ISO_TIME_LEN+1];
  3436. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  3437. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3438. const char *status = NULL;
  3439. time_t when = 0;
  3440. const node_t *node;
  3441. if (!e->made_contact) {
  3442. status = "never-connected";
  3443. } else if (e->bad_since) {
  3444. when = e->bad_since;
  3445. status = "unusable";
  3446. } else if (e->unreachable_since) {
  3447. when = e->unreachable_since;
  3448. status = "down";
  3449. } else {
  3450. status = "up";
  3451. }
  3452. node = node_get_by_id(e->identity);
  3453. if (node) {
  3454. node_get_verbose_nickname(node, nbuf);
  3455. } else {
  3456. nbuf[0] = '$';
  3457. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  3458. /* e->nickname field is not very reliable if we don't know about
  3459. * this router any longer; don't include it. */
  3460. }
  3461. if (when) {
  3462. format_iso_time(tbuf, when);
  3463. smartlist_add_asprintf(sl, "%s %s %s\n", nbuf, status, tbuf);
  3464. } else {
  3465. smartlist_add_asprintf(sl, "%s %s\n", nbuf, status);
  3466. }
  3467. } SMARTLIST_FOREACH_END(e);
  3468. *answer = smartlist_join_strings(sl, "", 0, NULL);
  3469. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  3470. smartlist_free(sl);
  3471. }
  3472. return 0;
  3473. }
  3474. /* Given the original bandwidth of a guard and its guardfraction,
  3475. * calculate how much bandwidth the guard should have as a guard and
  3476. * as a non-guard.
  3477. *
  3478. * Quoting from proposal236:
  3479. *
  3480. * Let Wpf denote the weight from the 'bandwidth-weights' line a
  3481. * client would apply to N for position p if it had the guard
  3482. * flag, Wpn the weight if it did not have the guard flag, and B the
  3483. * measured bandwidth of N in the consensus. Then instead of choosing
  3484. * N for position p proportionally to Wpf*B or Wpn*B, clients should
  3485. * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
  3486. *
  3487. * This function fills the <b>guardfraction_bw</b> structure. It sets
  3488. * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
  3489. */
  3490. void
  3491. guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
  3492. int orig_bandwidth,
  3493. uint32_t guardfraction_percentage)
  3494. {
  3495. double guardfraction_fraction;
  3496. /* Turn the percentage into a fraction. */
  3497. tor_assert(guardfraction_percentage <= 100);
  3498. guardfraction_fraction = guardfraction_percentage / 100.0;
  3499. long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
  3500. tor_assert(guard_bw <= INT_MAX);
  3501. guardfraction_bw->guard_bw = (int) guard_bw;
  3502. guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
  3503. }
  3504. /** Returns true iff the node is used as a guard in the specified guard
  3505. * context */
  3506. int
  3507. is_node_used_as_guard_for_guard_selection(guard_selection_t *gs,
  3508. const node_t *node)
  3509. {
  3510. int res = 0;
  3511. /*
  3512. * We used to have a using_as_guard flag in node_t, but it had to go away
  3513. * to allow for multiple guard selection contexts. Instead, search the
  3514. * guard list for a matching digest.
  3515. */
  3516. tor_assert(gs != NULL);
  3517. tor_assert(node != NULL);
  3518. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3519. if (tor_memeq(e->identity, node->identity, DIGEST_LEN)) {
  3520. res = 1;
  3521. break;
  3522. }
  3523. } SMARTLIST_FOREACH_END(e);
  3524. return res;
  3525. }
  3526. /** Returns true iff the node is used as a guard in the default guard
  3527. * context */
  3528. MOCK_IMPL(int,
  3529. is_node_used_as_guard, (const node_t *node))
  3530. {
  3531. return is_node_used_as_guard_for_guard_selection(
  3532. get_guard_selection_info(), node);
  3533. }
  3534. /** Return 1 if we have at least one descriptor for an entry guard
  3535. * (bridge or member of EntryNodes) and all descriptors we know are
  3536. * down. Else return 0. If <b>act</b> is 1, then mark the down guards
  3537. * up; else just observe and report. */
  3538. static int
  3539. entries_retry_helper(const or_options_t *options, int act)
  3540. {
  3541. const node_t *node;
  3542. int any_known = 0;
  3543. int any_running = 0;
  3544. int need_bridges = options->UseBridges != 0;
  3545. guard_selection_t *gs = get_guard_selection_info();
  3546. tor_assert(gs != NULL);
  3547. tor_assert(gs->chosen_entry_guards != NULL);
  3548. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3549. node = node_get_by_id(e->identity);
  3550. if (node && node_has_descriptor(node) &&
  3551. node_is_bridge(node) == need_bridges &&
  3552. (!need_bridges || (!e->bad_since &&
  3553. node_is_a_configured_bridge(node)))) {
  3554. any_known = 1;
  3555. if (node->is_running)
  3556. any_running = 1; /* some entry is both known and running */
  3557. else if (act) {
  3558. /* Mark all current connections to this OR as unhealthy, since
  3559. * otherwise there could be one that started 30 seconds
  3560. * ago, and in 30 seconds it will time out, causing us to mark
  3561. * the node down and undermine the retry attempt. We mark even
  3562. * the established conns, since if the network just came back
  3563. * we'll want to attach circuits to fresh conns. */
  3564. connection_or_set_bad_connections(node->identity, 1);
  3565. /* mark this entry node for retry */
  3566. router_set_status(node->identity, 1);
  3567. e->can_retry = 1;
  3568. e->bad_since = 0;
  3569. }
  3570. }
  3571. } SMARTLIST_FOREACH_END(e);
  3572. log_debug(LD_DIR, "%d: any_known %d, any_running %d",
  3573. act, any_known, any_running);
  3574. return any_known && !any_running;
  3575. }
  3576. /** Do we know any descriptors for our bridges / entrynodes, and are
  3577. * all the ones we have descriptors for down? */
  3578. int
  3579. entries_known_but_down(const or_options_t *options)
  3580. {
  3581. tor_assert(entry_list_is_constrained(options));
  3582. return entries_retry_helper(options, 0);
  3583. }
  3584. /** Mark all down known bridges / entrynodes up. */
  3585. void
  3586. entries_retry_all(const or_options_t *options)
  3587. {
  3588. tor_assert(entry_list_is_constrained(options));
  3589. entries_retry_helper(options, 1);
  3590. }
  3591. /** Helper: Update the status of all entry guards, in whatever algorithm
  3592. * is used. Return true if we should stop using all previously generated
  3593. * circuits. */
  3594. int
  3595. guards_update_all(void)
  3596. {
  3597. if (get_options()->UseDeprecatedGuardAlgorithm) {
  3598. entry_guards_compute_status(get_options(), approx_time());
  3599. return 0;
  3600. } else {
  3601. return entry_guards_update_all(get_guard_selection_info());
  3602. }
  3603. }
  3604. /** Helper: pick a guard for a circuit, with whatever algorithm is
  3605. used. */
  3606. const node_t *
  3607. guards_choose_guard(cpath_build_state_t *state,
  3608. circuit_guard_state_t **guard_state_out)
  3609. {
  3610. if (get_options()->UseDeprecatedGuardAlgorithm) {
  3611. return choose_random_entry(state);
  3612. } else {
  3613. // XXXX prop271 we need to look at the chosen exit node if any, and
  3614. // not duplicate it.
  3615. const node_t *r = NULL;
  3616. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  3617. &r,
  3618. guard_state_out) < 0) {
  3619. tor_assert(r == NULL);
  3620. }
  3621. return r;
  3622. }
  3623. }
  3624. /** Helper: pick a directory guard, with whatever algorithm is used. */
  3625. const node_t *
  3626. guards_choose_dirguard(dirinfo_type_t info,
  3627. circuit_guard_state_t **guard_state_out)
  3628. {
  3629. if (get_options()->UseDeprecatedGuardAlgorithm) {
  3630. return choose_random_dirguard(info);
  3631. } else {
  3632. // XXXX prop271 look at info?
  3633. const node_t *r = NULL;
  3634. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  3635. &r,
  3636. guard_state_out) < 0) {
  3637. tor_assert(r == NULL);
  3638. }
  3639. return r;
  3640. }
  3641. }
  3642. /** Free one guard selection context */
  3643. STATIC void
  3644. guard_selection_free(guard_selection_t *gs)
  3645. {
  3646. if (!gs) return;
  3647. tor_free(gs->name);
  3648. if (gs->chosen_entry_guards) {
  3649. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e,
  3650. entry_guard_free(e));
  3651. smartlist_free(gs->chosen_entry_guards);
  3652. gs->chosen_entry_guards = NULL;
  3653. }
  3654. if (gs->sampled_entry_guards) {
  3655. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
  3656. entry_guard_free(e));
  3657. smartlist_free(gs->sampled_entry_guards);
  3658. gs->sampled_entry_guards = NULL;
  3659. }
  3660. smartlist_free(gs->confirmed_entry_guards);
  3661. smartlist_free(gs->primary_entry_guards);
  3662. tor_free(gs);
  3663. }
  3664. /** Release all storage held by the list of entry guards and related
  3665. * memory structs. */
  3666. void
  3667. entry_guards_free_all(void)
  3668. {
  3669. /* Null out the default */
  3670. curr_guard_context = NULL;
  3671. /* Free all the guard contexts */
  3672. if (guard_contexts != NULL) {
  3673. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  3674. guard_selection_free(gs);
  3675. } SMARTLIST_FOREACH_END(gs);
  3676. smartlist_free(guard_contexts);
  3677. guard_contexts = NULL;
  3678. }
  3679. circuit_build_times_free_timeouts(get_circuit_build_times_mutable());
  3680. }