entrynodes.c 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178
  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. return 0;
  1411. }
  1412. }
  1413. /* "If any circuit is <waiting_for_better_guard>, and every currently
  1414. {is_pending} circuit whose guard has higher priority has been in
  1415. state <usable_if_no_better_guard> for at least
  1416. {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds, and all primary guards
  1417. have reachable status of <no>, then call that circuit <complete>."
  1418. XXXX --- prop271 deviation. there's no such thing in the spec as
  1419. an {is_pending circuit}; fix the spec.
  1420. */
  1421. int n_blockers_found = 0;
  1422. const time_t state_set_at_cutoff =
  1423. approx_time() - NONPRIMARY_GUARD_CONNECT_TIMEOUT;
  1424. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  1425. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  1426. if (state == NULL)
  1427. continue;
  1428. if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
  1429. continue;
  1430. if (state->state_set_at > state_set_at_cutoff &&
  1431. circ_state_has_higher_priority(circ, best_waiting_circuit))
  1432. ++n_blockers_found;
  1433. } SMARTLIST_FOREACH_END(circ);
  1434. if (n_blockers_found) {
  1435. log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  1436. "%d guard-stalled, but %d pending circuit(s) had higher "
  1437. "guard priority, so not upgrading.",
  1438. n_waiting, n_blockers_found);
  1439. return 0;
  1440. }
  1441. /* Okay. We have a best waiting circuit, and we aren't waiting for
  1442. anything better. Add all circuits with that priority to the
  1443. list, and call them COMPLETE. */
  1444. int n_succeeded = 0;
  1445. SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
  1446. circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
  1447. if (state == NULL)
  1448. continue;
  1449. if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
  1450. continue;
  1451. if (circ_state_has_higher_priority(best_waiting_circuit, circ))
  1452. continue;
  1453. state->state = GUARD_CIRC_STATE_COMPLETE;
  1454. state->state_set_at = approx_time();
  1455. smartlist_add(newly_complete_out, circ);
  1456. ++n_succeeded;
  1457. } SMARTLIST_FOREACH_END(circ);
  1458. log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
  1459. "%d guard-stalled, %d complete. %d of the guard-stalled "
  1460. "circuit(s) had high enough priority to upgrade.",
  1461. n_waiting, n_complete, n_succeeded);
  1462. tor_assert_nonfatal(n_succeeded >= 1);
  1463. return 1;
  1464. }
  1465. /**
  1466. * Return true iff the circuit whose state is <b>guard_state</b> should
  1467. * expire.
  1468. */
  1469. int
  1470. entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
  1471. {
  1472. if (guard_state == NULL)
  1473. return 0;
  1474. const time_t expire_if_waiting_since =
  1475. approx_time() - NONPRIMARY_GUARD_IDLE_TIMEOUT;
  1476. return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
  1477. && guard_state->state_set_at < expire_if_waiting_since);
  1478. }
  1479. /**
  1480. * Update all derived pieces of the guard selection state in <b>gs</b>.
  1481. * Return true iff we should stop using all previously generated circuits.
  1482. */
  1483. int
  1484. entry_guards_update_all(guard_selection_t *gs)
  1485. {
  1486. sampled_guards_update_from_consensus(gs);
  1487. entry_guards_update_filtered_sets(gs);
  1488. entry_guards_update_confirmed(gs);
  1489. entry_guards_update_primary(gs);
  1490. return 0;
  1491. }
  1492. /**
  1493. * Return a newly allocated string for encoding the persistent parts of
  1494. * <b>guard</b> to the state file.
  1495. */
  1496. STATIC char *
  1497. entry_guard_encode_for_state(entry_guard_t *guard)
  1498. {
  1499. /*
  1500. * The meta-format we use is K=V K=V K=V... where K can be any
  1501. * characters excepts space and =, and V can be any characters except
  1502. * space. The order of entries is not allowed to matter.
  1503. * Unrecognized K=V entries are persisted; recognized but erroneous
  1504. * entries are corrected.
  1505. */
  1506. smartlist_t *result = smartlist_new();
  1507. char tbuf[ISO_TIME_LEN+1];
  1508. tor_assert(guard);
  1509. smartlist_add_asprintf(result, "in=%s", guard->selection_name);
  1510. smartlist_add_asprintf(result, "rsa_id=%s",
  1511. hex_str(guard->identity, DIGEST_LEN));
  1512. if (strlen(guard->nickname)) {
  1513. smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
  1514. }
  1515. format_iso_time_nospace(tbuf, guard->sampled_on_date);
  1516. smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
  1517. if (guard->sampled_by_version) {
  1518. smartlist_add_asprintf(result, "sampled_by=%s",
  1519. guard->sampled_by_version);
  1520. }
  1521. if (guard->unlisted_since_date > 0) {
  1522. format_iso_time_nospace(tbuf, guard->unlisted_since_date);
  1523. smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
  1524. }
  1525. smartlist_add_asprintf(result, "listed=%d",
  1526. (int)guard->currently_listed);
  1527. if (guard->confirmed_idx >= 0) {
  1528. format_iso_time_nospace(tbuf, guard->confirmed_on_date);
  1529. smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
  1530. smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
  1531. }
  1532. const double EPSILON = 1.0e-6;
  1533. /* Make a copy of the pathbias object, since we will want to update
  1534. some of them */
  1535. guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
  1536. pb->use_successes = pathbias_get_use_success_count(guard);
  1537. pb->successful_circuits_closed = pathbias_get_close_success_count(guard);
  1538. #define PB_FIELD(field) do { \
  1539. if (pb->field >= EPSILON) { \
  1540. smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
  1541. } \
  1542. } while (0)
  1543. PB_FIELD(use_attempts);
  1544. PB_FIELD(use_successes);
  1545. PB_FIELD(circ_attempts);
  1546. PB_FIELD(circ_successes);
  1547. PB_FIELD(successful_circuits_closed);
  1548. PB_FIELD(collapsed_circuits);
  1549. PB_FIELD(unusable_circuits);
  1550. PB_FIELD(timeouts);
  1551. tor_free(pb);
  1552. #undef PB_FIELD
  1553. if (guard->extra_state_fields)
  1554. smartlist_add_strdup(result, guard->extra_state_fields);
  1555. char *joined = smartlist_join_strings(result, " ", 0, NULL);
  1556. SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
  1557. smartlist_free(result);
  1558. return joined;
  1559. }
  1560. /**
  1561. * Given a string generated by entry_guard_encode_for_state(), parse it
  1562. * (if possible) and return an entry_guard_t object for it. Return NULL
  1563. * on complete failure.
  1564. */
  1565. STATIC entry_guard_t *
  1566. entry_guard_parse_from_state(const char *s)
  1567. {
  1568. /* Unrecognized entries get put in here. */
  1569. smartlist_t *extra = smartlist_new();
  1570. /* These fields get parsed from the string. */
  1571. char *in = NULL;
  1572. char *rsa_id = NULL;
  1573. char *nickname = NULL;
  1574. char *sampled_on = NULL;
  1575. char *sampled_by = NULL;
  1576. char *unlisted_since = NULL;
  1577. char *listed = NULL;
  1578. char *confirmed_on = NULL;
  1579. char *confirmed_idx = NULL;
  1580. // pathbias
  1581. char *pb_use_attempts = NULL;
  1582. char *pb_use_successes = NULL;
  1583. char *pb_circ_attempts = NULL;
  1584. char *pb_circ_successes = NULL;
  1585. char *pb_successful_circuits_closed = NULL;
  1586. char *pb_collapsed_circuits = NULL;
  1587. char *pb_unusable_circuits = NULL;
  1588. char *pb_timeouts = NULL;
  1589. /* Split up the entries. Put the ones we know about in strings and the
  1590. * rest in "extra". */
  1591. {
  1592. smartlist_t *entries = smartlist_new();
  1593. strmap_t *vals = strmap_new(); // Maps keyword to location
  1594. #define FIELD(f) \
  1595. strmap_set(vals, #f, &f);
  1596. FIELD(in);
  1597. FIELD(rsa_id);
  1598. FIELD(nickname);
  1599. FIELD(sampled_on);
  1600. FIELD(sampled_by);
  1601. FIELD(unlisted_since);
  1602. FIELD(listed);
  1603. FIELD(confirmed_on);
  1604. FIELD(confirmed_idx);
  1605. FIELD(pb_use_attempts);
  1606. FIELD(pb_use_successes);
  1607. FIELD(pb_circ_attempts);
  1608. FIELD(pb_circ_successes);
  1609. FIELD(pb_successful_circuits_closed);
  1610. FIELD(pb_collapsed_circuits);
  1611. FIELD(pb_unusable_circuits);
  1612. FIELD(pb_timeouts);
  1613. #undef FIELD
  1614. smartlist_split_string(entries, s, " ",
  1615. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1616. SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
  1617. const char *eq = strchr(entry, '=');
  1618. if (!eq) {
  1619. smartlist_add(extra, entry);
  1620. continue;
  1621. }
  1622. char *key = tor_strndup(entry, eq-entry);
  1623. char **target = strmap_get(vals, key);
  1624. if (target == NULL || *target != NULL) {
  1625. /* unrecognized or already set */
  1626. smartlist_add(extra, entry);
  1627. tor_free(key);
  1628. continue;
  1629. }
  1630. *target = tor_strdup(eq+1);
  1631. tor_free(key);
  1632. tor_free(entry);
  1633. } SMARTLIST_FOREACH_END(entry);
  1634. smartlist_free(entries);
  1635. strmap_free(vals, NULL);
  1636. }
  1637. entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  1638. if (in == NULL) {
  1639. log_warn(LD_CIRC, "Guard missing 'in' field");
  1640. goto err;
  1641. }
  1642. guard->selection_name = in;
  1643. in = NULL;
  1644. if (rsa_id == NULL) {
  1645. log_warn(LD_CIRC, "Guard missing RSA ID field");
  1646. goto err;
  1647. }
  1648. /* Process the identity and nickname. */
  1649. if (base16_decode(guard->identity, sizeof(guard->identity),
  1650. rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
  1651. log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
  1652. goto err;
  1653. }
  1654. if (nickname) {
  1655. strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  1656. } else {
  1657. guard->nickname[0]='$';
  1658. base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
  1659. guard->identity, DIGEST_LEN);
  1660. }
  1661. /* Process the various time fields. */
  1662. #define HANDLE_TIME(field) do { \
  1663. if (field) { \
  1664. int r = parse_iso_time_nospace(field, &field ## _time); \
  1665. if (r < 0) { \
  1666. log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
  1667. #field, escaped(field)); \
  1668. field##_time = -1; \
  1669. } \
  1670. } \
  1671. } while (0)
  1672. time_t sampled_on_time = 0;
  1673. time_t unlisted_since_time = 0;
  1674. time_t confirmed_on_time = 0;
  1675. HANDLE_TIME(sampled_on);
  1676. HANDLE_TIME(unlisted_since);
  1677. HANDLE_TIME(confirmed_on);
  1678. if (sampled_on_time <= 0)
  1679. sampled_on_time = approx_time();
  1680. if (unlisted_since_time < 0)
  1681. unlisted_since_time = 0;
  1682. if (confirmed_on_time < 0)
  1683. confirmed_on_time = 0;
  1684. #undef HANDLE_TIME
  1685. guard->sampled_on_date = sampled_on_time;
  1686. guard->unlisted_since_date = unlisted_since_time;
  1687. guard->confirmed_on_date = confirmed_on_time;
  1688. /* Take sampled_by_version verbatim. */
  1689. guard->sampled_by_version = sampled_by;
  1690. sampled_by = NULL; /* prevent free */
  1691. // XXXX -- prop271 spec deviation -- we do not require sampled_by_version
  1692. /* Listed is a boolean */
  1693. if (listed && strcmp(listed, "0"))
  1694. guard->currently_listed = 1;
  1695. /* The index is a nonnegative integer. */
  1696. guard->confirmed_idx = -1;
  1697. if (confirmed_idx) {
  1698. int ok=1;
  1699. long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
  1700. if (! ok) {
  1701. log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
  1702. escaped(confirmed_idx));
  1703. } else {
  1704. guard->confirmed_idx = (int)idx;
  1705. }
  1706. }
  1707. /* Anything we didn't recognize gets crammed together */
  1708. if (smartlist_len(extra) > 0) {
  1709. guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
  1710. }
  1711. /* initialize non-persistent fields */
  1712. guard->is_reachable = GUARD_REACHABLE_MAYBE;
  1713. #define PB_FIELD(field) \
  1714. do { \
  1715. if (pb_ ## field) { \
  1716. int ok = 1; \
  1717. double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
  1718. if (! ok) { \
  1719. log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
  1720. #field, pb_ ## field); \
  1721. } else { \
  1722. guard->pb.field = r; \
  1723. } \
  1724. } \
  1725. } while (0)
  1726. PB_FIELD(use_attempts);
  1727. PB_FIELD(use_successes);
  1728. PB_FIELD(circ_attempts);
  1729. PB_FIELD(circ_successes);
  1730. PB_FIELD(successful_circuits_closed);
  1731. PB_FIELD(collapsed_circuits);
  1732. PB_FIELD(unusable_circuits);
  1733. PB_FIELD(timeouts);
  1734. #undef PB_FIELD
  1735. pathbias_check_use_success_count(guard);
  1736. pathbias_check_close_success_count(guard);
  1737. /* We update everything on this guard later, after we've parsed
  1738. * everything. */
  1739. goto done;
  1740. err:
  1741. // only consider it an error if the guard state was totally unparseable.
  1742. entry_guard_free(guard);
  1743. guard = NULL;
  1744. done:
  1745. tor_free(in);
  1746. tor_free(rsa_id);
  1747. tor_free(nickname);
  1748. tor_free(sampled_on);
  1749. tor_free(sampled_by);
  1750. tor_free(unlisted_since);
  1751. tor_free(listed);
  1752. tor_free(confirmed_on);
  1753. tor_free(confirmed_idx);
  1754. tor_free(pb_use_attempts);
  1755. tor_free(pb_use_successes);
  1756. tor_free(pb_circ_attempts);
  1757. tor_free(pb_circ_successes);
  1758. tor_free(pb_successful_circuits_closed);
  1759. tor_free(pb_collapsed_circuits);
  1760. tor_free(pb_unusable_circuits);
  1761. tor_free(pb_timeouts);
  1762. SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
  1763. smartlist_free(extra);
  1764. return guard;
  1765. }
  1766. /**
  1767. * Replace the Guards entries in <b>state</b> with a list of all our
  1768. * non-legacy sampled guards.
  1769. */
  1770. static void
  1771. entry_guards_update_guards_in_state(or_state_t *state)
  1772. {
  1773. if (!guard_contexts)
  1774. return;
  1775. config_line_t *lines = NULL;
  1776. config_line_t **nextline = &lines;
  1777. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  1778. if (!strcmp(gs->name, "legacy"))
  1779. continue; /* This is encoded differently. */
  1780. SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
  1781. *nextline = tor_malloc_zero(sizeof(config_line_t));
  1782. (*nextline)->key = tor_strdup("Guard");
  1783. (*nextline)->value = entry_guard_encode_for_state(guard);
  1784. nextline = &(*nextline)->next;
  1785. } SMARTLIST_FOREACH_END(guard);
  1786. } SMARTLIST_FOREACH_END(gs);
  1787. config_free_lines(state->Guard);
  1788. state->Guard = lines;
  1789. }
  1790. /**
  1791. * Replace our non-legacy sampled guards from the Guards entries in
  1792. * <b>state</b>. Return 0 on success, -1 on failure. (If <b>set</b> is
  1793. * true, replace nothing -- only check whether replacing would work.)
  1794. */
  1795. static int
  1796. entry_guards_load_guards_from_state(or_state_t *state, int set)
  1797. {
  1798. const config_line_t *line = state->Guard;
  1799. int n_errors = 0;
  1800. if (!guard_contexts)
  1801. guard_contexts = smartlist_new();
  1802. /* Wipe all our existing guard info. (we shouldn't have any, but
  1803. * let's be safe.) */
  1804. if (set) {
  1805. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  1806. if (!strcmp(gs->name, "legacy"))
  1807. continue;
  1808. guard_selection_free(gs);
  1809. if (curr_guard_context == gs)
  1810. curr_guard_context = NULL;
  1811. SMARTLIST_DEL_CURRENT(guard_contexts, gs);
  1812. } SMARTLIST_FOREACH_END(gs);
  1813. }
  1814. for ( ; line != NULL; line = line->next) {
  1815. entry_guard_t *guard = entry_guard_parse_from_state(line->value);
  1816. if (guard == NULL) {
  1817. ++n_errors;
  1818. continue;
  1819. }
  1820. tor_assert(guard->selection_name);
  1821. if (!strcmp(guard->selection_name, "legacy")) {
  1822. ++n_errors;
  1823. entry_guard_free(guard);
  1824. continue;
  1825. }
  1826. if (set) {
  1827. guard_selection_t *gs;
  1828. gs = get_guard_selection_by_name(guard->selection_name, 1);
  1829. tor_assert(gs);
  1830. smartlist_add(gs->sampled_entry_guards, guard);
  1831. } else {
  1832. entry_guard_free(guard);
  1833. }
  1834. }
  1835. if (set) {
  1836. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  1837. if (!strcmp(gs->name, "legacy"))
  1838. continue;
  1839. entry_guards_update_all(gs);
  1840. } SMARTLIST_FOREACH_END(gs);
  1841. }
  1842. return n_errors ? -1 : 0;
  1843. }
  1844. /* XXXXX ----------------------------------------------- */
  1845. /* XXXXX prop271 ----- end of new-for-prop271 code ----- */
  1846. /* XXXXX ----------------------------------------------- */
  1847. /**
  1848. * @name Constants for old (pre-prop271) guard selection algorithm.
  1849. */
  1850. /**@{*/
  1851. /* Default number of entry guards in the case where the NumEntryGuards
  1852. * consensus parameter is not set */
  1853. #define DEFAULT_N_GUARDS 1
  1854. /* Minimum and maximum number of entry guards (in case the NumEntryGuards
  1855. * consensus parameter is set). */
  1856. #define MIN_N_GUARDS 1
  1857. #define MAX_N_GUARDS 10
  1858. /** Largest amount that we'll backdate chosen_on_date */
  1859. #define CHOSEN_ON_DATE_SLOP (30*86400)
  1860. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  1861. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  1862. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  1863. /**}@*/
  1864. /**
  1865. * @name Networkstatus parameters for old (pre-prop271) guard selection
  1866. */
  1867. /**@}*/
  1868. /** Choose how many entry guards or directory guards we'll use. If
  1869. * <b>for_directory</b> is true, we return how many directory guards to
  1870. * use; else we return how many entry guards to use. */
  1871. STATIC int
  1872. decide_num_guards(const or_options_t *options, int for_directory)
  1873. {
  1874. if (for_directory) {
  1875. int answer;
  1876. if (options->NumDirectoryGuards != 0)
  1877. return options->NumDirectoryGuards;
  1878. answer = networkstatus_get_param(NULL, "NumDirectoryGuards", 0, 0, 10);
  1879. if (answer) /* non-zero means use the consensus value */
  1880. return answer;
  1881. }
  1882. if (options->NumEntryGuards)
  1883. return options->NumEntryGuards;
  1884. /* Use the value from the consensus, or 3 if no guidance. */
  1885. return networkstatus_get_param(NULL, "NumEntryGuards", DEFAULT_N_GUARDS,
  1886. MIN_N_GUARDS, MAX_N_GUARDS);
  1887. }
  1888. /** Check whether the entry guard <b>e</b> is usable, given the directory
  1889. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  1890. * configuration (in <b>options</b>). Set <b>e</b>->bad_since
  1891. * accordingly. Return true iff the entry guard's status changes.
  1892. *
  1893. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  1894. */
  1895. static int
  1896. entry_guard_set_status(entry_guard_t *e, const node_t *node,
  1897. time_t now, const or_options_t *options,
  1898. const char **reason)
  1899. {
  1900. char buf[HEX_DIGEST_LEN+1];
  1901. int changed = 0;
  1902. *reason = NULL;
  1903. /* Do we want to mark this guard as bad? */
  1904. if (!node)
  1905. *reason = "unlisted";
  1906. else if (!node->is_running)
  1907. *reason = "down";
  1908. else if (options->UseBridges && (!node->ri ||
  1909. node->ri->purpose != ROUTER_PURPOSE_BRIDGE))
  1910. *reason = "not a bridge";
  1911. else if (options->UseBridges && !node_is_a_configured_bridge(node))
  1912. *reason = "not a configured bridge";
  1913. else if (!options->UseBridges && !node->is_possible_guard &&
  1914. !routerset_contains_node(options->EntryNodes,node))
  1915. *reason = "not recommended as a guard";
  1916. else if (routerset_contains_node(options->ExcludeNodes, node))
  1917. *reason = "excluded";
  1918. /* We only care about OR connection connectivity for entry guards. */
  1919. else if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
  1920. *reason = "unreachable by config";
  1921. else if (e->pb.path_bias_disabled)
  1922. *reason = "path-biased";
  1923. if (*reason && ! e->bad_since) {
  1924. /* Router is newly bad. */
  1925. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1926. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  1927. e->nickname, buf, *reason);
  1928. e->bad_since = now;
  1929. control_event_guard(e->nickname, e->identity, "BAD");
  1930. changed = 1;
  1931. } else if (!*reason && e->bad_since) {
  1932. /* There's nothing wrong with the router any more. */
  1933. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1934. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  1935. "marking as ok.", e->nickname, buf);
  1936. e->bad_since = 0;
  1937. control_event_guard(e->nickname, e->identity, "GOOD");
  1938. changed = 1;
  1939. }
  1940. if (node) {
  1941. int is_dir = node_is_dir(node);
  1942. if (options->UseBridges && node_is_a_configured_bridge(node))
  1943. is_dir = 1;
  1944. if (e->is_dir_cache != is_dir) {
  1945. e->is_dir_cache = is_dir;
  1946. changed = 1;
  1947. }
  1948. }
  1949. return changed;
  1950. }
  1951. /** Return true iff enough time has passed since we last tried to connect
  1952. * to the unreachable guard <b>e</b> that we're willing to try again. */
  1953. STATIC int
  1954. entry_is_time_to_retry(const entry_guard_t *e, time_t now)
  1955. {
  1956. struct guard_retry_period_s {
  1957. time_t period_duration;
  1958. time_t interval_during_period;
  1959. };
  1960. struct guard_retry_period_s periods[] = {
  1961. { 6*60*60, 60*60 }, /* For first 6 hrs., retry hourly; */
  1962. { 3*24*60*60, 4*60*60 }, /* Then retry every 4 hrs. until the
  1963. 3-day mark; */
  1964. { 7*24*60*60, 18*60*60 }, /* After 3 days, retry every 18 hours until
  1965. 1 week mark. */
  1966. { TIME_MAX, 36*60*60 } /* After 1 week, retry every 36 hours. */
  1967. };
  1968. time_t ith_deadline_for_retry;
  1969. time_t unreachable_for;
  1970. unsigned i;
  1971. if (e->last_attempted < e->unreachable_since)
  1972. return 1;
  1973. unreachable_for = now - e->unreachable_since;
  1974. for (i = 0; i < ARRAY_LENGTH(periods); i++) {
  1975. if (unreachable_for <= periods[i].period_duration) {
  1976. ith_deadline_for_retry = e->last_attempted +
  1977. periods[i].interval_during_period;
  1978. return (now > ith_deadline_for_retry);
  1979. }
  1980. }
  1981. return 0;
  1982. }
  1983. /** Return the node corresponding to <b>e</b>, if <b>e</b> is
  1984. * working well enough that we are willing to use it as an entry
  1985. * right now. (Else return NULL.) In particular, it must be
  1986. * - Listed as either up or never yet contacted;
  1987. * - Present in the routerlist;
  1988. * - Listed as 'stable' or 'fast' by the current dirserver consensus,
  1989. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
  1990. * (unless it's a configured EntryNode);
  1991. * - Allowed by our current ReachableORAddresses config option; and
  1992. * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
  1993. * is true).
  1994. *
  1995. * If the answer is no, set *<b>msg</b> to an explanation of why.
  1996. *
  1997. * If need_descriptor is true, only return the node if we currently have
  1998. * a descriptor (routerinfo or microdesc) for it.
  1999. */
  2000. STATIC const node_t *
  2001. entry_is_live(const entry_guard_t *e, entry_is_live_flags_t flags,
  2002. const char **msg)
  2003. {
  2004. const node_t *node;
  2005. const or_options_t *options = get_options();
  2006. int need_uptime = (flags & ENTRY_NEED_UPTIME) != 0;
  2007. int need_capacity = (flags & ENTRY_NEED_CAPACITY) != 0;
  2008. const int assume_reachable = (flags & ENTRY_ASSUME_REACHABLE) != 0;
  2009. const int need_descriptor = (flags & ENTRY_NEED_DESCRIPTOR) != 0;
  2010. tor_assert(msg);
  2011. if (e->pb.path_bias_disabled) {
  2012. *msg = "path-biased";
  2013. return NULL;
  2014. }
  2015. if (e->bad_since) {
  2016. *msg = "bad";
  2017. return NULL;
  2018. }
  2019. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  2020. if (!assume_reachable && !e->can_retry &&
  2021. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
  2022. *msg = "unreachable";
  2023. return NULL;
  2024. }
  2025. node = node_get_by_id(e->identity);
  2026. if (!node) {
  2027. *msg = "no node info";
  2028. return NULL;
  2029. }
  2030. if (need_descriptor && !node_has_descriptor(node)) {
  2031. *msg = "no descriptor";
  2032. return NULL;
  2033. }
  2034. if (get_options()->UseBridges) {
  2035. if (node_get_purpose(node) != ROUTER_PURPOSE_BRIDGE) {
  2036. *msg = "not a bridge";
  2037. return NULL;
  2038. }
  2039. if (!node_is_a_configured_bridge(node)) {
  2040. *msg = "not a configured bridge";
  2041. return NULL;
  2042. }
  2043. } else { /* !get_options()->UseBridges */
  2044. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  2045. *msg = "not general-purpose";
  2046. return NULL;
  2047. }
  2048. }
  2049. if (routerset_contains_node(options->EntryNodes, node)) {
  2050. /* they asked for it, they get it */
  2051. need_uptime = need_capacity = 0;
  2052. }
  2053. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  2054. *msg = "not fast/stable";
  2055. return NULL;
  2056. }
  2057. if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0)) {
  2058. *msg = "unreachable by config";
  2059. return NULL;
  2060. }
  2061. return node;
  2062. }
  2063. /** Return the number of entry guards that we think are usable, in the
  2064. * context of the given guard_selection_t */
  2065. int
  2066. num_live_entry_guards_for_guard_selection(guard_selection_t *gs,
  2067. int for_directory)
  2068. {
  2069. int n = 0;
  2070. const char *msg;
  2071. tor_assert(gs != NULL);
  2072. /* Set the entry node attributes we are interested in. */
  2073. entry_is_live_flags_t entry_flags = ENTRY_NEED_CAPACITY;
  2074. if (!for_directory) {
  2075. entry_flags |= ENTRY_NEED_DESCRIPTOR;
  2076. }
  2077. if (!(gs->chosen_entry_guards)) {
  2078. return 0;
  2079. }
  2080. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, entry) {
  2081. if (for_directory && !entry->is_dir_cache)
  2082. continue;
  2083. if (entry_is_live(entry, entry_flags, &msg))
  2084. ++n;
  2085. } SMARTLIST_FOREACH_END(entry);
  2086. return n;
  2087. }
  2088. /** Return the number of entry guards that we think are usable, for the
  2089. * default guard selection */
  2090. int
  2091. num_live_entry_guards(int for_directory)
  2092. {
  2093. return num_live_entry_guards_for_guard_selection(
  2094. get_guard_selection_info(), for_directory);
  2095. }
  2096. /** If <b>digest</b> matches the identity of any node in the
  2097. * entry_guards list for the provided guard selection state,
  2098. return that node. Else return NULL. */
  2099. entry_guard_t *
  2100. entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
  2101. const char *digest)
  2102. {
  2103. tor_assert(gs != NULL);
  2104. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry,
  2105. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  2106. return entry;
  2107. );
  2108. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, entry,
  2109. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  2110. return entry;
  2111. );
  2112. return NULL;
  2113. }
  2114. /** Return the node_t associated with a single entry_guard_t. May
  2115. * return NULL if the guard is not currently in the consensus. */
  2116. const node_t *
  2117. entry_guard_find_node(const entry_guard_t *guard)
  2118. {
  2119. tor_assert(guard);
  2120. return node_get_by_id(guard->identity);
  2121. }
  2122. /** If <b>digest</b> matches the identity of any node in the
  2123. * entry_guards list for the default guard selection state,
  2124. return that node. Else return NULL. */
  2125. entry_guard_t *
  2126. entry_guard_get_by_id_digest(const char *digest)
  2127. {
  2128. return entry_guard_get_by_id_digest_for_guard_selection(
  2129. get_guard_selection_info(), digest);
  2130. }
  2131. /** Dump a description of our list of entry guards in the given guard
  2132. * selection context to the log at level <b>severity</b>. */
  2133. static void
  2134. log_entry_guards_for_guard_selection(guard_selection_t *gs, int severity)
  2135. {
  2136. smartlist_t *elements = smartlist_new();
  2137. char *s;
  2138. /*
  2139. * TODO this should probably log more info about prop-271 state too
  2140. * when it's implemented.
  2141. */
  2142. tor_assert(gs != NULL);
  2143. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e)
  2144. {
  2145. const char *msg = NULL;
  2146. if (entry_is_live(e, ENTRY_NEED_CAPACITY, &msg))
  2147. smartlist_add_asprintf(elements, "%s [%s] (up %s)",
  2148. e->nickname,
  2149. hex_str(e->identity, DIGEST_LEN),
  2150. e->made_contact ? "made-contact" : "never-contacted");
  2151. else
  2152. smartlist_add_asprintf(elements, "%s [%s] (%s, %s)",
  2153. e->nickname,
  2154. hex_str(e->identity, DIGEST_LEN),
  2155. msg,
  2156. e->made_contact ? "made-contact" : "never-contacted");
  2157. }
  2158. SMARTLIST_FOREACH_END(e);
  2159. s = smartlist_join_strings(elements, ",", 0, NULL);
  2160. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  2161. smartlist_free(elements);
  2162. log_fn(severity,LD_CIRC,"%s",s);
  2163. tor_free(s);
  2164. }
  2165. /** Called when one or more guards that we would previously have used for some
  2166. * purpose are no longer in use because a higher-priority guard has become
  2167. * usable again. */
  2168. static void
  2169. control_event_guard_deferred(void)
  2170. {
  2171. /* XXXX We don't actually have a good way to figure out _how many_ entries
  2172. * are live for some purpose. We need an entry_is_even_slightly_live()
  2173. * function for this to work right. NumEntryGuards isn't reliable: if we
  2174. * need guards with weird properties, we can have more than that number
  2175. * live.
  2176. **/
  2177. #if 0
  2178. int n = 0;
  2179. const char *msg;
  2180. const or_options_t *options = get_options();
  2181. if (!entry_guards)
  2182. return;
  2183. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2184. {
  2185. if (entry_is_live(entry, 0, 1, 0, &msg)) {
  2186. if (n++ == options->NumEntryGuards) {
  2187. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  2188. return;
  2189. }
  2190. }
  2191. });
  2192. #endif
  2193. }
  2194. /** Add a new (preferably stable and fast) router to our chosen_entry_guards
  2195. * list for the supplied guard selection. Return a pointer to the router if
  2196. * we succeed, or NULL if we can't find any more suitable entries.
  2197. *
  2198. * If <b>chosen</b> is defined, use that one, and if it's not
  2199. * already in our entry_guards list, put it at the *beginning*.
  2200. * Else, put the one we pick at the end of the list. */
  2201. STATIC const node_t *
  2202. add_an_entry_guard(guard_selection_t *gs,
  2203. const node_t *chosen, int reset_status, int prepend,
  2204. int for_discovery, int for_directory)
  2205. {
  2206. const node_t *node;
  2207. entry_guard_t *entry;
  2208. tor_assert(gs != NULL);
  2209. tor_assert(gs->chosen_entry_guards != NULL);
  2210. if (chosen) {
  2211. node = chosen;
  2212. entry = entry_guard_get_by_id_digest_for_guard_selection(gs,
  2213. node->identity);
  2214. if (entry) {
  2215. if (reset_status) {
  2216. entry->bad_since = 0;
  2217. entry->can_retry = 1;
  2218. }
  2219. entry->is_dir_cache = node_is_dir(node);
  2220. if (get_options()->UseBridges && node_is_a_configured_bridge(node))
  2221. entry->is_dir_cache = 1;
  2222. return NULL;
  2223. }
  2224. } else if (!for_directory) {
  2225. node = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL, NULL);
  2226. if (!node)
  2227. return NULL;
  2228. } else {
  2229. const routerstatus_t *rs;
  2230. rs = router_pick_directory_server(MICRODESC_DIRINFO|V3_DIRINFO,
  2231. PDS_FOR_GUARD);
  2232. if (!rs)
  2233. return NULL;
  2234. node = node_get_by_id(rs->identity_digest);
  2235. if (!node)
  2236. return NULL;
  2237. }
  2238. if (entry_guard_get_by_id_digest_for_guard_selection(gs, node->identity)
  2239. != NULL) {
  2240. log_info(LD_CIRC, "I was about to add a duplicate entry guard.");
  2241. /* This can happen if we choose a guard, then the node goes away, then
  2242. * comes back. */
  2243. return NULL;
  2244. }
  2245. entry = tor_malloc_zero(sizeof(entry_guard_t));
  2246. log_info(LD_CIRC, "Chose %s as new entry guard.",
  2247. node_describe(node));
  2248. strlcpy(entry->nickname, node_get_nickname(node), sizeof(entry->nickname));
  2249. memcpy(entry->identity, node->identity, DIGEST_LEN);
  2250. entry->is_dir_cache = node_is_dir(node);
  2251. if (get_options()->UseBridges && node_is_a_configured_bridge(node))
  2252. entry->is_dir_cache = 1;
  2253. /* Choose expiry time smudged over the past month. The goal here
  2254. * is to a) spread out when Tor clients rotate their guards, so they
  2255. * don't all select them on the same day, and b) avoid leaving a
  2256. * precise timestamp in the state file about when we first picked
  2257. * this guard. For details, see the Jan 2010 or-dev thread. */
  2258. time_t now = time(NULL);
  2259. entry->chosen_on_date = crypto_rand_time_range(now - 3600*24*30, now);
  2260. entry->chosen_by_version = tor_strdup(VERSION);
  2261. /* Are we picking this guard because all of our current guards are
  2262. * down so we need another one (for_discovery is 1), or because we
  2263. * decided we need more variety in our guard list (for_discovery is 0)?
  2264. *
  2265. * Currently we hack this behavior into place by setting "made_contact"
  2266. * for guards of the latter variety, so we'll be willing to use any of
  2267. * them right off the bat.
  2268. */
  2269. if (!for_discovery)
  2270. entry->made_contact = 1;
  2271. if (prepend)
  2272. smartlist_insert(gs->chosen_entry_guards, 0, entry);
  2273. else
  2274. smartlist_add(gs->chosen_entry_guards, entry);
  2275. control_event_guard(entry->nickname, entry->identity, "NEW");
  2276. control_event_guard_deferred();
  2277. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2278. return node;
  2279. }
  2280. /** Entry point for bridges.c to add a bridge as guard.
  2281. *
  2282. * XXXX prop271 refactor.*/
  2283. void
  2284. add_bridge_as_entry_guard(guard_selection_t *gs,
  2285. const node_t *chosen)
  2286. {
  2287. add_an_entry_guard(gs, chosen, 1, 1, 0, 0);
  2288. }
  2289. /**
  2290. * Return the minimum lifetime of working entry guard, in seconds,
  2291. * as given in the consensus networkstatus. (Plus CHOSEN_ON_DATE_SLOP,
  2292. * so that we can do the chosen_on_date randomization while achieving the
  2293. * desired minimum lifetime.)
  2294. */
  2295. static int32_t
  2296. guards_get_lifetime(void)
  2297. {
  2298. const or_options_t *options = get_options();
  2299. #define DFLT_GUARD_LIFETIME (86400 * 60) /* Two months. */
  2300. #define MIN_GUARD_LIFETIME (86400 * 30) /* One months. */
  2301. #define MAX_GUARD_LIFETIME (86400 * 1826) /* Five years. */
  2302. if (options->GuardLifetime >= 1) {
  2303. return CLAMP(MIN_GUARD_LIFETIME,
  2304. options->GuardLifetime,
  2305. MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
  2306. }
  2307. return networkstatus_get_param(NULL, "GuardLifetime",
  2308. DFLT_GUARD_LIFETIME,
  2309. MIN_GUARD_LIFETIME,
  2310. MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
  2311. }
  2312. /** If the use of entry guards is configured, choose more entry guards
  2313. * until we have enough in the list. */
  2314. static void
  2315. pick_entry_guards(guard_selection_t *gs,
  2316. const or_options_t *options,
  2317. int for_directory)
  2318. {
  2319. int changed = 0;
  2320. const int num_needed = decide_num_guards(options, for_directory);
  2321. tor_assert(gs != NULL);
  2322. tor_assert(gs->chosen_entry_guards != NULL);
  2323. while (num_live_entry_guards_for_guard_selection(gs, for_directory)
  2324. < num_needed) {
  2325. if (!add_an_entry_guard(gs, NULL, 0, 0, 0, for_directory))
  2326. break;
  2327. changed = 1;
  2328. }
  2329. if (changed)
  2330. entry_guards_changed_for_guard_selection(gs);
  2331. }
  2332. /** Release all storage held by <b>e</b>. */
  2333. STATIC void
  2334. entry_guard_free(entry_guard_t *e)
  2335. {
  2336. if (!e)
  2337. return;
  2338. entry_guard_handles_clear(e);
  2339. tor_free(e->chosen_by_version);
  2340. tor_free(e->sampled_by_version);
  2341. tor_free(e->extra_state_fields);
  2342. tor_free(e->selection_name);
  2343. tor_free(e);
  2344. }
  2345. /** Remove from a guard selection context any entry guard which was selected
  2346. * by an unknown version of Tor, or which was selected by a version of Tor
  2347. * that's known to select entry guards badly, or which was selected more 2
  2348. * months ago. */
  2349. /* XXXX The "obsolete guards" and "chosen long ago guards" things should
  2350. * probably be different functions. */
  2351. static int
  2352. remove_obsolete_entry_guards(guard_selection_t *gs, time_t now)
  2353. {
  2354. int changed = 0, i;
  2355. int32_t guard_lifetime = guards_get_lifetime();
  2356. tor_assert(gs != NULL);
  2357. if (!(gs->chosen_entry_guards)) goto done;
  2358. for (i = 0; i < smartlist_len(gs->chosen_entry_guards); ++i) {
  2359. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, i);
  2360. const char *ver = entry->chosen_by_version;
  2361. const char *msg = NULL;
  2362. tor_version_t v;
  2363. int version_is_bad = 0, date_is_bad = 0;
  2364. if (!ver) {
  2365. msg = "does not say what version of Tor it was selected by";
  2366. version_is_bad = 1;
  2367. } else if (tor_version_parse(ver, &v)) {
  2368. msg = "does not seem to be from any recognized version of Tor";
  2369. version_is_bad = 1;
  2370. }
  2371. if (!version_is_bad && entry->chosen_on_date + guard_lifetime < now) {
  2372. /* It's been too long since the date listed in our state file. */
  2373. msg = "was selected several months ago";
  2374. date_is_bad = 1;
  2375. }
  2376. if (version_is_bad || date_is_bad) { /* we need to drop it */
  2377. char dbuf[HEX_DIGEST_LEN+1];
  2378. tor_assert(msg);
  2379. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2380. log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
  2381. "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
  2382. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  2383. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2384. entry_guard_free(entry);
  2385. smartlist_del_keeporder(gs->chosen_entry_guards, i--);
  2386. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2387. changed = 1;
  2388. }
  2389. }
  2390. done:
  2391. return changed ? 1 : 0;
  2392. }
  2393. /** Remove all entry guards from this guard selection context that have
  2394. * been down or unlisted for so long that we don't think they'll come up
  2395. * again. Return 1 if we removed any, or 0 if we did nothing. */
  2396. static int
  2397. remove_dead_entry_guards(guard_selection_t *gs, time_t now)
  2398. {
  2399. char dbuf[HEX_DIGEST_LEN+1];
  2400. char tbuf[ISO_TIME_LEN+1];
  2401. int i;
  2402. int changed = 0;
  2403. tor_assert(gs != NULL);
  2404. if (!(gs->chosen_entry_guards)) goto done;
  2405. for (i = 0; i < smartlist_len(gs->chosen_entry_guards); ) {
  2406. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, i);
  2407. if (entry->bad_since &&
  2408. ! entry->pb.path_bias_disabled &&
  2409. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  2410. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2411. format_local_iso_time(tbuf, entry->bad_since);
  2412. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  2413. "since %s local time; removing.",
  2414. entry->nickname, dbuf, tbuf);
  2415. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2416. entry_guard_free(entry);
  2417. smartlist_del_keeporder(gs->chosen_entry_guards, i);
  2418. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2419. changed = 1;
  2420. } else
  2421. ++i;
  2422. }
  2423. done:
  2424. return changed ? 1 : 0;
  2425. }
  2426. /** Remove all currently listed entry guards for a given guard selection
  2427. * context */
  2428. void
  2429. remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
  2430. {
  2431. char dbuf[HEX_DIGEST_LEN+1];
  2432. tor_assert(gs != NULL);
  2433. if (gs->chosen_entry_guards) {
  2434. while (smartlist_len(gs->chosen_entry_guards)) {
  2435. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, 0);
  2436. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  2437. log_info(LD_CIRC, "Entry guard '%s' (%s) has been dropped.",
  2438. entry->nickname, dbuf);
  2439. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2440. entry_guard_free(entry);
  2441. smartlist_del(gs->chosen_entry_guards, 0);
  2442. }
  2443. }
  2444. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2445. entry_guards_changed_for_guard_selection(gs);
  2446. }
  2447. /** Remove all currently listed entry guards. So new ones will be chosen. */
  2448. void
  2449. remove_all_entry_guards(void)
  2450. {
  2451. remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
  2452. }
  2453. /** A new directory or router-status has arrived; update the down/listed
  2454. * status of the entry guards.
  2455. *
  2456. * An entry is 'down' if the directory lists it as nonrunning.
  2457. * An entry is 'unlisted' if the directory doesn't include it.
  2458. *
  2459. * Don't call this on startup; only on a fresh download. Otherwise we'll
  2460. * think that things are unlisted.
  2461. */
  2462. void
  2463. entry_guards_compute_status_for_guard_selection(guard_selection_t *gs,
  2464. const or_options_t *options,
  2465. time_t now)
  2466. {
  2467. int changed = 0;
  2468. digestmap_t *reasons;
  2469. if ((!gs) || !(gs->chosen_entry_guards))
  2470. return;
  2471. if (!get_options()->UseDeprecatedGuardAlgorithm)
  2472. return;
  2473. if (options->EntryNodes) /* reshuffle the entry guard list if needed */
  2474. entry_nodes_should_be_added();
  2475. reasons = digestmap_new();
  2476. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, entry)
  2477. {
  2478. const node_t *r = node_get_by_id(entry->identity);
  2479. const char *reason = NULL;
  2480. if (entry_guard_set_status(entry, r, now, options, &reason))
  2481. changed = 1;
  2482. if (entry->bad_since)
  2483. tor_assert(reason);
  2484. if (reason)
  2485. digestmap_set(reasons, entry->identity, (char*)reason);
  2486. }
  2487. SMARTLIST_FOREACH_END(entry);
  2488. if (remove_dead_entry_guards(gs, now))
  2489. changed = 1;
  2490. if (remove_obsolete_entry_guards(gs, now))
  2491. changed = 1;
  2492. if (changed) {
  2493. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *,
  2494. entry) {
  2495. const char *reason = digestmap_get(reasons, entry->identity);
  2496. const char *live_msg = "";
  2497. const node_t *r = entry_is_live(entry, ENTRY_NEED_CAPACITY, &live_msg);
  2498. log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
  2499. entry->nickname,
  2500. hex_str(entry->identity, DIGEST_LEN),
  2501. entry->unreachable_since ? "unreachable" : "reachable",
  2502. entry->bad_since ? "unusable" : "usable",
  2503. reason ? ", ": "",
  2504. reason ? reason : "",
  2505. r ? "live" : "not live / ",
  2506. r ? "" : live_msg);
  2507. } SMARTLIST_FOREACH_END(entry);
  2508. log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
  2509. num_live_entry_guards_for_guard_selection(gs, 0),
  2510. smartlist_len(gs->chosen_entry_guards));
  2511. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2512. entry_guards_changed_for_guard_selection(gs);
  2513. }
  2514. digestmap_free(reasons, NULL);
  2515. }
  2516. /** A new directory or router-status has arrived; update the down/listed
  2517. * status of the entry guards.
  2518. *
  2519. * An entry is 'down' if the directory lists it as nonrunning.
  2520. * An entry is 'unlisted' if the directory doesn't include it.
  2521. *
  2522. * Don't call this on startup; only on a fresh download. Otherwise we'll
  2523. * think that things are unlisted.
  2524. */
  2525. void
  2526. entry_guards_compute_status(const or_options_t *options, time_t now)
  2527. {
  2528. entry_guards_compute_status_for_guard_selection(get_guard_selection_info(),
  2529. options, now);
  2530. }
  2531. /** Called when a connection to an OR with the identity digest <b>digest</b>
  2532. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  2533. * If the OR is an entry, change that entry's up/down status.
  2534. * Return 0 normally, or -1 if we want to tear down the new connection.
  2535. *
  2536. * If <b>mark_relay_status</b>, also call router_set_status() on this
  2537. * relay.
  2538. */
  2539. /* XXX We could change succeeded and mark_relay_status into 'int flags'.
  2540. * Too many boolean arguments is a recipe for confusion.
  2541. */
  2542. int
  2543. entry_guard_register_connect_status_for_guard_selection(
  2544. guard_selection_t *gs, const char *digest, int succeeded,
  2545. int mark_relay_status, time_t now)
  2546. {
  2547. int changed = 0;
  2548. int refuse_conn = 0;
  2549. int first_contact = 0;
  2550. entry_guard_t *entry = NULL;
  2551. int idx = -1;
  2552. char buf[HEX_DIGEST_LEN+1];
  2553. if (!(gs) || !(gs->chosen_entry_guards)) {
  2554. return 0;
  2555. }
  2556. if (! get_options()->UseDeprecatedGuardAlgorithm) {
  2557. return 0;
  2558. }
  2559. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  2560. tor_assert(e);
  2561. if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
  2562. entry = e;
  2563. idx = e_sl_idx;
  2564. break;
  2565. }
  2566. } SMARTLIST_FOREACH_END(e);
  2567. if (!entry)
  2568. return 0;
  2569. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  2570. if (succeeded) {
  2571. if (entry->unreachable_since) {
  2572. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  2573. entry->nickname, buf);
  2574. entry->can_retry = 0;
  2575. entry->unreachable_since = 0;
  2576. entry->last_attempted = now;
  2577. control_event_guard(entry->nickname, entry->identity, "UP");
  2578. changed = 1;
  2579. }
  2580. if (!entry->made_contact) {
  2581. entry->made_contact = 1;
  2582. first_contact = changed = 1;
  2583. }
  2584. } else { /* ! succeeded */
  2585. if (!entry->made_contact) {
  2586. /* We've never connected to this one. */
  2587. log_info(LD_CIRC,
  2588. "Connection to never-contacted entry guard '%s' (%s) failed. "
  2589. "Removing from the list. %d/%d entry guards usable/new.",
  2590. entry->nickname, buf,
  2591. num_live_entry_guards_for_guard_selection(gs, 0) - 1,
  2592. smartlist_len(gs->chosen_entry_guards)-1);
  2593. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  2594. entry_guard_free(entry);
  2595. smartlist_del_keeporder(gs->chosen_entry_guards, idx);
  2596. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2597. changed = 1;
  2598. } else if (!entry->unreachable_since) {
  2599. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  2600. "Marking as unreachable.", entry->nickname, buf);
  2601. entry->unreachable_since = entry->last_attempted = now;
  2602. control_event_guard(entry->nickname, entry->identity, "DOWN");
  2603. changed = 1;
  2604. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2605. } else {
  2606. char tbuf[ISO_TIME_LEN+1];
  2607. format_iso_time(tbuf, entry->unreachable_since);
  2608. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  2609. "'%s' (%s). It has been unreachable since %s.",
  2610. entry->nickname, buf, tbuf);
  2611. entry->last_attempted = now;
  2612. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2613. }
  2614. }
  2615. /* if the caller asked us to, also update the is_running flags for this
  2616. * relay */
  2617. if (mark_relay_status)
  2618. router_set_status(digest, succeeded);
  2619. if (first_contact) {
  2620. /* We've just added a new long-term entry guard. Perhaps the network just
  2621. * came back? We should give our earlier entries another try too,
  2622. * and close this connection so we don't use it before we've given
  2623. * the others a shot. */
  2624. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  2625. if (e == entry)
  2626. break;
  2627. if (e->made_contact) {
  2628. const char *msg;
  2629. const node_t *r = entry_is_live(e,
  2630. ENTRY_NEED_CAPACITY | ENTRY_ASSUME_REACHABLE,
  2631. &msg);
  2632. if (r && e->unreachable_since) {
  2633. refuse_conn = 1;
  2634. e->can_retry = 1;
  2635. }
  2636. }
  2637. } SMARTLIST_FOREACH_END(e);
  2638. if (refuse_conn) {
  2639. log_info(LD_CIRC,
  2640. "Connected to new entry guard '%s' (%s). Marking earlier "
  2641. "entry guards up. %d/%d entry guards usable/new.",
  2642. entry->nickname, buf,
  2643. num_live_entry_guards_for_guard_selection(gs, 0),
  2644. smartlist_len(gs->chosen_entry_guards));
  2645. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  2646. changed = 1;
  2647. }
  2648. }
  2649. if (changed)
  2650. entry_guards_changed_for_guard_selection(gs);
  2651. return refuse_conn ? -1 : 0;
  2652. }
  2653. /** Called when a connection to an OR with the identity digest <b>digest</b>
  2654. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  2655. * If the OR is an entry, change that entry's up/down status in the default
  2656. * guard selection context.
  2657. * Return 0 normally, or -1 if we want to tear down the new connection.
  2658. *
  2659. * If <b>mark_relay_status</b>, also call router_set_status() on this
  2660. * relay.
  2661. */
  2662. int
  2663. entry_guard_register_connect_status(const char *digest, int succeeded,
  2664. int mark_relay_status, time_t now)
  2665. {
  2666. return entry_guard_register_connect_status_for_guard_selection(
  2667. get_guard_selection_info(), digest, succeeded, mark_relay_status, now);
  2668. }
  2669. /** Called when the value of EntryNodes changes in our configuration. */
  2670. void
  2671. entry_nodes_should_be_added_for_guard_selection(guard_selection_t *gs)
  2672. {
  2673. tor_assert(gs != NULL);
  2674. log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
  2675. "relays at the front of the entry guard list.");
  2676. gs->should_add_entry_nodes = 1;
  2677. }
  2678. /** Called when the value of EntryNodes changes in our configuration. */
  2679. void
  2680. entry_nodes_should_be_added(void)
  2681. {
  2682. entry_nodes_should_be_added_for_guard_selection(
  2683. get_guard_selection_info());
  2684. }
  2685. /** Adjust the entry guards list so that it only contains entries from
  2686. * EntryNodes, adding new entries from EntryNodes to the list as needed. */
  2687. STATIC void
  2688. entry_guards_set_from_config(guard_selection_t *gs,
  2689. const or_options_t *options)
  2690. {
  2691. smartlist_t *entry_nodes, *worse_entry_nodes, *entry_fps;
  2692. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  2693. const int numentryguards = decide_num_guards(options, 0);
  2694. tor_assert(gs != NULL);
  2695. tor_assert(gs->chosen_entry_guards != NULL);
  2696. gs->should_add_entry_nodes = 0;
  2697. if (!options->EntryNodes) {
  2698. /* It's possible that a controller set EntryNodes, thus making
  2699. * should_add_entry_nodes set, then cleared it again, all before the
  2700. * call to choose_random_entry() that triggered us. If so, just return.
  2701. */
  2702. return;
  2703. }
  2704. {
  2705. char *string = routerset_to_string(options->EntryNodes);
  2706. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
  2707. tor_free(string);
  2708. }
  2709. entry_nodes = smartlist_new();
  2710. worse_entry_nodes = smartlist_new();
  2711. entry_fps = smartlist_new();
  2712. old_entry_guards_on_list = smartlist_new();
  2713. old_entry_guards_not_on_list = smartlist_new();
  2714. /* Split entry guards into those on the list and those not. */
  2715. routerset_get_all_nodes(entry_nodes, options->EntryNodes,
  2716. options->ExcludeNodes, 0);
  2717. SMARTLIST_FOREACH(entry_nodes, const node_t *,node,
  2718. smartlist_add(entry_fps, (void*)node->identity));
  2719. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e, {
  2720. if (smartlist_contains_digest(entry_fps, e->identity))
  2721. smartlist_add(old_entry_guards_on_list, e);
  2722. else
  2723. smartlist_add(old_entry_guards_not_on_list, e);
  2724. });
  2725. /* Remove all currently configured guard nodes, excluded nodes, unreachable
  2726. * nodes, or non-Guard nodes from entry_nodes. */
  2727. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  2728. if (entry_guard_get_by_id_digest_for_guard_selection(gs,
  2729. node->identity)) {
  2730. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  2731. continue;
  2732. } else if (routerset_contains_node(options->ExcludeNodes, node)) {
  2733. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  2734. continue;
  2735. } else if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION,
  2736. 0)) {
  2737. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  2738. continue;
  2739. } else if (! node->is_possible_guard) {
  2740. smartlist_add(worse_entry_nodes, (node_t*)node);
  2741. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  2742. }
  2743. } SMARTLIST_FOREACH_END(node);
  2744. /* Now build the new entry_guards list. */
  2745. smartlist_clear(gs->chosen_entry_guards);
  2746. /* First, the previously configured guards that are in EntryNodes. */
  2747. smartlist_add_all(gs->chosen_entry_guards, old_entry_guards_on_list);
  2748. /* Next, scramble the rest of EntryNodes, putting the guards first. */
  2749. smartlist_shuffle(entry_nodes);
  2750. smartlist_shuffle(worse_entry_nodes);
  2751. smartlist_add_all(entry_nodes, worse_entry_nodes);
  2752. /* Next, the rest of EntryNodes */
  2753. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  2754. add_an_entry_guard(gs, node, 0, 0, 1, 0);
  2755. if (smartlist_len(gs->chosen_entry_guards) > numentryguards * 10)
  2756. break;
  2757. } SMARTLIST_FOREACH_END(node);
  2758. log_notice(LD_GENERAL, "%d entries in guards",
  2759. smartlist_len(gs->chosen_entry_guards));
  2760. /* Finally, free the remaining previously configured guards that are not in
  2761. * EntryNodes. */
  2762. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  2763. entry_guard_free(e));
  2764. smartlist_free(entry_nodes);
  2765. smartlist_free(worse_entry_nodes);
  2766. smartlist_free(entry_fps);
  2767. smartlist_free(old_entry_guards_on_list);
  2768. smartlist_free(old_entry_guards_not_on_list);
  2769. entry_guards_changed_for_guard_selection(gs);
  2770. }
  2771. /** Return 0 if we're fine adding arbitrary routers out of the
  2772. * directory to our entry guard list, or return 1 if we have a
  2773. * list already and we must stick to it.
  2774. */
  2775. int
  2776. entry_list_is_constrained(const or_options_t *options)
  2777. {
  2778. if (options->EntryNodes)
  2779. return 1;
  2780. if (options->UseBridges)
  2781. return 1;
  2782. return 0;
  2783. }
  2784. /** Pick a live (up and listed) entry guard from entry_guards. If
  2785. * <b>state</b> is non-NULL, this is for a specific circuit --
  2786. * make sure not to pick this circuit's exit or any node in the
  2787. * exit's family. If <b>state</b> is NULL, we're looking for a random
  2788. * guard (likely a bridge). If <b>dirinfo</b> is not NO_DIRINFO (zero),
  2789. * then only select from nodes that know how to answer directory questions
  2790. * of that type. */
  2791. const node_t *
  2792. choose_random_entry(cpath_build_state_t *state)
  2793. {
  2794. tor_assert(get_options()->UseDeprecatedGuardAlgorithm);
  2795. return choose_random_entry_impl(get_guard_selection_info(),
  2796. state, 0, NO_DIRINFO, NULL);
  2797. }
  2798. /** Pick a live (up and listed) directory guard from entry_guards for
  2799. * downloading information of type <b>type</b>. */
  2800. const node_t *
  2801. choose_random_dirguard(dirinfo_type_t type)
  2802. {
  2803. tor_assert(get_options()->UseDeprecatedGuardAlgorithm);
  2804. return choose_random_entry_impl(get_guard_selection_info(),
  2805. NULL, 1, type, NULL);
  2806. }
  2807. /** Return the number of bridges that have descriptors that are marked with
  2808. * purpose 'bridge' and are running.
  2809. */
  2810. int
  2811. num_bridges_usable(void)
  2812. {
  2813. tor_assert(get_options()->UseDeprecatedGuardAlgorithm);
  2814. int n_options = 0;
  2815. tor_assert(get_options()->UseBridges);
  2816. (void) choose_random_entry_impl(get_guard_selection_info(),
  2817. NULL, 0, 0, &n_options);
  2818. return n_options;
  2819. }
  2820. /** Filter <b>all_entry_guards</b> for usable entry guards and put them
  2821. * in <b>live_entry_guards</b>. We filter based on whether the node is
  2822. * currently alive, and on whether it satisfies the restrictions
  2823. * imposed by the other arguments of this function.
  2824. *
  2825. * We don't place more guards than NumEntryGuards in <b>live_entry_guards</b>.
  2826. *
  2827. * If <b>chosen_exit</b> is set, it contains the exit node of this
  2828. * circuit. Make sure to not use it or its family as an entry guard.
  2829. *
  2830. * If <b>need_uptime</b> is set, we are looking for a stable entry guard.
  2831. * if <b>need_capacity</b> is set, we are looking for a fast entry guard.
  2832. *
  2833. * The rest of the arguments are the same as in choose_random_entry_impl().
  2834. *
  2835. * Return 1 if we should choose a guard right away. Return 0 if we
  2836. * should try to add more nodes to our list before deciding on a
  2837. * guard.
  2838. */
  2839. STATIC int
  2840. populate_live_entry_guards(smartlist_t *live_entry_guards,
  2841. const smartlist_t *all_entry_guards,
  2842. const node_t *chosen_exit,
  2843. dirinfo_type_t dirinfo_type,
  2844. int for_directory,
  2845. int need_uptime, int need_capacity)
  2846. {
  2847. const or_options_t *options = get_options();
  2848. const node_t *node = NULL;
  2849. const int num_needed = decide_num_guards(options, for_directory);
  2850. smartlist_t *exit_family = smartlist_new();
  2851. int retval = 0;
  2852. entry_is_live_flags_t entry_flags = 0;
  2853. (void) dirinfo_type;
  2854. { /* Set the flags we want our entry node to have */
  2855. if (need_uptime) {
  2856. entry_flags |= ENTRY_NEED_UPTIME;
  2857. }
  2858. if (need_capacity) {
  2859. entry_flags |= ENTRY_NEED_CAPACITY;
  2860. }
  2861. if (!for_directory) {
  2862. entry_flags |= ENTRY_NEED_DESCRIPTOR;
  2863. }
  2864. }
  2865. tor_assert(all_entry_guards);
  2866. if (chosen_exit) {
  2867. nodelist_add_node_and_family(exit_family, chosen_exit);
  2868. }
  2869. SMARTLIST_FOREACH_BEGIN(all_entry_guards, const entry_guard_t *, entry) {
  2870. const char *msg;
  2871. node = entry_is_live(entry, entry_flags, &msg);
  2872. if (!node)
  2873. continue; /* down, no point */
  2874. if (for_directory) {
  2875. if (!entry->is_dir_cache)
  2876. continue; /* We need a directory and didn't get one. */
  2877. }
  2878. if (node == chosen_exit)
  2879. continue; /* don't pick the same node for entry and exit */
  2880. if (smartlist_contains(exit_family, node))
  2881. continue; /* avoid relays that are family members of our exit */
  2882. smartlist_add(live_entry_guards, (void*)node);
  2883. if (!entry->made_contact) {
  2884. /* Always start with the first not-yet-contacted entry
  2885. * guard. Otherwise we might add several new ones, pick
  2886. * the second new one, and now we've expanded our entry
  2887. * guard list without needing to. */
  2888. retval = 1;
  2889. goto done;
  2890. }
  2891. if (smartlist_len(live_entry_guards) >= num_needed) {
  2892. retval = 1;
  2893. goto done; /* We picked enough entry guards. Done! */
  2894. }
  2895. } SMARTLIST_FOREACH_END(entry);
  2896. done:
  2897. smartlist_free(exit_family);
  2898. return retval;
  2899. }
  2900. /** Pick a node to be used as the entry guard of a circuit, relative to
  2901. * a supplied guard selection context.
  2902. *
  2903. * If <b>state</b> is set, it contains the information we know about
  2904. * the upcoming circuit.
  2905. *
  2906. * If <b>for_directory</b> is set, we are looking for a directory guard.
  2907. *
  2908. * <b>dirinfo_type</b> contains the kind of directory information we
  2909. * are looking for in our node, or NO_DIRINFO (zero) if we are not
  2910. * looking for any particular directory information (when set to
  2911. * NO_DIRINFO, the <b>dirinfo_type</b> filter is ignored).
  2912. *
  2913. * If <b>n_options_out</b> is set, we set it to the number of
  2914. * candidate guard nodes we had before picking a specific guard node.
  2915. *
  2916. * On success, return the node that should be used as the entry guard
  2917. * of the circuit. Return NULL if no such node could be found.
  2918. *
  2919. * Helper for choose_random{entry,dirguard}.
  2920. */
  2921. static const node_t *
  2922. choose_random_entry_impl(guard_selection_t *gs,
  2923. cpath_build_state_t *state, int for_directory,
  2924. dirinfo_type_t dirinfo_type, int *n_options_out)
  2925. {
  2926. const or_options_t *options = get_options();
  2927. smartlist_t *live_entry_guards = smartlist_new();
  2928. const node_t *chosen_exit =
  2929. state?build_state_get_exit_node(state) : NULL;
  2930. const node_t *node = NULL;
  2931. int need_uptime = state ? state->need_uptime : 0;
  2932. int need_capacity = state ? state->need_capacity : 0;
  2933. int preferred_min = 0;
  2934. const int num_needed = decide_num_guards(options, for_directory);
  2935. int retval = 0;
  2936. tor_assert(gs != NULL);
  2937. tor_assert(gs->chosen_entry_guards != NULL);
  2938. if (n_options_out)
  2939. *n_options_out = 0;
  2940. if (gs->should_add_entry_nodes)
  2941. entry_guards_set_from_config(gs, options);
  2942. if (!entry_list_is_constrained(options) &&
  2943. smartlist_len(gs->chosen_entry_guards) < num_needed)
  2944. pick_entry_guards(gs, options, for_directory);
  2945. retry:
  2946. smartlist_clear(live_entry_guards);
  2947. /* Populate the list of live entry guards so that we pick one of
  2948. them. */
  2949. retval = populate_live_entry_guards(live_entry_guards,
  2950. gs->chosen_entry_guards,
  2951. chosen_exit,
  2952. dirinfo_type,
  2953. for_directory,
  2954. need_uptime, need_capacity);
  2955. if (retval == 1) { /* We should choose a guard right now. */
  2956. goto choose_and_finish;
  2957. }
  2958. if (entry_list_is_constrained(options)) {
  2959. /* If we prefer the entry nodes we've got, and we have at least
  2960. * one choice, that's great. Use it. */
  2961. preferred_min = 1;
  2962. } else {
  2963. /* Try to have at least 2 choices available. This way we don't
  2964. * get stuck with a single live-but-crummy entry and just keep
  2965. * using it.
  2966. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  2967. preferred_min = 2;
  2968. }
  2969. if (smartlist_len(live_entry_guards) < preferred_min) {
  2970. if (!entry_list_is_constrained(options)) {
  2971. /* still no? try adding a new entry then */
  2972. /* XXX if guard doesn't imply fast and stable, then we need
  2973. * to tell add_an_entry_guard below what we want, or it might
  2974. * be a long time til we get it. -RD */
  2975. node = add_an_entry_guard(gs, NULL, 0, 0, 1, for_directory);
  2976. if (node) {
  2977. entry_guards_changed_for_guard_selection(gs);
  2978. /* XXX we start over here in case the new node we added shares
  2979. * a family with our exit node. There's a chance that we'll just
  2980. * load up on entry guards here, if the network we're using is
  2981. * one big family. Perhaps we should teach add_an_entry_guard()
  2982. * to understand nodes-to-avoid-if-possible? -RD */
  2983. goto retry;
  2984. }
  2985. }
  2986. if (!node && need_uptime) {
  2987. need_uptime = 0; /* try without that requirement */
  2988. goto retry;
  2989. }
  2990. if (!node && need_capacity) {
  2991. /* still no? last attempt, try without requiring capacity */
  2992. need_capacity = 0;
  2993. goto retry;
  2994. }
  2995. /* live_entry_guards may be empty below. Oh well, we tried. */
  2996. }
  2997. choose_and_finish:
  2998. if (entry_list_is_constrained(options)) {
  2999. /* We need to weight by bandwidth, because our bridges or entryguards
  3000. * were not already selected proportional to their bandwidth. */
  3001. node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  3002. } else {
  3003. /* We choose uniformly at random here, because choose_good_entry_server()
  3004. * already weights its choices by bandwidth, so we don't want to
  3005. * *double*-weight our guard selection. */
  3006. node = smartlist_choose(live_entry_guards);
  3007. }
  3008. if (n_options_out)
  3009. *n_options_out = smartlist_len(live_entry_guards);
  3010. smartlist_free(live_entry_guards);
  3011. return node;
  3012. }
  3013. static void
  3014. pathbias_check_use_success_count(entry_guard_t *node)
  3015. {
  3016. const or_options_t *options = get_options();
  3017. const double EPSILON = 1.0e-9;
  3018. /* Note: We rely on the < comparison here to allow us to set a 0
  3019. * rate and disable the feature entirely. If refactoring, don't
  3020. * change to <= */
  3021. if (node->pb.use_attempts > EPSILON &&
  3022. pathbias_get_use_success_count(node)/node->pb.use_attempts
  3023. < pathbias_get_extreme_use_rate(options) &&
  3024. pathbias_get_dropguards(options)) {
  3025. node->pb.path_bias_disabled = 1;
  3026. log_info(LD_GENERAL,
  3027. "Path use bias is too high (%f/%f); disabling node %s",
  3028. node->pb.circ_successes, node->pb.circ_attempts,
  3029. node->nickname);
  3030. }
  3031. }
  3032. static void
  3033. pathbias_check_close_success_count(entry_guard_t *node)
  3034. {
  3035. const or_options_t *options = get_options();
  3036. const double EPSILON = 1.0e-9;
  3037. /* Note: We rely on the < comparison here to allow us to set a 0
  3038. * rate and disable the feature entirely. If refactoring, don't
  3039. * change to <= */
  3040. if (node->pb.circ_attempts > EPSILON &&
  3041. pathbias_get_close_success_count(node)/node->pb.circ_attempts
  3042. < pathbias_get_extreme_rate(options) &&
  3043. pathbias_get_dropguards(options)) {
  3044. node->pb.path_bias_disabled = 1;
  3045. log_info(LD_GENERAL,
  3046. "Path bias is too high (%f/%f); disabling node %s",
  3047. node->pb.circ_successes, node->pb.circ_attempts,
  3048. node->nickname);
  3049. }
  3050. }
  3051. /** Parse <b>state</b> and learn about the entry guards it describes.
  3052. * If <b>set</b> is true, and there are no errors, replace the guard
  3053. * list in the provided guard selection context with what we find.
  3054. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  3055. * describing the error, and return -1.
  3056. */
  3057. int
  3058. entry_guards_parse_state_for_guard_selection(
  3059. guard_selection_t *gs,
  3060. or_state_t *state, int set, char **msg)
  3061. {
  3062. entry_guard_t *node = NULL;
  3063. smartlist_t *new_entry_guards = smartlist_new();
  3064. config_line_t *line;
  3065. time_t now = time(NULL);
  3066. const char *state_version = state->TorVersion;
  3067. digestmap_t *added_by = digestmap_new();
  3068. tor_assert(gs != NULL);
  3069. *msg = NULL;
  3070. for (line = state->EntryGuards; line; line = line->next) {
  3071. if (!strcasecmp(line->key, "EntryGuard")) {
  3072. smartlist_t *args = smartlist_new();
  3073. node = tor_malloc_zero(sizeof(entry_guard_t));
  3074. /* all entry guards on disk have been contacted */
  3075. node->made_contact = 1;
  3076. smartlist_add(new_entry_guards, node);
  3077. smartlist_split_string(args, line->value, " ",
  3078. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3079. if (smartlist_len(args)<2) {
  3080. *msg = tor_strdup("Unable to parse entry nodes: "
  3081. "Too few arguments to EntryGuard");
  3082. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  3083. *msg = tor_strdup("Unable to parse entry nodes: "
  3084. "Bad nickname for EntryGuard");
  3085. } else {
  3086. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  3087. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  3088. strlen(smartlist_get(args,1))) != DIGEST_LEN) {
  3089. *msg = tor_strdup("Unable to parse entry nodes: "
  3090. "Bad hex digest for EntryGuard");
  3091. }
  3092. }
  3093. if (smartlist_len(args) >= 3) {
  3094. const char *is_cache = smartlist_get(args, 2);
  3095. if (!strcasecmp(is_cache, "DirCache")) {
  3096. node->is_dir_cache = 1;
  3097. } else if (!strcasecmp(is_cache, "NoDirCache")) {
  3098. node->is_dir_cache = 0;
  3099. } else {
  3100. log_warn(LD_CONFIG, "Bogus third argument to EntryGuard line: %s",
  3101. escaped(is_cache));
  3102. }
  3103. }
  3104. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  3105. smartlist_free(args);
  3106. if (*msg)
  3107. break;
  3108. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  3109. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  3110. time_t when;
  3111. time_t last_try = 0;
  3112. if (!node) {
  3113. *msg = tor_strdup("Unable to parse entry nodes: "
  3114. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  3115. break;
  3116. }
  3117. if (parse_iso_time_(line->value, &when, 0, 0)<0) {
  3118. *msg = tor_strdup("Unable to parse entry nodes: "
  3119. "Bad time in EntryGuardDownSince/UnlistedSince");
  3120. break;
  3121. }
  3122. if (when > now) {
  3123. /* It's a bad idea to believe info in the future: you can wind
  3124. * up with timeouts that aren't allowed to happen for years. */
  3125. continue;
  3126. }
  3127. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  3128. /* ignore failure */
  3129. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  3130. }
  3131. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  3132. node->unreachable_since = when;
  3133. node->last_attempted = last_try;
  3134. } else {
  3135. node->bad_since = when;
  3136. }
  3137. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  3138. char d[DIGEST_LEN];
  3139. /* format is digest version date */
  3140. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  3141. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  3142. continue;
  3143. }
  3144. if (base16_decode(d, sizeof(d),
  3145. line->value, HEX_DIGEST_LEN) != sizeof(d) ||
  3146. line->value[HEX_DIGEST_LEN] != ' ') {
  3147. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  3148. "hex digest", escaped(line->value));
  3149. continue;
  3150. }
  3151. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  3152. } else if (!strcasecmp(line->key, "EntryGuardPathUseBias")) {
  3153. double use_cnt, success_cnt;
  3154. if (!node) {
  3155. *msg = tor_strdup("Unable to parse entry nodes: "
  3156. "EntryGuardPathUseBias without EntryGuard");
  3157. break;
  3158. }
  3159. if (tor_sscanf(line->value, "%lf %lf",
  3160. &use_cnt, &success_cnt) != 2) {
  3161. log_info(LD_GENERAL, "Malformed path use bias line for node %s",
  3162. node->nickname);
  3163. continue;
  3164. }
  3165. if (use_cnt < success_cnt) {
  3166. int severity = LOG_INFO;
  3167. /* If this state file was written by a Tor that would have
  3168. * already fixed it, then the overcounting bug is still there.. */
  3169. if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
  3170. severity = LOG_NOTICE;
  3171. }
  3172. log_fn(severity, LD_BUG,
  3173. "State file contains unexpectedly high usage success "
  3174. "counts %lf/%lf for Guard %s ($%s)",
  3175. success_cnt, use_cnt,
  3176. node->nickname, hex_str(node->identity, DIGEST_LEN));
  3177. success_cnt = use_cnt;
  3178. }
  3179. node->pb.use_attempts = use_cnt;
  3180. node->pb.use_successes = success_cnt;
  3181. log_info(LD_GENERAL, "Read %f/%f path use bias for node %s",
  3182. node->pb.use_successes, node->pb.use_attempts, node->nickname);
  3183. pathbias_check_use_success_count(node);
  3184. } else if (!strcasecmp(line->key, "EntryGuardPathBias")) {
  3185. double hop_cnt, success_cnt, timeouts, collapsed, successful_closed,
  3186. unusable;
  3187. if (!node) {
  3188. *msg = tor_strdup("Unable to parse entry nodes: "
  3189. "EntryGuardPathBias without EntryGuard");
  3190. break;
  3191. }
  3192. /* First try 3 params, then 2. */
  3193. /* In the long run: circuit_success ~= successful_circuit_close +
  3194. * collapsed_circuits +
  3195. * unusable_circuits */
  3196. if (tor_sscanf(line->value, "%lf %lf %lf %lf %lf %lf",
  3197. &hop_cnt, &success_cnt, &successful_closed,
  3198. &collapsed, &unusable, &timeouts) != 6) {
  3199. int old_success, old_hops;
  3200. if (tor_sscanf(line->value, "%u %u", &old_success, &old_hops) != 2) {
  3201. continue;
  3202. }
  3203. log_info(LD_GENERAL, "Reading old-style EntryGuardPathBias %s",
  3204. escaped(line->value));
  3205. success_cnt = old_success;
  3206. successful_closed = old_success;
  3207. hop_cnt = old_hops;
  3208. timeouts = 0;
  3209. collapsed = 0;
  3210. unusable = 0;
  3211. }
  3212. if (hop_cnt < success_cnt) {
  3213. int severity = LOG_INFO;
  3214. /* If this state file was written by a Tor that would have
  3215. * already fixed it, then the overcounting bug is still there.. */
  3216. if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
  3217. severity = LOG_NOTICE;
  3218. }
  3219. log_fn(severity, LD_BUG,
  3220. "State file contains unexpectedly high success counts "
  3221. "%lf/%lf for Guard %s ($%s)",
  3222. success_cnt, hop_cnt,
  3223. node->nickname, hex_str(node->identity, DIGEST_LEN));
  3224. success_cnt = hop_cnt;
  3225. }
  3226. node->pb.circ_attempts = hop_cnt;
  3227. node->pb.circ_successes = success_cnt;
  3228. node->pb.successful_circuits_closed = successful_closed;
  3229. node->pb.timeouts = timeouts;
  3230. node->pb.collapsed_circuits = collapsed;
  3231. node->pb.unusable_circuits = unusable;
  3232. log_info(LD_GENERAL, "Read %f/%f path bias for node %s",
  3233. node->pb.circ_successes, node->pb.circ_attempts,
  3234. node->nickname);
  3235. pathbias_check_close_success_count(node);
  3236. } else {
  3237. log_warn(LD_BUG, "Unexpected key %s", line->key);
  3238. }
  3239. }
  3240. SMARTLIST_FOREACH_BEGIN(new_entry_guards, entry_guard_t *, e) {
  3241. char *sp;
  3242. char *val = digestmap_get(added_by, e->identity);
  3243. if (val && (sp = strchr(val, ' '))) {
  3244. time_t when;
  3245. *sp++ = '\0';
  3246. if (parse_iso_time(sp, &when)<0) {
  3247. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  3248. } else {
  3249. e->chosen_by_version = tor_strdup(val);
  3250. e->chosen_on_date = when;
  3251. }
  3252. } else {
  3253. if (state_version) {
  3254. e->chosen_on_date = crypto_rand_time_range(now - 3600*24*30, now);
  3255. e->chosen_by_version = tor_strdup(state_version);
  3256. }
  3257. }
  3258. if (e->pb.path_bias_disabled && !e->bad_since)
  3259. e->bad_since = time(NULL);
  3260. }
  3261. SMARTLIST_FOREACH_END(e);
  3262. if (*msg || !set) {
  3263. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  3264. entry_guard_free(e));
  3265. smartlist_free(new_entry_guards);
  3266. } else { /* !err && set */
  3267. if (gs->chosen_entry_guards) {
  3268. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e,
  3269. entry_guard_free(e));
  3270. smartlist_free(gs->chosen_entry_guards);
  3271. }
  3272. gs->chosen_entry_guards = new_entry_guards;
  3273. /* XXX hand new_entry_guards to this func, and move it up a
  3274. * few lines, so we don't have to re-dirty it */
  3275. if (remove_obsolete_entry_guards(gs, now))
  3276. entry_guards_dirty = 1;
  3277. }
  3278. digestmap_free(added_by, tor_free_);
  3279. return *msg ? -1 : 0;
  3280. }
  3281. /** Parse <b>state</b> and learn about the entry guards it describes.
  3282. * If <b>set</b> is true, and there are no errors, replace the guard
  3283. * list in the default guard selection context with what we find.
  3284. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  3285. * describing the error, and return -1.
  3286. */
  3287. int
  3288. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  3289. {
  3290. entry_guards_dirty = 0;
  3291. int r1 = entry_guards_load_guards_from_state(state, set);
  3292. int r2 = entry_guards_parse_state_for_guard_selection(
  3293. get_guard_selection_by_name("legacy", 1),
  3294. state, set, msg);
  3295. entry_guards_dirty = 0;
  3296. if (r1 < 0 || r2 < 0) {
  3297. if (msg && *msg == NULL) {
  3298. *msg = tor_strdup("parsing error"); //xxxx prop271 should we try harder?
  3299. }
  3300. return -1;
  3301. }
  3302. return 0;
  3303. }
  3304. /** How long will we let a change in our guard nodes stay un-saved
  3305. * when we are trying to avoid disk writes? */
  3306. #define SLOW_GUARD_STATE_FLUSH_TIME 600
  3307. /** How long will we let a change in our guard nodes stay un-saved
  3308. * when we are not trying to avoid disk writes? */
  3309. #define FAST_GUARD_STATE_FLUSH_TIME 30
  3310. /** Our list of entry guards has changed for a particular guard selection
  3311. * context, or some element of one of our entry guards has changed for one.
  3312. * Write the changes to disk within the next few minutes.
  3313. */
  3314. void
  3315. entry_guards_changed_for_guard_selection(guard_selection_t *gs)
  3316. {
  3317. time_t when;
  3318. tor_assert(gs != NULL);
  3319. entry_guards_dirty = 1;
  3320. if (get_options()->AvoidDiskWrites)
  3321. when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
  3322. else
  3323. when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
  3324. /* or_state_save() will call entry_guards_update_state() and
  3325. entry_guards_update_guards_in_state()
  3326. */
  3327. or_state_mark_dirty(get_or_state(), when);
  3328. }
  3329. /** Our list of entry guards has changed for the default guard selection
  3330. * context, or some element of one of our entry guards has changed. Write
  3331. * the changes to disk within the next few minutes.
  3332. */
  3333. void
  3334. entry_guards_changed(void)
  3335. {
  3336. entry_guards_changed_for_guard_selection(get_guard_selection_info());
  3337. }
  3338. /** If the entry guard info has not changed, do nothing and return.
  3339. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  3340. * a new one out of the global entry_guards list, and then mark
  3341. * <b>state</b> dirty so it will get saved to disk.
  3342. */
  3343. void
  3344. entry_guards_update_state(or_state_t *state)
  3345. {
  3346. config_line_t **next, *line;
  3347. entry_guards_dirty = 0;
  3348. // Handles all non-legacy guard info.
  3349. entry_guards_update_guards_in_state(state);
  3350. entry_guards_dirty = 0;
  3351. guard_selection_t *gs = get_guard_selection_by_name("legacy", 0);
  3352. if (!gs)
  3353. return; // nothign to save.
  3354. tor_assert(gs->chosen_entry_guards != NULL);
  3355. config_free_lines(state->EntryGuards);
  3356. next = &state->EntryGuards;
  3357. *next = NULL;
  3358. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3359. char dbuf[HEX_DIGEST_LEN+1];
  3360. if (!e->made_contact)
  3361. continue; /* don't write this one to disk */
  3362. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3363. line->key = tor_strdup("EntryGuard");
  3364. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  3365. tor_asprintf(&line->value, "%s %s %sDirCache", e->nickname, dbuf,
  3366. e->is_dir_cache ? "" : "No");
  3367. next = &(line->next);
  3368. if (e->unreachable_since) {
  3369. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3370. line->key = tor_strdup("EntryGuardDownSince");
  3371. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  3372. format_iso_time(line->value, e->unreachable_since);
  3373. if (e->last_attempted) {
  3374. line->value[ISO_TIME_LEN] = ' ';
  3375. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  3376. }
  3377. next = &(line->next);
  3378. }
  3379. if (e->bad_since) {
  3380. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3381. line->key = tor_strdup("EntryGuardUnlistedSince");
  3382. line->value = tor_malloc(ISO_TIME_LEN+1);
  3383. format_iso_time(line->value, e->bad_since);
  3384. next = &(line->next);
  3385. }
  3386. if (e->chosen_on_date && e->chosen_by_version &&
  3387. !strchr(e->chosen_by_version, ' ')) {
  3388. char d[HEX_DIGEST_LEN+1];
  3389. char t[ISO_TIME_LEN+1];
  3390. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3391. line->key = tor_strdup("EntryGuardAddedBy");
  3392. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  3393. format_iso_time(t, e->chosen_on_date);
  3394. tor_asprintf(&line->value, "%s %s %s",
  3395. d, e->chosen_by_version, t);
  3396. next = &(line->next);
  3397. }
  3398. if (e->pb.circ_attempts > 0) {
  3399. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3400. line->key = tor_strdup("EntryGuardPathBias");
  3401. /* In the long run: circuit_success ~= successful_circuit_close +
  3402. * collapsed_circuits +
  3403. * unusable_circuits */
  3404. tor_asprintf(&line->value, "%f %f %f %f %f %f",
  3405. e->pb.circ_attempts, e->pb.circ_successes,
  3406. pathbias_get_close_success_count(e),
  3407. e->pb.collapsed_circuits,
  3408. e->pb.unusable_circuits, e->pb.timeouts);
  3409. next = &(line->next);
  3410. }
  3411. if (e->pb.use_attempts > 0) {
  3412. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3413. line->key = tor_strdup("EntryGuardPathUseBias");
  3414. tor_asprintf(&line->value, "%f %f",
  3415. e->pb.use_attempts,
  3416. pathbias_get_use_success_count(e));
  3417. next = &(line->next);
  3418. }
  3419. } SMARTLIST_FOREACH_END(e);
  3420. if (!get_options()->AvoidDiskWrites)
  3421. or_state_mark_dirty(get_or_state(), 0);
  3422. entry_guards_dirty = 0;
  3423. }
  3424. /** If <b>question</b> is the string "entry-guards", then dump
  3425. * to *<b>answer</b> a newly allocated string describing all of
  3426. * the nodes in the global entry_guards list. See control-spec.txt
  3427. * for details.
  3428. * For backward compatibility, we also handle the string "helper-nodes".
  3429. *
  3430. * XXX this should be totally redesigned after prop 271 too, and that's
  3431. * going to take some control spec work.
  3432. * */
  3433. int
  3434. getinfo_helper_entry_guards(control_connection_t *conn,
  3435. const char *question, char **answer,
  3436. const char **errmsg)
  3437. {
  3438. guard_selection_t *gs = get_guard_selection_info();
  3439. tor_assert(gs != NULL);
  3440. tor_assert(gs->chosen_entry_guards != NULL);
  3441. (void) conn;
  3442. (void) errmsg;
  3443. if (!strcmp(question,"entry-guards") ||
  3444. !strcmp(question,"helper-nodes")) {
  3445. smartlist_t *sl = smartlist_new();
  3446. char tbuf[ISO_TIME_LEN+1];
  3447. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  3448. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3449. const char *status = NULL;
  3450. time_t when = 0;
  3451. const node_t *node;
  3452. if (!e->made_contact) {
  3453. status = "never-connected";
  3454. } else if (e->bad_since) {
  3455. when = e->bad_since;
  3456. status = "unusable";
  3457. } else if (e->unreachable_since) {
  3458. when = e->unreachable_since;
  3459. status = "down";
  3460. } else {
  3461. status = "up";
  3462. }
  3463. node = node_get_by_id(e->identity);
  3464. if (node) {
  3465. node_get_verbose_nickname(node, nbuf);
  3466. } else {
  3467. nbuf[0] = '$';
  3468. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  3469. /* e->nickname field is not very reliable if we don't know about
  3470. * this router any longer; don't include it. */
  3471. }
  3472. if (when) {
  3473. format_iso_time(tbuf, when);
  3474. smartlist_add_asprintf(sl, "%s %s %s\n", nbuf, status, tbuf);
  3475. } else {
  3476. smartlist_add_asprintf(sl, "%s %s\n", nbuf, status);
  3477. }
  3478. } SMARTLIST_FOREACH_END(e);
  3479. *answer = smartlist_join_strings(sl, "", 0, NULL);
  3480. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  3481. smartlist_free(sl);
  3482. }
  3483. return 0;
  3484. }
  3485. /* Given the original bandwidth of a guard and its guardfraction,
  3486. * calculate how much bandwidth the guard should have as a guard and
  3487. * as a non-guard.
  3488. *
  3489. * Quoting from proposal236:
  3490. *
  3491. * Let Wpf denote the weight from the 'bandwidth-weights' line a
  3492. * client would apply to N for position p if it had the guard
  3493. * flag, Wpn the weight if it did not have the guard flag, and B the
  3494. * measured bandwidth of N in the consensus. Then instead of choosing
  3495. * N for position p proportionally to Wpf*B or Wpn*B, clients should
  3496. * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
  3497. *
  3498. * This function fills the <b>guardfraction_bw</b> structure. It sets
  3499. * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
  3500. */
  3501. void
  3502. guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
  3503. int orig_bandwidth,
  3504. uint32_t guardfraction_percentage)
  3505. {
  3506. double guardfraction_fraction;
  3507. /* Turn the percentage into a fraction. */
  3508. tor_assert(guardfraction_percentage <= 100);
  3509. guardfraction_fraction = guardfraction_percentage / 100.0;
  3510. long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
  3511. tor_assert(guard_bw <= INT_MAX);
  3512. guardfraction_bw->guard_bw = (int) guard_bw;
  3513. guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
  3514. }
  3515. /** Returns true iff the node is used as a guard in the specified guard
  3516. * context */
  3517. int
  3518. is_node_used_as_guard_for_guard_selection(guard_selection_t *gs,
  3519. const node_t *node)
  3520. {
  3521. int res = 0;
  3522. /*
  3523. * We used to have a using_as_guard flag in node_t, but it had to go away
  3524. * to allow for multiple guard selection contexts. Instead, search the
  3525. * guard list for a matching digest.
  3526. */
  3527. tor_assert(gs != NULL);
  3528. tor_assert(node != NULL);
  3529. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3530. if (tor_memeq(e->identity, node->identity, DIGEST_LEN)) {
  3531. res = 1;
  3532. break;
  3533. }
  3534. } SMARTLIST_FOREACH_END(e);
  3535. return res;
  3536. }
  3537. /** Returns true iff the node is used as a guard in the default guard
  3538. * context */
  3539. MOCK_IMPL(int,
  3540. is_node_used_as_guard, (const node_t *node))
  3541. {
  3542. return is_node_used_as_guard_for_guard_selection(
  3543. get_guard_selection_info(), node);
  3544. }
  3545. /** Return 1 if we have at least one descriptor for an entry guard
  3546. * (bridge or member of EntryNodes) and all descriptors we know are
  3547. * down. Else return 0. If <b>act</b> is 1, then mark the down guards
  3548. * up; else just observe and report. */
  3549. static int
  3550. entries_retry_helper(const or_options_t *options, int act)
  3551. {
  3552. const node_t *node;
  3553. int any_known = 0;
  3554. int any_running = 0;
  3555. int need_bridges = options->UseBridges != 0;
  3556. guard_selection_t *gs = get_guard_selection_info();
  3557. tor_assert(gs != NULL);
  3558. tor_assert(gs->chosen_entry_guards != NULL);
  3559. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  3560. node = node_get_by_id(e->identity);
  3561. if (node && node_has_descriptor(node) &&
  3562. node_is_bridge(node) == need_bridges &&
  3563. (!need_bridges || (!e->bad_since &&
  3564. node_is_a_configured_bridge(node)))) {
  3565. any_known = 1;
  3566. if (node->is_running)
  3567. any_running = 1; /* some entry is both known and running */
  3568. else if (act) {
  3569. /* Mark all current connections to this OR as unhealthy, since
  3570. * otherwise there could be one that started 30 seconds
  3571. * ago, and in 30 seconds it will time out, causing us to mark
  3572. * the node down and undermine the retry attempt. We mark even
  3573. * the established conns, since if the network just came back
  3574. * we'll want to attach circuits to fresh conns. */
  3575. connection_or_set_bad_connections(node->identity, 1);
  3576. /* mark this entry node for retry */
  3577. router_set_status(node->identity, 1);
  3578. e->can_retry = 1;
  3579. e->bad_since = 0;
  3580. }
  3581. }
  3582. } SMARTLIST_FOREACH_END(e);
  3583. log_debug(LD_DIR, "%d: any_known %d, any_running %d",
  3584. act, any_known, any_running);
  3585. return any_known && !any_running;
  3586. }
  3587. /** Do we know any descriptors for our bridges / entrynodes, and are
  3588. * all the ones we have descriptors for down? */
  3589. int
  3590. entries_known_but_down(const or_options_t *options)
  3591. {
  3592. tor_assert(entry_list_is_constrained(options));
  3593. return entries_retry_helper(options, 0);
  3594. }
  3595. /** Mark all down known bridges / entrynodes up. */
  3596. void
  3597. entries_retry_all(const or_options_t *options)
  3598. {
  3599. tor_assert(entry_list_is_constrained(options));
  3600. entries_retry_helper(options, 1);
  3601. }
  3602. /** Helper: Update the status of all entry guards, in whatever algorithm
  3603. * is used. Return true if we should stop using all previously generated
  3604. * circuits. */
  3605. int
  3606. guards_update_all(void)
  3607. {
  3608. if (get_options()->UseDeprecatedGuardAlgorithm) {
  3609. entry_guards_compute_status(get_options(), approx_time());
  3610. return 0;
  3611. } else {
  3612. return entry_guards_update_all(get_guard_selection_info());
  3613. }
  3614. }
  3615. /** Helper: pick a guard for a circuit, with whatever algorithm is
  3616. used. */
  3617. const node_t *
  3618. guards_choose_guard(cpath_build_state_t *state,
  3619. circuit_guard_state_t **guard_state_out)
  3620. {
  3621. if (get_options()->UseDeprecatedGuardAlgorithm) {
  3622. return choose_random_entry(state);
  3623. } else {
  3624. // XXXX prop271 we need to look at the chosen exit node if any, and
  3625. // not duplicate it.
  3626. const node_t *r = NULL;
  3627. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  3628. &r,
  3629. guard_state_out) < 0) {
  3630. tor_assert(r == NULL);
  3631. }
  3632. return r;
  3633. }
  3634. }
  3635. /** Helper: pick a directory guard, with whatever algorithm is used. */
  3636. const node_t *
  3637. guards_choose_dirguard(dirinfo_type_t info,
  3638. circuit_guard_state_t **guard_state_out)
  3639. {
  3640. if (get_options()->UseDeprecatedGuardAlgorithm) {
  3641. return choose_random_dirguard(info);
  3642. } else {
  3643. // XXXX prop271 look at info?
  3644. const node_t *r = NULL;
  3645. if (entry_guard_pick_for_circuit(get_guard_selection_info(),
  3646. &r,
  3647. guard_state_out) < 0) {
  3648. tor_assert(r == NULL);
  3649. }
  3650. return r;
  3651. }
  3652. }
  3653. /** Free one guard selection context */
  3654. STATIC void
  3655. guard_selection_free(guard_selection_t *gs)
  3656. {
  3657. if (!gs) return;
  3658. tor_free(gs->name);
  3659. if (gs->chosen_entry_guards) {
  3660. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e,
  3661. entry_guard_free(e));
  3662. smartlist_free(gs->chosen_entry_guards);
  3663. gs->chosen_entry_guards = NULL;
  3664. }
  3665. if (gs->sampled_entry_guards) {
  3666. SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
  3667. entry_guard_free(e));
  3668. smartlist_free(gs->sampled_entry_guards);
  3669. gs->sampled_entry_guards = NULL;
  3670. }
  3671. smartlist_free(gs->confirmed_entry_guards);
  3672. smartlist_free(gs->primary_entry_guards);
  3673. tor_free(gs);
  3674. }
  3675. /** Release all storage held by the list of entry guards and related
  3676. * memory structs. */
  3677. void
  3678. entry_guards_free_all(void)
  3679. {
  3680. /* Null out the default */
  3681. curr_guard_context = NULL;
  3682. /* Free all the guard contexts */
  3683. if (guard_contexts != NULL) {
  3684. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  3685. guard_selection_free(gs);
  3686. } SMARTLIST_FOREACH_END(gs);
  3687. smartlist_free(guard_contexts);
  3688. guard_contexts = NULL;
  3689. }
  3690. circuit_build_times_free_timeouts(get_circuit_build_times_mutable());
  3691. }