circuitbuild.c 162 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874
  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-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitbuild.c
  8. * \brief The actual details of building circuits.
  9. **/
  10. #define CIRCUIT_PRIVATE
  11. #include "or.h"
  12. #include "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "circuituse.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "connection_edge.h"
  18. #include "connection_or.h"
  19. #include "control.h"
  20. #include "directory.h"
  21. #include "main.h"
  22. #include "networkstatus.h"
  23. #include "onion.h"
  24. #include "policies.h"
  25. #include "relay.h"
  26. #include "rephist.h"
  27. #include "router.h"
  28. #include "routerlist.h"
  29. #include "routerparse.h"
  30. #include "crypto.h"
  31. #undef log
  32. #include <math.h>
  33. #ifndef MIN
  34. #define MIN(a,b) ((a)<(b)?(a):(b))
  35. #endif
  36. #define CBT_BIN_TO_MS(bin) ((bin)*CBT_BIN_WIDTH + (CBT_BIN_WIDTH/2))
  37. /********* START VARIABLES **********/
  38. /** Global list of circuit build times */
  39. // XXXX023: Add this as a member for entry_guard_t instead of global?
  40. // Then we could do per-guard statistics, as guards are likely to
  41. // vary in their own latency. The downside of this is that guards
  42. // can change frequently, so we'd be building a lot more circuits
  43. // most likely.
  44. /* XXXX023 Make this static; add accessor functions. */
  45. circuit_build_times_t circ_times;
  46. /** A global list of all circuits at this hop. */
  47. extern circuit_t *global_circuitlist;
  48. /** An entry_guard_t represents our information about a chosen long-term
  49. * first hop, known as a "helper" node in the literature. We can't just
  50. * use a routerinfo_t, since we want to remember these even when we
  51. * don't have a directory. */
  52. typedef struct {
  53. char nickname[MAX_NICKNAME_LEN+1];
  54. char identity[DIGEST_LEN];
  55. time_t chosen_on_date; /**< Approximately when was this guard added?
  56. * "0" if we don't know. */
  57. char *chosen_by_version; /**< What tor version added this guard? NULL
  58. * if we don't know. */
  59. unsigned int made_contact : 1; /**< 0 if we have never connected to this
  60. * router, 1 if we have. */
  61. unsigned int can_retry : 1; /**< Should we retry connecting to this entry,
  62. * in spite of having it marked as unreachable?*/
  63. time_t bad_since; /**< 0 if this guard is currently usable, or the time at
  64. * which it was observed to become (according to the
  65. * directory or the user configuration) unusable. */
  66. time_t unreachable_since; /**< 0 if we can connect to this guard, or the
  67. * time at which we first noticed we couldn't
  68. * connect to it. */
  69. time_t last_attempted; /**< 0 if we can connect to this guard, or the time
  70. * at which we last failed to connect to it. */
  71. } entry_guard_t;
  72. /** A list of our chosen entry guards. */
  73. static smartlist_t *entry_guards = NULL;
  74. /** A value of 1 means that the entry_guards list has changed
  75. * and those changes need to be flushed to disk. */
  76. static int entry_guards_dirty = 0;
  77. /** If set, we're running the unit tests: we should avoid clobbering
  78. * our state file or accessing get_options() or get_or_state() */
  79. static int unit_tests = 0;
  80. /********* END VARIABLES ************/
  81. static int circuit_deliver_create_cell(circuit_t *circ,
  82. uint8_t cell_type, const char *payload);
  83. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  84. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  85. static int onion_extend_cpath(origin_circuit_t *circ);
  86. static int count_acceptable_routers(smartlist_t *routers);
  87. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  88. static void entry_guards_changed(void);
  89. /**
  90. * This function decides if CBT learning should be disabled. It returns
  91. * true if one or more of the following four conditions are met:
  92. *
  93. * 1. If the cbtdisabled consensus parameter is set.
  94. * 2. If the torrc option LearnCircuitBuildTimeout is false.
  95. * 3. If we are a directory authority
  96. * 4. If we fail to write circuit build time history to our state file.
  97. */
  98. static int
  99. circuit_build_times_disabled(void)
  100. {
  101. if (unit_tests) {
  102. return 0;
  103. } else {
  104. int consensus_disabled = networkstatus_get_param(NULL, "cbtdisabled",
  105. 0, 0, 1);
  106. int config_disabled = !get_options()->LearnCircuitBuildTimeout;
  107. int dirauth_disabled = get_options()->AuthoritativeDir;
  108. int state_disabled = did_last_state_file_write_fail() ? 1 : 0;
  109. if (consensus_disabled || config_disabled || dirauth_disabled ||
  110. state_disabled) {
  111. log_info(LD_CIRC,
  112. "CircuitBuildTime learning is disabled. "
  113. "Consensus=%d, Config=%d, AuthDir=%d, StateFile=%d",
  114. consensus_disabled, config_disabled, dirauth_disabled,
  115. state_disabled);
  116. return 1;
  117. } else {
  118. return 0;
  119. }
  120. }
  121. }
  122. /**
  123. * Retrieve and bounds-check the cbtmaxtimeouts consensus paramter.
  124. *
  125. * Effect: When this many timeouts happen in the last 'cbtrecentcount'
  126. * circuit attempts, the client should discard all of its history and
  127. * begin learning a fresh timeout value.
  128. */
  129. static int32_t
  130. circuit_build_times_max_timeouts(void)
  131. {
  132. return networkstatus_get_param(NULL, "cbtmaxtimeouts",
  133. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT,
  134. CBT_MIN_MAX_RECENT_TIMEOUT_COUNT,
  135. CBT_MAX_MAX_RECENT_TIMEOUT_COUNT);
  136. }
  137. /**
  138. * Retrieve and bounds-check the cbtnummodes consensus paramter.
  139. *
  140. * Effect: This value governs how many modes to use in the weighted
  141. * average calculation of Pareto parameter Xm. A value of 3 introduces
  142. * some bias (2-5% of CDF) under ideal conditions, but allows for better
  143. * performance in the event that a client chooses guard nodes of radically
  144. * different performance characteristics.
  145. */
  146. static int32_t
  147. circuit_build_times_default_num_xm_modes(void)
  148. {
  149. int32_t num = networkstatus_get_param(NULL, "cbtnummodes",
  150. CBT_DEFAULT_NUM_XM_MODES,
  151. CBT_MIN_NUM_XM_MODES,
  152. CBT_MAX_NUM_XM_MODES);
  153. return num;
  154. }
  155. /**
  156. * Retrieve and bounds-check the cbtmincircs consensus paramter.
  157. *
  158. * Effect: This is the minimum number of circuits to build before
  159. * computing a timeout.
  160. */
  161. static int32_t
  162. circuit_build_times_min_circs_to_observe(void)
  163. {
  164. int32_t num = networkstatus_get_param(NULL, "cbtmincircs",
  165. CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE,
  166. CBT_MIN_MIN_CIRCUITS_TO_OBSERVE,
  167. CBT_MAX_MIN_CIRCUITS_TO_OBSERVE);
  168. return num;
  169. }
  170. /** Return true iff <b>cbt</b> has recorded enough build times that we
  171. * want to start acting on the timeout it implies. */
  172. int
  173. circuit_build_times_enough_to_compute(circuit_build_times_t *cbt)
  174. {
  175. return cbt->total_build_times >= circuit_build_times_min_circs_to_observe();
  176. }
  177. /**
  178. * Retrieve and bounds-check the cbtquantile consensus paramter.
  179. *
  180. * Effect: This is the position on the quantile curve to use to set the
  181. * timeout value. It is a percent (10-99).
  182. */
  183. double
  184. circuit_build_times_quantile_cutoff(void)
  185. {
  186. int32_t num = networkstatus_get_param(NULL, "cbtquantile",
  187. CBT_DEFAULT_QUANTILE_CUTOFF,
  188. CBT_MIN_QUANTILE_CUTOFF,
  189. CBT_MAX_QUANTILE_CUTOFF);
  190. return num/100.0;
  191. }
  192. int
  193. circuit_build_times_get_bw_scale(networkstatus_t *ns)
  194. {
  195. return networkstatus_get_param(ns, "bwweightscale",
  196. BW_WEIGHT_SCALE,
  197. BW_MIN_WEIGHT_SCALE,
  198. BW_MAX_WEIGHT_SCALE);
  199. }
  200. /**
  201. * Retrieve and bounds-check the cbtclosequantile consensus paramter.
  202. *
  203. * Effect: This is the position on the quantile curve to use to set the
  204. * timeout value to use to actually close circuits. It is a percent
  205. * (0-99).
  206. */
  207. static double
  208. circuit_build_times_close_quantile(void)
  209. {
  210. int32_t param;
  211. /* Cast is safe - circuit_build_times_quantile_cutoff() is capped */
  212. int32_t min = (int)tor_lround(100*circuit_build_times_quantile_cutoff());
  213. param = networkstatus_get_param(NULL, "cbtclosequantile",
  214. CBT_DEFAULT_CLOSE_QUANTILE,
  215. CBT_MIN_CLOSE_QUANTILE,
  216. CBT_MAX_CLOSE_QUANTILE);
  217. if (param < min) {
  218. log_warn(LD_DIR, "Consensus parameter cbtclosequantile is "
  219. "too small, raising to %d", min);
  220. param = min;
  221. }
  222. return param / 100.0;
  223. }
  224. /**
  225. * Retrieve and bounds-check the cbttestfreq consensus paramter.
  226. *
  227. * Effect: Describes how often in seconds to build a test circuit to
  228. * gather timeout values. Only applies if less than 'cbtmincircs'
  229. * have been recorded.
  230. */
  231. static int32_t
  232. circuit_build_times_test_frequency(void)
  233. {
  234. int32_t num = networkstatus_get_param(NULL, "cbttestfreq",
  235. CBT_DEFAULT_TEST_FREQUENCY,
  236. CBT_MIN_TEST_FREQUENCY,
  237. CBT_MAX_TEST_FREQUENCY);
  238. return num;
  239. }
  240. /**
  241. * Retrieve and bounds-check the cbtmintimeout consensus paramter.
  242. *
  243. * Effect: This is the minimum allowed timeout value in milliseconds.
  244. * The minimum is to prevent rounding to 0 (we only check once
  245. * per second).
  246. */
  247. static int32_t
  248. circuit_build_times_min_timeout(void)
  249. {
  250. int32_t num = networkstatus_get_param(NULL, "cbtmintimeout",
  251. CBT_DEFAULT_TIMEOUT_MIN_VALUE,
  252. CBT_MIN_TIMEOUT_MIN_VALUE,
  253. CBT_MAX_TIMEOUT_MIN_VALUE);
  254. return num;
  255. }
  256. /**
  257. * Retrieve and bounds-check the cbtinitialtimeout consensus paramter.
  258. *
  259. * Effect: This is the timeout value to use before computing a timeout,
  260. * in milliseconds.
  261. */
  262. int32_t
  263. circuit_build_times_initial_timeout(void)
  264. {
  265. int32_t min = circuit_build_times_min_timeout();
  266. int32_t param = networkstatus_get_param(NULL, "cbtinitialtimeout",
  267. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE,
  268. CBT_MIN_TIMEOUT_INITIAL_VALUE,
  269. CBT_MAX_TIMEOUT_INITIAL_VALUE);
  270. if (param < min) {
  271. log_warn(LD_DIR, "Consensus parameter cbtinitialtimeout is too small, "
  272. "raising to %d", min);
  273. param = min;
  274. }
  275. return param;
  276. }
  277. /**
  278. * Retrieve and bounds-check the cbtrecentcount consensus paramter.
  279. *
  280. * Effect: This is the number of circuit build times to keep track of
  281. * for deciding if we hit cbtmaxtimeouts and need to reset our state
  282. * and learn a new timeout.
  283. */
  284. static int32_t
  285. circuit_build_times_recent_circuit_count(networkstatus_t *ns)
  286. {
  287. return networkstatus_get_param(ns, "cbtrecentcount",
  288. CBT_DEFAULT_RECENT_CIRCUITS,
  289. CBT_MIN_RECENT_CIRCUITS,
  290. CBT_MAX_RECENT_CIRCUITS);
  291. }
  292. /**
  293. * This function is called when we get a consensus update.
  294. *
  295. * It checks to see if we have changed any consensus parameters
  296. * that require reallocation or discard of previous stats.
  297. */
  298. void
  299. circuit_build_times_new_consensus_params(circuit_build_times_t *cbt,
  300. networkstatus_t *ns)
  301. {
  302. int32_t num = circuit_build_times_recent_circuit_count(ns);
  303. if (num > 0 && num != cbt->liveness.num_recent_circs) {
  304. int8_t *recent_circs;
  305. log_notice(LD_CIRC, "The Tor Directory Consensus has changed how many "
  306. "circuits we must track to detect network failures from %d "
  307. "to %d.", cbt->liveness.num_recent_circs, num);
  308. tor_assert(cbt->liveness.timeouts_after_firsthop);
  309. /*
  310. * Technically this is a circular array that we are reallocating
  311. * and memcopying. However, since it only consists of either 1s
  312. * or 0s, and is only used in a statistical test to determine when
  313. * we should discard our history after a sufficient number of 1's
  314. * have been reached, it is fine if order is not preserved or
  315. * elements are lost.
  316. *
  317. * cbtrecentcount should only be changing in cases of severe network
  318. * distress anyway, so memory correctness here is paramount over
  319. * doing acrobatics to preserve the array.
  320. */
  321. recent_circs = tor_malloc_zero(sizeof(int8_t)*num);
  322. memcpy(recent_circs, cbt->liveness.timeouts_after_firsthop,
  323. sizeof(int8_t)*MIN(num, cbt->liveness.num_recent_circs));
  324. // Adjust the index if it needs it.
  325. if (num < cbt->liveness.num_recent_circs) {
  326. cbt->liveness.after_firsthop_idx = MIN(num-1,
  327. cbt->liveness.after_firsthop_idx);
  328. }
  329. tor_free(cbt->liveness.timeouts_after_firsthop);
  330. cbt->liveness.timeouts_after_firsthop = recent_circs;
  331. cbt->liveness.num_recent_circs = num;
  332. }
  333. }
  334. /** Make a note that we're running unit tests (rather than running Tor
  335. * itself), so we avoid clobbering our state file. */
  336. void
  337. circuitbuild_running_unit_tests(void)
  338. {
  339. unit_tests = 1;
  340. }
  341. /**
  342. * Return the initial default or configured timeout in milliseconds
  343. */
  344. static double
  345. circuit_build_times_get_initial_timeout(void)
  346. {
  347. double timeout;
  348. if (!unit_tests && get_options()->CircuitBuildTimeout) {
  349. timeout = get_options()->CircuitBuildTimeout*1000;
  350. if (timeout < circuit_build_times_min_timeout()) {
  351. log_warn(LD_CIRC, "Config CircuitBuildTimeout too low. Setting to %ds",
  352. circuit_build_times_min_timeout()/1000);
  353. timeout = circuit_build_times_min_timeout();
  354. }
  355. } else {
  356. timeout = circuit_build_times_initial_timeout();
  357. }
  358. return timeout;
  359. }
  360. /**
  361. * Reset the build time state.
  362. *
  363. * Leave estimated parameters, timeout and network liveness intact
  364. * for future use.
  365. */
  366. void
  367. circuit_build_times_reset(circuit_build_times_t *cbt)
  368. {
  369. memset(cbt->circuit_build_times, 0, sizeof(cbt->circuit_build_times));
  370. cbt->total_build_times = 0;
  371. cbt->build_times_idx = 0;
  372. cbt->have_computed_timeout = 0;
  373. }
  374. /**
  375. * Initialize the buildtimes structure for first use.
  376. *
  377. * Sets the initial timeout values based on either the config setting,
  378. * the consensus param, or the default (CBT_DEFAULT_TIMEOUT_INITIAL_VALUE).
  379. */
  380. void
  381. circuit_build_times_init(circuit_build_times_t *cbt)
  382. {
  383. memset(cbt, 0, sizeof(*cbt));
  384. cbt->liveness.num_recent_circs =
  385. circuit_build_times_recent_circuit_count(NULL);
  386. cbt->liveness.timeouts_after_firsthop = tor_malloc_zero(sizeof(int8_t)*
  387. cbt->liveness.num_recent_circs);
  388. cbt->close_ms = cbt->timeout_ms = circuit_build_times_get_initial_timeout();
  389. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  390. }
  391. #if 0
  392. /**
  393. * Rewind our build time history by n positions.
  394. */
  395. static void
  396. circuit_build_times_rewind_history(circuit_build_times_t *cbt, int n)
  397. {
  398. int i = 0;
  399. cbt->build_times_idx -= n;
  400. cbt->build_times_idx %= CBT_NCIRCUITS_TO_OBSERVE;
  401. for (i = 0; i < n; i++) {
  402. cbt->circuit_build_times[(i+cbt->build_times_idx)
  403. %CBT_NCIRCUITS_TO_OBSERVE]=0;
  404. }
  405. if (cbt->total_build_times > n) {
  406. cbt->total_build_times -= n;
  407. } else {
  408. cbt->total_build_times = 0;
  409. }
  410. log_info(LD_CIRC,
  411. "Rewound history by %d places. Current index: %d. "
  412. "Total: %d", n, cbt->build_times_idx, cbt->total_build_times);
  413. }
  414. #endif
  415. /**
  416. * Add a new build time value <b>time</b> to the set of build times. Time
  417. * units are milliseconds.
  418. *
  419. * circuit_build_times <b>cbt</b> is a circular array, so loop around when
  420. * array is full.
  421. */
  422. int
  423. circuit_build_times_add_time(circuit_build_times_t *cbt, build_time_t time)
  424. {
  425. if (time <= 0 || time > CBT_BUILD_TIME_MAX) {
  426. log_warn(LD_BUG, "Circuit build time is too large (%u)."
  427. "This is probably a bug.", time);
  428. tor_fragile_assert();
  429. return -1;
  430. }
  431. log_debug(LD_CIRC, "Adding circuit build time %u", time);
  432. cbt->circuit_build_times[cbt->build_times_idx] = time;
  433. cbt->build_times_idx = (cbt->build_times_idx + 1) % CBT_NCIRCUITS_TO_OBSERVE;
  434. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  435. cbt->total_build_times++;
  436. if ((cbt->total_build_times % CBT_SAVE_STATE_EVERY) == 0) {
  437. /* Save state every n circuit builds */
  438. if (!unit_tests && !get_options()->AvoidDiskWrites)
  439. or_state_mark_dirty(get_or_state(), 0);
  440. }
  441. return 0;
  442. }
  443. /**
  444. * Return maximum circuit build time
  445. */
  446. static build_time_t
  447. circuit_build_times_max(circuit_build_times_t *cbt)
  448. {
  449. int i = 0;
  450. build_time_t max_build_time = 0;
  451. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  452. if (cbt->circuit_build_times[i] > max_build_time
  453. && cbt->circuit_build_times[i] != CBT_BUILD_ABANDONED)
  454. max_build_time = cbt->circuit_build_times[i];
  455. }
  456. return max_build_time;
  457. }
  458. #if 0
  459. /** Return minimum circuit build time */
  460. build_time_t
  461. circuit_build_times_min(circuit_build_times_t *cbt)
  462. {
  463. int i = 0;
  464. build_time_t min_build_time = CBT_BUILD_TIME_MAX;
  465. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  466. if (cbt->circuit_build_times[i] && /* 0 <-> uninitialized */
  467. cbt->circuit_build_times[i] < min_build_time)
  468. min_build_time = cbt->circuit_build_times[i];
  469. }
  470. if (min_build_time == CBT_BUILD_TIME_MAX) {
  471. log_warn(LD_CIRC, "No build times less than CBT_BUILD_TIME_MAX!");
  472. }
  473. return min_build_time;
  474. }
  475. #endif
  476. /**
  477. * Calculate and return a histogram for the set of build times.
  478. *
  479. * Returns an allocated array of histrogram bins representing
  480. * the frequency of index*CBT_BIN_WIDTH millisecond
  481. * build times. Also outputs the number of bins in nbins.
  482. *
  483. * The return value must be freed by the caller.
  484. */
  485. static uint32_t *
  486. circuit_build_times_create_histogram(circuit_build_times_t *cbt,
  487. build_time_t *nbins)
  488. {
  489. uint32_t *histogram;
  490. build_time_t max_build_time = circuit_build_times_max(cbt);
  491. int i, c;
  492. *nbins = 1 + (max_build_time / CBT_BIN_WIDTH);
  493. histogram = tor_malloc_zero(*nbins * sizeof(build_time_t));
  494. // calculate histogram
  495. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  496. if (cbt->circuit_build_times[i] == 0
  497. || cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  498. continue; /* 0 <-> uninitialized */
  499. c = (cbt->circuit_build_times[i] / CBT_BIN_WIDTH);
  500. histogram[c]++;
  501. }
  502. return histogram;
  503. }
  504. /**
  505. * Return the Pareto start-of-curve parameter Xm.
  506. *
  507. * Because we are not a true Pareto curve, we compute this as the
  508. * weighted average of the N most frequent build time bins. N is either
  509. * 1 if we don't have enough circuit build time data collected, or
  510. * determined by the consensus parameter cbtnummodes (default 3).
  511. */
  512. static build_time_t
  513. circuit_build_times_get_xm(circuit_build_times_t *cbt)
  514. {
  515. build_time_t i, nbins;
  516. build_time_t *nth_max_bin;
  517. int32_t bin_counts=0;
  518. build_time_t ret = 0;
  519. uint32_t *histogram = circuit_build_times_create_histogram(cbt, &nbins);
  520. int n=0;
  521. int num_modes = circuit_build_times_default_num_xm_modes();
  522. tor_assert(nbins > 0);
  523. tor_assert(num_modes > 0);
  524. // Only use one mode if < 1000 buildtimes. Not enough data
  525. // for multiple.
  526. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  527. num_modes = 1;
  528. nth_max_bin = (build_time_t*)tor_malloc_zero(num_modes*sizeof(build_time_t));
  529. /* Determine the N most common build times */
  530. for (i = 0; i < nbins; i++) {
  531. if (histogram[i] >= histogram[nth_max_bin[0]]) {
  532. nth_max_bin[0] = i;
  533. }
  534. for (n = 1; n < num_modes; n++) {
  535. if (histogram[i] >= histogram[nth_max_bin[n]] &&
  536. (!histogram[nth_max_bin[n-1]]
  537. || histogram[i] < histogram[nth_max_bin[n-1]])) {
  538. nth_max_bin[n] = i;
  539. }
  540. }
  541. }
  542. for (n = 0; n < num_modes; n++) {
  543. bin_counts += histogram[nth_max_bin[n]];
  544. ret += CBT_BIN_TO_MS(nth_max_bin[n])*histogram[nth_max_bin[n]];
  545. log_info(LD_CIRC, "Xm mode #%d: %u %u", n, CBT_BIN_TO_MS(nth_max_bin[n]),
  546. histogram[nth_max_bin[n]]);
  547. }
  548. /* The following assert is safe, because we don't get called when we
  549. * haven't observed at least CBT_MIN_MIN_CIRCUITS_TO_OBSERVE circuits. */
  550. tor_assert(bin_counts > 0);
  551. ret /= bin_counts;
  552. tor_free(histogram);
  553. tor_free(nth_max_bin);
  554. return ret;
  555. }
  556. /**
  557. * Output a histogram of current circuit build times to
  558. * the or_state_t state structure.
  559. */
  560. void
  561. circuit_build_times_update_state(circuit_build_times_t *cbt,
  562. or_state_t *state)
  563. {
  564. uint32_t *histogram;
  565. build_time_t i = 0;
  566. build_time_t nbins = 0;
  567. config_line_t **next, *line;
  568. histogram = circuit_build_times_create_histogram(cbt, &nbins);
  569. // write to state
  570. config_free_lines(state->BuildtimeHistogram);
  571. next = &state->BuildtimeHistogram;
  572. *next = NULL;
  573. state->TotalBuildTimes = cbt->total_build_times;
  574. state->CircuitBuildAbandonedCount = 0;
  575. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  576. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  577. state->CircuitBuildAbandonedCount++;
  578. }
  579. for (i = 0; i < nbins; i++) {
  580. // compress the histogram by skipping the blanks
  581. if (histogram[i] == 0) continue;
  582. *next = line = tor_malloc_zero(sizeof(config_line_t));
  583. line->key = tor_strdup("CircuitBuildTimeBin");
  584. line->value = tor_malloc(25);
  585. tor_snprintf(line->value, 25, "%d %d",
  586. CBT_BIN_TO_MS(i), histogram[i]);
  587. next = &(line->next);
  588. }
  589. if (!unit_tests) {
  590. if (!get_options()->AvoidDiskWrites)
  591. or_state_mark_dirty(get_or_state(), 0);
  592. }
  593. tor_free(histogram);
  594. }
  595. /**
  596. * Shuffle the build times array.
  597. *
  598. * Adapted from http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  599. */
  600. static void
  601. circuit_build_times_shuffle_and_store_array(circuit_build_times_t *cbt,
  602. build_time_t *raw_times,
  603. uint32_t num_times)
  604. {
  605. uint32_t n = num_times;
  606. if (num_times > CBT_NCIRCUITS_TO_OBSERVE) {
  607. log_notice(LD_CIRC, "The number of circuit times that this Tor version "
  608. "uses to calculate build times is less than the number stored "
  609. "in your state file. Decreasing the circuit time history from "
  610. "%d to %d.", num_times, CBT_NCIRCUITS_TO_OBSERVE);
  611. }
  612. /* This code can only be run on a compact array */
  613. while (n-- > 1) {
  614. int k = crypto_rand_int(n + 1); /* 0 <= k <= n. */
  615. build_time_t tmp = raw_times[k];
  616. raw_times[k] = raw_times[n];
  617. raw_times[n] = tmp;
  618. }
  619. /* Since the times are now shuffled, take a random CBT_NCIRCUITS_TO_OBSERVE
  620. * subset (ie the first CBT_NCIRCUITS_TO_OBSERVE values) */
  621. for (n = 0; n < MIN(num_times, CBT_NCIRCUITS_TO_OBSERVE); n++) {
  622. circuit_build_times_add_time(cbt, raw_times[n]);
  623. }
  624. }
  625. /**
  626. * Filter old synthetic timeouts that were created before the
  627. * new right-censored Pareto calculation was deployed.
  628. *
  629. * Once all clients before 0.2.1.13-alpha are gone, this code
  630. * will be unused.
  631. */
  632. static int
  633. circuit_build_times_filter_timeouts(circuit_build_times_t *cbt)
  634. {
  635. int num_filtered=0, i=0;
  636. double timeout_rate = 0;
  637. build_time_t max_timeout = 0;
  638. timeout_rate = circuit_build_times_timeout_rate(cbt);
  639. max_timeout = (build_time_t)cbt->close_ms;
  640. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  641. if (cbt->circuit_build_times[i] > max_timeout) {
  642. build_time_t replaced = cbt->circuit_build_times[i];
  643. num_filtered++;
  644. cbt->circuit_build_times[i] = CBT_BUILD_ABANDONED;
  645. log_debug(LD_CIRC, "Replaced timeout %d with %d", replaced,
  646. cbt->circuit_build_times[i]);
  647. }
  648. }
  649. log_info(LD_CIRC,
  650. "We had %d timeouts out of %d build times, "
  651. "and filtered %d above the max of %u",
  652. (int)(cbt->total_build_times*timeout_rate),
  653. cbt->total_build_times, num_filtered, max_timeout);
  654. return num_filtered;
  655. }
  656. /**
  657. * Load histogram from <b>state</b>, shuffling the resulting array
  658. * after we do so. Use this result to estimate parameters and
  659. * calculate the timeout.
  660. *
  661. * Return -1 on error.
  662. */
  663. int
  664. circuit_build_times_parse_state(circuit_build_times_t *cbt,
  665. or_state_t *state)
  666. {
  667. int tot_values = 0;
  668. uint32_t loaded_cnt = 0, N = 0;
  669. config_line_t *line;
  670. unsigned int i;
  671. build_time_t *loaded_times;
  672. int err = 0;
  673. circuit_build_times_init(cbt);
  674. if (circuit_build_times_disabled()) {
  675. return 0;
  676. }
  677. /* build_time_t 0 means uninitialized */
  678. loaded_times = tor_malloc_zero(sizeof(build_time_t)*state->TotalBuildTimes);
  679. for (line = state->BuildtimeHistogram; line; line = line->next) {
  680. smartlist_t *args = smartlist_create();
  681. smartlist_split_string(args, line->value, " ",
  682. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  683. if (smartlist_len(args) < 2) {
  684. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  685. "Too few arguments to CircuitBuildTime");
  686. err = 1;
  687. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  688. smartlist_free(args);
  689. break;
  690. } else {
  691. const char *ms_str = smartlist_get(args,0);
  692. const char *count_str = smartlist_get(args,1);
  693. uint32_t count, k;
  694. build_time_t ms;
  695. int ok;
  696. ms = (build_time_t)tor_parse_ulong(ms_str, 0, 0,
  697. CBT_BUILD_TIME_MAX, &ok, NULL);
  698. if (!ok) {
  699. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  700. "Unparsable bin number");
  701. err = 1;
  702. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  703. smartlist_free(args);
  704. break;
  705. }
  706. count = (uint32_t)tor_parse_ulong(count_str, 0, 0,
  707. UINT32_MAX, &ok, NULL);
  708. if (!ok) {
  709. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  710. "Unparsable bin count");
  711. err = 1;
  712. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  713. smartlist_free(args);
  714. break;
  715. }
  716. if (loaded_cnt+count+state->CircuitBuildAbandonedCount
  717. > state->TotalBuildTimes) {
  718. log_warn(LD_CIRC,
  719. "Too many build times in state file. "
  720. "Stopping short before %d",
  721. loaded_cnt+count);
  722. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  723. smartlist_free(args);
  724. break;
  725. }
  726. for (k = 0; k < count; k++) {
  727. loaded_times[loaded_cnt++] = ms;
  728. }
  729. N++;
  730. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  731. smartlist_free(args);
  732. }
  733. }
  734. log_info(LD_CIRC,
  735. "Adding %d timeouts.", state->CircuitBuildAbandonedCount);
  736. for (i=0; i < state->CircuitBuildAbandonedCount; i++) {
  737. loaded_times[loaded_cnt++] = CBT_BUILD_ABANDONED;
  738. }
  739. if (loaded_cnt != state->TotalBuildTimes) {
  740. log_warn(LD_CIRC,
  741. "Corrupt state file? Build times count mismatch. "
  742. "Read %d times, but file says %d", loaded_cnt,
  743. state->TotalBuildTimes);
  744. err = 1;
  745. circuit_build_times_reset(cbt);
  746. goto done;
  747. }
  748. circuit_build_times_shuffle_and_store_array(cbt, loaded_times, loaded_cnt);
  749. /* Verify that we didn't overwrite any indexes */
  750. for (i=0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  751. if (!cbt->circuit_build_times[i])
  752. break;
  753. tot_values++;
  754. }
  755. log_info(LD_CIRC,
  756. "Loaded %d/%d values from %d lines in circuit time histogram",
  757. tot_values, cbt->total_build_times, N);
  758. if (cbt->total_build_times != tot_values
  759. || cbt->total_build_times > CBT_NCIRCUITS_TO_OBSERVE) {
  760. log_warn(LD_CIRC,
  761. "Corrupt state file? Shuffled build times mismatch. "
  762. "Read %d times, but file says %d", tot_values,
  763. state->TotalBuildTimes);
  764. err = 1;
  765. circuit_build_times_reset(cbt);
  766. goto done;
  767. }
  768. circuit_build_times_set_timeout(cbt);
  769. if (!state->CircuitBuildAbandonedCount && cbt->total_build_times) {
  770. circuit_build_times_filter_timeouts(cbt);
  771. }
  772. done:
  773. tor_free(loaded_times);
  774. return err ? -1 : 0;
  775. }
  776. /**
  777. * Estimates the Xm and Alpha parameters using
  778. * http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
  779. *
  780. * The notable difference is that we use mode instead of min to estimate Xm.
  781. * This is because our distribution is frechet-like. We claim this is
  782. * an acceptable approximation because we are only concerned with the
  783. * accuracy of the CDF of the tail.
  784. */
  785. int
  786. circuit_build_times_update_alpha(circuit_build_times_t *cbt)
  787. {
  788. build_time_t *x=cbt->circuit_build_times;
  789. double a = 0;
  790. int n=0,i=0,abandoned_count=0;
  791. build_time_t max_time=0;
  792. /* http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation */
  793. /* We sort of cheat here and make our samples slightly more pareto-like
  794. * and less frechet-like. */
  795. cbt->Xm = circuit_build_times_get_xm(cbt);
  796. tor_assert(cbt->Xm > 0);
  797. for (i=0; i< CBT_NCIRCUITS_TO_OBSERVE; i++) {
  798. if (!x[i]) {
  799. continue;
  800. }
  801. if (x[i] < cbt->Xm) {
  802. a += tor_mathlog(cbt->Xm);
  803. } else if (x[i] == CBT_BUILD_ABANDONED) {
  804. abandoned_count++;
  805. } else {
  806. a += tor_mathlog(x[i]);
  807. if (x[i] > max_time)
  808. max_time = x[i];
  809. }
  810. n++;
  811. }
  812. /*
  813. * We are erring and asserting here because this can only happen
  814. * in codepaths other than startup. The startup state parsing code
  815. * performs this same check, and resets state if it hits it. If we
  816. * hit it at runtime, something serious has gone wrong.
  817. */
  818. if (n!=cbt->total_build_times) {
  819. log_err(LD_CIRC, "Discrepancy in build times count: %d vs %d", n,
  820. cbt->total_build_times);
  821. }
  822. tor_assert(n==cbt->total_build_times);
  823. if (max_time <= 0) {
  824. /* This can happen if Xm is actually the *maximum* value in the set.
  825. * It can also happen if we've abandoned every single circuit somehow.
  826. * In either case, tell the caller not to compute a new build timeout. */
  827. log_warn(LD_BUG,
  828. "Could not determine largest build time (%d). "
  829. "Xm is %dms and we've abandoned %d out of %d circuits.", max_time,
  830. cbt->Xm, abandoned_count, n);
  831. return 0;
  832. }
  833. a += abandoned_count*tor_mathlog(max_time);
  834. a -= n*tor_mathlog(cbt->Xm);
  835. // Estimator comes from Eq #4 in:
  836. // "Bayesian estimation based on trimmed samples from Pareto populations"
  837. // by Arturo J. Fernández. We are right-censored only.
  838. a = (n-abandoned_count)/a;
  839. cbt->alpha = a;
  840. return 1;
  841. }
  842. /**
  843. * This is the Pareto Quantile Function. It calculates the point x
  844. * in the distribution such that F(x) = quantile (ie quantile*100%
  845. * of the mass of the density function is below x on the curve).
  846. *
  847. * We use it to calculate the timeout and also to generate synthetic
  848. * values of time for circuits that timeout before completion.
  849. *
  850. * See http://en.wikipedia.org/wiki/Quantile_function,
  851. * http://en.wikipedia.org/wiki/Inverse_transform_sampling and
  852. * http://en.wikipedia.org/wiki/Pareto_distribution#Generating_a_
  853. * random_sample_from_Pareto_distribution
  854. * That's right. I'll cite wikipedia all day long.
  855. *
  856. * Return value is in milliseconds.
  857. */
  858. double
  859. circuit_build_times_calculate_timeout(circuit_build_times_t *cbt,
  860. double quantile)
  861. {
  862. double ret;
  863. tor_assert(quantile >= 0);
  864. tor_assert(1.0-quantile > 0);
  865. tor_assert(cbt->Xm > 0);
  866. ret = cbt->Xm/pow(1.0-quantile,1.0/cbt->alpha);
  867. if (ret > INT32_MAX) {
  868. ret = INT32_MAX;
  869. }
  870. tor_assert(ret > 0);
  871. return ret;
  872. }
  873. /** Pareto CDF */
  874. double
  875. circuit_build_times_cdf(circuit_build_times_t *cbt, double x)
  876. {
  877. double ret;
  878. tor_assert(cbt->Xm > 0);
  879. ret = 1.0-pow(cbt->Xm/x,cbt->alpha);
  880. tor_assert(0 <= ret && ret <= 1.0);
  881. return ret;
  882. }
  883. /**
  884. * Generate a synthetic time using our distribution parameters.
  885. *
  886. * The return value will be within the [q_lo, q_hi) quantile points
  887. * on the CDF.
  888. */
  889. build_time_t
  890. circuit_build_times_generate_sample(circuit_build_times_t *cbt,
  891. double q_lo, double q_hi)
  892. {
  893. double randval = crypto_rand_double();
  894. build_time_t ret;
  895. double u;
  896. /* Generate between [q_lo, q_hi) */
  897. /*XXXX This is what nextafter is supposed to be for; we should use it on the
  898. * platforms that support it. */
  899. q_hi -= 1.0/(INT32_MAX);
  900. tor_assert(q_lo >= 0);
  901. tor_assert(q_hi < 1);
  902. tor_assert(q_lo < q_hi);
  903. u = q_lo + (q_hi-q_lo)*randval;
  904. tor_assert(0 <= u && u < 1.0);
  905. /* circuit_build_times_calculate_timeout returns <= INT32_MAX */
  906. ret = (build_time_t)
  907. tor_lround(circuit_build_times_calculate_timeout(cbt, u));
  908. tor_assert(ret > 0);
  909. return ret;
  910. }
  911. /**
  912. * Estimate an initial alpha parameter by solving the quantile
  913. * function with a quantile point and a specific timeout value.
  914. */
  915. void
  916. circuit_build_times_initial_alpha(circuit_build_times_t *cbt,
  917. double quantile, double timeout_ms)
  918. {
  919. // Q(u) = Xm/((1-u)^(1/a))
  920. // Q(0.8) = Xm/((1-0.8))^(1/a)) = CircBuildTimeout
  921. // CircBuildTimeout = Xm/((1-0.8))^(1/a))
  922. // CircBuildTimeout = Xm*((1-0.8))^(-1/a))
  923. // ln(CircBuildTimeout) = ln(Xm)+ln(((1-0.8)))*(-1/a)
  924. // -ln(1-0.8)/(ln(CircBuildTimeout)-ln(Xm))=a
  925. tor_assert(quantile >= 0);
  926. tor_assert(cbt->Xm > 0);
  927. cbt->alpha = tor_mathlog(1.0-quantile)/
  928. (tor_mathlog(cbt->Xm)-tor_mathlog(timeout_ms));
  929. tor_assert(cbt->alpha > 0);
  930. }
  931. /**
  932. * Returns true if we need circuits to be built
  933. */
  934. int
  935. circuit_build_times_needs_circuits(circuit_build_times_t *cbt)
  936. {
  937. /* Return true if < MIN_CIRCUITS_TO_OBSERVE */
  938. return !circuit_build_times_enough_to_compute(cbt);
  939. }
  940. /**
  941. * Returns true if we should build a timeout test circuit
  942. * right now.
  943. */
  944. int
  945. circuit_build_times_needs_circuits_now(circuit_build_times_t *cbt)
  946. {
  947. return circuit_build_times_needs_circuits(cbt) &&
  948. approx_time()-cbt->last_circ_at > circuit_build_times_test_frequency();
  949. }
  950. /**
  951. * Called to indicate that the network showed some signs of liveness,
  952. * i.e. we received a cell.
  953. *
  954. * This is used by circuit_build_times_network_check_live() to decide
  955. * if we should record the circuit build timeout or not.
  956. *
  957. * This function is called every time we receive a cell. Avoid
  958. * syscalls, events, and other high-intensity work.
  959. */
  960. void
  961. circuit_build_times_network_is_live(circuit_build_times_t *cbt)
  962. {
  963. time_t now = approx_time();
  964. if (cbt->liveness.nonlive_timeouts > 0) {
  965. log_notice(LD_CIRC,
  966. "Tor now sees network activity. Restoring circuit build "
  967. "timeout recording. Network was down for %d seconds "
  968. "during %d circuit attempts.",
  969. (int)(now - cbt->liveness.network_last_live),
  970. cbt->liveness.nonlive_timeouts);
  971. }
  972. cbt->liveness.network_last_live = now;
  973. cbt->liveness.nonlive_timeouts = 0;
  974. }
  975. /**
  976. * Called to indicate that we completed a circuit. Because this circuit
  977. * succeeded, it doesn't count as a timeout-after-the-first-hop.
  978. *
  979. * This is used by circuit_build_times_network_check_changed() to determine
  980. * if we had too many recent timeouts and need to reset our learned timeout
  981. * to something higher.
  982. */
  983. void
  984. circuit_build_times_network_circ_success(circuit_build_times_t *cbt)
  985. {
  986. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx] = 0;
  987. cbt->liveness.after_firsthop_idx++;
  988. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  989. }
  990. /**
  991. * A circuit just timed out. If it failed after the first hop, record it
  992. * in our history for later deciding if the network speed has changed.
  993. *
  994. * This is used by circuit_build_times_network_check_changed() to determine
  995. * if we had too many recent timeouts and need to reset our learned timeout
  996. * to something higher.
  997. */
  998. static void
  999. circuit_build_times_network_timeout(circuit_build_times_t *cbt,
  1000. int did_onehop)
  1001. {
  1002. if (did_onehop) {
  1003. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]=1;
  1004. cbt->liveness.after_firsthop_idx++;
  1005. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1006. }
  1007. }
  1008. /**
  1009. * A circuit was just forcibly closed. If there has been no recent network
  1010. * activity at all, but this circuit was launched back when we thought the
  1011. * network was live, increment the number of "nonlive" circuit timeouts.
  1012. *
  1013. * This is used by circuit_build_times_network_check_live() to decide
  1014. * if we should record the circuit build timeout or not.
  1015. */
  1016. static void
  1017. circuit_build_times_network_close(circuit_build_times_t *cbt,
  1018. int did_onehop, time_t start_time)
  1019. {
  1020. time_t now = time(NULL);
  1021. /*
  1022. * Check if this is a timeout that was for a circuit that spent its
  1023. * entire existence during a time where we have had no network activity.
  1024. */
  1025. if (cbt->liveness.network_last_live < start_time) {
  1026. if (did_onehop) {
  1027. char last_live_buf[ISO_TIME_LEN+1];
  1028. char start_time_buf[ISO_TIME_LEN+1];
  1029. char now_buf[ISO_TIME_LEN+1];
  1030. format_local_iso_time(last_live_buf, cbt->liveness.network_last_live);
  1031. format_local_iso_time(start_time_buf, start_time);
  1032. format_local_iso_time(now_buf, now);
  1033. log_warn(LD_BUG,
  1034. "Circuit somehow completed a hop while the network was "
  1035. "not live. Network was last live at %s, but circuit launched "
  1036. "at %s. It's now %s.", last_live_buf, start_time_buf,
  1037. now_buf);
  1038. }
  1039. cbt->liveness.nonlive_timeouts++;
  1040. if (cbt->liveness.nonlive_timeouts == 1) {
  1041. log_notice(LD_CIRC,
  1042. "Tor has not observed any network activity for the past %d "
  1043. "seconds. Disabling circuit build timeout recording.",
  1044. (int)(now - cbt->liveness.network_last_live));
  1045. } else {
  1046. log_info(LD_CIRC,
  1047. "Got non-live timeout. Current count is: %d",
  1048. cbt->liveness.nonlive_timeouts);
  1049. }
  1050. }
  1051. }
  1052. /**
  1053. * When the network is not live, we do not record circuit build times.
  1054. *
  1055. * The network is considered not live if there has been at least one
  1056. * circuit build that began and ended (had its close_ms measurement
  1057. * period expire) since we last received a cell.
  1058. *
  1059. * Also has the side effect of rewinding the circuit time history
  1060. * in the case of recent liveness changes.
  1061. */
  1062. int
  1063. circuit_build_times_network_check_live(circuit_build_times_t *cbt)
  1064. {
  1065. if (cbt->liveness.nonlive_timeouts > 0) {
  1066. return 0;
  1067. }
  1068. return 1;
  1069. }
  1070. /**
  1071. * Returns true if we have seen more than MAX_RECENT_TIMEOUT_COUNT of
  1072. * the past RECENT_CIRCUITS time out after the first hop. Used to detect
  1073. * if the network connection has changed significantly, and if so,
  1074. * resets our circuit build timeout to the default.
  1075. *
  1076. * Also resets the entire timeout history in this case and causes us
  1077. * to restart the process of building test circuits and estimating a
  1078. * new timeout.
  1079. */
  1080. int
  1081. circuit_build_times_network_check_changed(circuit_build_times_t *cbt)
  1082. {
  1083. int total_build_times = cbt->total_build_times;
  1084. int timeout_count=0;
  1085. int i;
  1086. /* how many of our recent circuits made it to the first hop but then
  1087. * timed out? */
  1088. for (i = 0; i < cbt->liveness.num_recent_circs; i++) {
  1089. timeout_count += cbt->liveness.timeouts_after_firsthop[i];
  1090. }
  1091. /* If 80% of our recent circuits are timing out after the first hop,
  1092. * we need to re-estimate a new initial alpha and timeout. */
  1093. if (timeout_count < circuit_build_times_max_timeouts()) {
  1094. return 0;
  1095. }
  1096. circuit_build_times_reset(cbt);
  1097. memset(cbt->liveness.timeouts_after_firsthop, 0,
  1098. sizeof(*cbt->liveness.timeouts_after_firsthop)*
  1099. cbt->liveness.num_recent_circs);
  1100. cbt->liveness.after_firsthop_idx = 0;
  1101. /* Check to see if this has happened before. If so, double the timeout
  1102. * to give people on abysmally bad network connections a shot at access */
  1103. if (cbt->timeout_ms >= circuit_build_times_get_initial_timeout()) {
  1104. if (cbt->timeout_ms > INT32_MAX/2 || cbt->close_ms > INT32_MAX/2) {
  1105. log_warn(LD_CIRC, "Insanely large circuit build timeout value. "
  1106. "(timeout = %lfmsec, close = %lfmsec)",
  1107. cbt->timeout_ms, cbt->close_ms);
  1108. } else {
  1109. cbt->timeout_ms *= 2;
  1110. cbt->close_ms *= 2;
  1111. }
  1112. } else {
  1113. cbt->close_ms = cbt->timeout_ms
  1114. = circuit_build_times_get_initial_timeout();
  1115. }
  1116. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  1117. log_notice(LD_CIRC,
  1118. "Your network connection speed appears to have changed. Resetting "
  1119. "timeout to %lds after %d timeouts and %d buildtimes.",
  1120. tor_lround(cbt->timeout_ms/1000), timeout_count,
  1121. total_build_times);
  1122. return 1;
  1123. }
  1124. /**
  1125. * Count the number of timeouts in a set of cbt data.
  1126. */
  1127. double
  1128. circuit_build_times_timeout_rate(const circuit_build_times_t *cbt)
  1129. {
  1130. int i=0,timeouts=0;
  1131. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1132. if (cbt->circuit_build_times[i] >= cbt->timeout_ms) {
  1133. timeouts++;
  1134. }
  1135. }
  1136. if (!cbt->total_build_times)
  1137. return 0;
  1138. return ((double)timeouts)/cbt->total_build_times;
  1139. }
  1140. /**
  1141. * Count the number of closed circuits in a set of cbt data.
  1142. */
  1143. double
  1144. circuit_build_times_close_rate(const circuit_build_times_t *cbt)
  1145. {
  1146. int i=0,closed=0;
  1147. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1148. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED) {
  1149. closed++;
  1150. }
  1151. }
  1152. if (!cbt->total_build_times)
  1153. return 0;
  1154. return ((double)closed)/cbt->total_build_times;
  1155. }
  1156. /**
  1157. * Store a timeout as a synthetic value.
  1158. *
  1159. * Returns true if the store was successful and we should possibly
  1160. * update our timeout estimate.
  1161. */
  1162. int
  1163. circuit_build_times_count_close(circuit_build_times_t *cbt,
  1164. int did_onehop,
  1165. time_t start_time)
  1166. {
  1167. if (circuit_build_times_disabled()) {
  1168. cbt->close_ms = cbt->timeout_ms
  1169. = circuit_build_times_get_initial_timeout();
  1170. return 0;
  1171. }
  1172. /* Record this force-close to help determine if the network is dead */
  1173. circuit_build_times_network_close(cbt, did_onehop, start_time);
  1174. /* Only count timeouts if network is live.. */
  1175. if (!circuit_build_times_network_check_live(cbt)) {
  1176. return 0;
  1177. }
  1178. circuit_build_times_add_time(cbt, CBT_BUILD_ABANDONED);
  1179. return 1;
  1180. }
  1181. /**
  1182. * Update timeout counts to determine if we need to expire
  1183. * our build time history due to excessive timeouts.
  1184. *
  1185. * We do not record any actual time values at this stage;
  1186. * we are only interested in recording the fact that a timeout
  1187. * happened. We record the time values via
  1188. * circuit_build_times_count_close() and circuit_build_times_add_time().
  1189. */
  1190. void
  1191. circuit_build_times_count_timeout(circuit_build_times_t *cbt,
  1192. int did_onehop)
  1193. {
  1194. if (circuit_build_times_disabled()) {
  1195. cbt->close_ms = cbt->timeout_ms
  1196. = circuit_build_times_get_initial_timeout();
  1197. return;
  1198. }
  1199. /* Register the fact that a timeout just occurred. */
  1200. circuit_build_times_network_timeout(cbt, did_onehop);
  1201. /* If there are a ton of timeouts, we should reset
  1202. * the circuit build timeout. */
  1203. circuit_build_times_network_check_changed(cbt);
  1204. }
  1205. /**
  1206. * Estimate a new timeout based on history and set our timeout
  1207. * variable accordingly.
  1208. */
  1209. static int
  1210. circuit_build_times_set_timeout_worker(circuit_build_times_t *cbt)
  1211. {
  1212. build_time_t max_time;
  1213. if (!circuit_build_times_enough_to_compute(cbt))
  1214. return 0;
  1215. if (!circuit_build_times_update_alpha(cbt))
  1216. return 0;
  1217. cbt->timeout_ms = circuit_build_times_calculate_timeout(cbt,
  1218. circuit_build_times_quantile_cutoff());
  1219. cbt->close_ms = circuit_build_times_calculate_timeout(cbt,
  1220. circuit_build_times_close_quantile());
  1221. max_time = circuit_build_times_max(cbt);
  1222. /* Sometimes really fast guard nodes give us such a steep curve
  1223. * that this ends up being not that much greater than timeout_ms.
  1224. * Make it be at least 1 min to handle this case. */
  1225. cbt->close_ms = MAX(cbt->close_ms, circuit_build_times_initial_timeout());
  1226. if (cbt->timeout_ms > max_time) {
  1227. log_notice(LD_CIRC,
  1228. "Circuit build timeout of %dms is beyond the maximum build "
  1229. "time we have ever observed. Capping it to %dms.",
  1230. (int)cbt->timeout_ms, max_time);
  1231. cbt->timeout_ms = max_time;
  1232. }
  1233. if (max_time < INT32_MAX/2 && cbt->close_ms > 2*max_time) {
  1234. log_info(LD_CIRC,
  1235. "Circuit build measurement period of %dms is more than twice "
  1236. "the maximum build time we have ever observed. Capping it to "
  1237. "%dms.", (int)cbt->close_ms, 2*max_time);
  1238. cbt->close_ms = 2*max_time;
  1239. }
  1240. cbt->have_computed_timeout = 1;
  1241. return 1;
  1242. }
  1243. /**
  1244. * Exposed function to compute a new timeout. Dispatches events and
  1245. * also filters out extremely high timeout values.
  1246. */
  1247. void
  1248. circuit_build_times_set_timeout(circuit_build_times_t *cbt)
  1249. {
  1250. long prev_timeout = tor_lround(cbt->timeout_ms/1000);
  1251. double timeout_rate;
  1252. if (!circuit_build_times_set_timeout_worker(cbt))
  1253. return;
  1254. if (cbt->timeout_ms < circuit_build_times_min_timeout()) {
  1255. log_warn(LD_CIRC, "Set buildtimeout to low value %lfms. Setting to %dms",
  1256. cbt->timeout_ms, circuit_build_times_min_timeout());
  1257. cbt->timeout_ms = circuit_build_times_min_timeout();
  1258. if (cbt->close_ms < cbt->timeout_ms) {
  1259. /* This shouldn't happen because of MAX() in timeout_worker above,
  1260. * but doing it just in case */
  1261. cbt->close_ms = circuit_build_times_initial_timeout();
  1262. }
  1263. }
  1264. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_COMPUTED);
  1265. timeout_rate = circuit_build_times_timeout_rate(cbt);
  1266. if (prev_timeout > tor_lround(cbt->timeout_ms/1000)) {
  1267. log_notice(LD_CIRC,
  1268. "Based on %d circuit times, it looks like we don't need to "
  1269. "wait so long for circuits to finish. We will now assume a "
  1270. "circuit is too slow to use after waiting %ld seconds.",
  1271. cbt->total_build_times,
  1272. tor_lround(cbt->timeout_ms/1000));
  1273. log_info(LD_CIRC,
  1274. "Circuit timeout data: %lfms, %lfms, Xm: %d, a: %lf, r: %lf",
  1275. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1276. timeout_rate);
  1277. } else if (prev_timeout < tor_lround(cbt->timeout_ms/1000)) {
  1278. log_notice(LD_CIRC,
  1279. "Based on %d circuit times, it looks like we need to wait "
  1280. "longer for circuits to finish. We will now assume a "
  1281. "circuit is too slow to use after waiting %ld seconds.",
  1282. cbt->total_build_times,
  1283. tor_lround(cbt->timeout_ms/1000));
  1284. log_info(LD_CIRC,
  1285. "Circuit timeout data: %lfms, %lfms, Xm: %d, a: %lf, r: %lf",
  1286. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1287. timeout_rate);
  1288. } else {
  1289. log_info(LD_CIRC,
  1290. "Set circuit build timeout to %lds (%lfms, %lfms, Xm: %d, a: %lf,"
  1291. " r: %lf) based on %d circuit times",
  1292. tor_lround(cbt->timeout_ms/1000),
  1293. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha, timeout_rate,
  1294. cbt->total_build_times);
  1295. }
  1296. }
  1297. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  1298. * and with the high bit specified by conn-\>circ_id_type, until we get
  1299. * a circ_id that is not in use by any other circuit on that conn.
  1300. *
  1301. * Return it, or 0 if can't get a unique circ_id.
  1302. */
  1303. static circid_t
  1304. get_unique_circ_id_by_conn(or_connection_t *conn)
  1305. {
  1306. circid_t test_circ_id;
  1307. circid_t attempts=0;
  1308. circid_t high_bit;
  1309. tor_assert(conn);
  1310. if (conn->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  1311. log_warn(LD_BUG, "Trying to pick a circuit ID for a connection from "
  1312. "a client with no identity.");
  1313. return 0;
  1314. }
  1315. high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  1316. do {
  1317. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  1318. * circID such that (high_bit|test_circ_id) is not already used. */
  1319. test_circ_id = conn->next_circ_id++;
  1320. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  1321. test_circ_id = 1;
  1322. conn->next_circ_id = 2;
  1323. }
  1324. if (++attempts > 1<<15) {
  1325. /* Make sure we don't loop forever if all circ_id's are used. This
  1326. * matters because it's an external DoS opportunity.
  1327. */
  1328. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  1329. return 0;
  1330. }
  1331. test_circ_id |= high_bit;
  1332. } while (circuit_id_in_use_on_orconn(test_circ_id, conn));
  1333. return test_circ_id;
  1334. }
  1335. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  1336. * the currently built elements of circuit_t. If <b>verbose</b> is true, also
  1337. * list information about link status in a more verbose format using spaces.
  1338. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  1339. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  1340. * names.
  1341. */
  1342. static char *
  1343. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  1344. {
  1345. crypt_path_t *hop;
  1346. smartlist_t *elements;
  1347. const char *states[] = {"closed", "waiting for keys", "open"};
  1348. char *s;
  1349. elements = smartlist_create();
  1350. if (verbose) {
  1351. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  1352. char *cp;
  1353. tor_asprintf(&cp, "%s%s circ (length %d%s%s):",
  1354. circ->build_state->is_internal ? "internal" : "exit",
  1355. circ->build_state->need_uptime ? " (high-uptime)" : "",
  1356. circ->build_state->desired_path_len,
  1357. circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  1358. circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
  1359. (nickname?nickname:"*unnamed*"));
  1360. smartlist_add(elements, cp);
  1361. }
  1362. hop = circ->cpath;
  1363. do {
  1364. routerinfo_t *ri;
  1365. routerstatus_t *rs;
  1366. char *elt;
  1367. const char *id;
  1368. if (!hop)
  1369. break;
  1370. if (!verbose && hop->state != CPATH_STATE_OPEN)
  1371. break;
  1372. if (!hop->extend_info)
  1373. break;
  1374. id = hop->extend_info->identity_digest;
  1375. if (verbose_names) {
  1376. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  1377. if ((ri = router_get_by_digest(id))) {
  1378. router_get_verbose_nickname(elt, ri);
  1379. } else if ((rs = router_get_consensus_status_by_id(id))) {
  1380. routerstatus_get_verbose_nickname(elt, rs);
  1381. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  1382. elt[0] = '$';
  1383. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  1384. elt[HEX_DIGEST_LEN+1]= '~';
  1385. strlcpy(elt+HEX_DIGEST_LEN+2,
  1386. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  1387. } else {
  1388. elt[0] = '$';
  1389. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  1390. }
  1391. } else { /* ! verbose_names */
  1392. if ((ri = router_get_by_digest(id)) &&
  1393. ri->is_named) {
  1394. elt = tor_strdup(hop->extend_info->nickname);
  1395. } else {
  1396. elt = tor_malloc(HEX_DIGEST_LEN+2);
  1397. elt[0] = '$';
  1398. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  1399. }
  1400. }
  1401. tor_assert(elt);
  1402. if (verbose) {
  1403. size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
  1404. char *v = tor_malloc(len);
  1405. tor_assert(hop->state <= 2);
  1406. tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
  1407. smartlist_add(elements, v);
  1408. tor_free(elt);
  1409. } else {
  1410. smartlist_add(elements, elt);
  1411. }
  1412. hop = hop->next;
  1413. } while (hop != circ->cpath);
  1414. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  1415. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  1416. smartlist_free(elements);
  1417. return s;
  1418. }
  1419. /** If <b>verbose</b> is false, allocate and return a comma-separated
  1420. * list of the currently built elements of circuit_t. If
  1421. * <b>verbose</b> is true, also list information about link status in
  1422. * a more verbose format using spaces.
  1423. */
  1424. char *
  1425. circuit_list_path(origin_circuit_t *circ, int verbose)
  1426. {
  1427. return circuit_list_path_impl(circ, verbose, 0);
  1428. }
  1429. /** Allocate and return a comma-separated list of the currently built elements
  1430. * of circuit_t, giving each as a verbose nickname.
  1431. */
  1432. char *
  1433. circuit_list_path_for_controller(origin_circuit_t *circ)
  1434. {
  1435. return circuit_list_path_impl(circ, 0, 1);
  1436. }
  1437. /** Log, at severity <b>severity</b>, the nicknames of each router in
  1438. * circ's cpath. Also log the length of the cpath, and the intended
  1439. * exit point.
  1440. */
  1441. void
  1442. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  1443. {
  1444. char *s = circuit_list_path(circ,1);
  1445. tor_log(severity,domain,"%s",s);
  1446. tor_free(s);
  1447. }
  1448. /** Tell the rep(utation)hist(ory) module about the status of the links
  1449. * in circ. Hops that have become OPEN are marked as successfully
  1450. * extended; the _first_ hop that isn't open (if any) is marked as
  1451. * unable to extend.
  1452. */
  1453. /* XXXX Someday we should learn from OR circuits too. */
  1454. void
  1455. circuit_rep_hist_note_result(origin_circuit_t *circ)
  1456. {
  1457. crypt_path_t *hop;
  1458. char *prev_digest = NULL;
  1459. routerinfo_t *router;
  1460. hop = circ->cpath;
  1461. if (!hop) /* circuit hasn't started building yet. */
  1462. return;
  1463. if (server_mode(get_options())) {
  1464. routerinfo_t *me = router_get_my_routerinfo();
  1465. if (!me)
  1466. return;
  1467. prev_digest = me->cache_info.identity_digest;
  1468. }
  1469. do {
  1470. router = router_get_by_digest(hop->extend_info->identity_digest);
  1471. if (router) {
  1472. if (prev_digest) {
  1473. if (hop->state == CPATH_STATE_OPEN)
  1474. rep_hist_note_extend_succeeded(prev_digest,
  1475. router->cache_info.identity_digest);
  1476. else {
  1477. rep_hist_note_extend_failed(prev_digest,
  1478. router->cache_info.identity_digest);
  1479. break;
  1480. }
  1481. }
  1482. prev_digest = router->cache_info.identity_digest;
  1483. } else {
  1484. prev_digest = NULL;
  1485. }
  1486. hop=hop->next;
  1487. } while (hop!=circ->cpath);
  1488. }
  1489. /** Pick all the entries in our cpath. Stop and return 0 when we're
  1490. * happy, or return -1 if an error occurs. */
  1491. static int
  1492. onion_populate_cpath(origin_circuit_t *circ)
  1493. {
  1494. int r;
  1495. again:
  1496. r = onion_extend_cpath(circ);
  1497. if (r < 0) {
  1498. log_info(LD_CIRC,"Generating cpath hop failed.");
  1499. return -1;
  1500. }
  1501. if (r == 0)
  1502. goto again;
  1503. return 0; /* if r == 1 */
  1504. }
  1505. /** Create and return a new origin circuit. Initialize its purpose and
  1506. * build-state based on our arguments. The <b>flags</b> argument is a
  1507. * bitfield of CIRCLAUNCH_* flags. */
  1508. origin_circuit_t *
  1509. origin_circuit_init(uint8_t purpose, int flags)
  1510. {
  1511. /* sets circ->p_circ_id and circ->p_conn */
  1512. origin_circuit_t *circ = origin_circuit_new();
  1513. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
  1514. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  1515. circ->build_state->onehop_tunnel =
  1516. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  1517. circ->build_state->need_uptime =
  1518. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  1519. circ->build_state->need_capacity =
  1520. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  1521. circ->build_state->is_internal =
  1522. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  1523. circ->_base.purpose = purpose;
  1524. return circ;
  1525. }
  1526. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  1527. * is defined, then use that as your exit router, else choose a suitable
  1528. * exit node.
  1529. *
  1530. * Also launch a connection to the first OR in the chosen path, if
  1531. * it's not open already.
  1532. */
  1533. origin_circuit_t *
  1534. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  1535. {
  1536. origin_circuit_t *circ;
  1537. int err_reason = 0;
  1538. circ = origin_circuit_init(purpose, flags);
  1539. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  1540. onion_populate_cpath(circ) < 0) {
  1541. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  1542. return NULL;
  1543. }
  1544. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  1545. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  1546. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1547. return NULL;
  1548. }
  1549. return circ;
  1550. }
  1551. /** Start establishing the first hop of our circuit. Figure out what
  1552. * OR we should connect to, and if necessary start the connection to
  1553. * it. If we're already connected, then send the 'create' cell.
  1554. * Return 0 for ok, -reason if circ should be marked-for-close. */
  1555. int
  1556. circuit_handle_first_hop(origin_circuit_t *circ)
  1557. {
  1558. crypt_path_t *firsthop;
  1559. or_connection_t *n_conn;
  1560. int err_reason = 0;
  1561. const char *msg = NULL;
  1562. int should_launch = 0;
  1563. firsthop = onion_next_hop_in_cpath(circ->cpath);
  1564. tor_assert(firsthop);
  1565. tor_assert(firsthop->extend_info);
  1566. /* now see if we're already connected to the first OR in 'route' */
  1567. log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",
  1568. fmt_addr(&firsthop->extend_info->addr),
  1569. firsthop->extend_info->port);
  1570. n_conn = connection_or_get_for_extend(firsthop->extend_info->identity_digest,
  1571. &firsthop->extend_info->addr,
  1572. &msg,
  1573. &should_launch);
  1574. if (!n_conn) {
  1575. /* not currently connected in a useful way. */
  1576. const char *name = strlen(firsthop->extend_info->nickname) ?
  1577. firsthop->extend_info->nickname : fmt_addr(&firsthop->extend_info->addr);
  1578. log_info(LD_CIRC, "Next router is %s: %s ",
  1579. safe_str_client(name), msg?msg:"???");
  1580. circ->_base.n_hop = extend_info_dup(firsthop->extend_info);
  1581. if (should_launch) {
  1582. if (circ->build_state->onehop_tunnel)
  1583. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  1584. n_conn = connection_or_connect(&firsthop->extend_info->addr,
  1585. firsthop->extend_info->port,
  1586. firsthop->extend_info->identity_digest);
  1587. if (!n_conn) { /* connect failed, forget the whole thing */
  1588. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  1589. return -END_CIRC_REASON_CONNECTFAILED;
  1590. }
  1591. }
  1592. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  1593. /* return success. The onion/circuit/etc will be taken care of
  1594. * automatically (may already have been) whenever n_conn reaches
  1595. * OR_CONN_STATE_OPEN.
  1596. */
  1597. return 0;
  1598. } else { /* it's already open. use it. */
  1599. tor_assert(!circ->_base.n_hop);
  1600. circ->_base.n_conn = n_conn;
  1601. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  1602. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  1603. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  1604. return err_reason;
  1605. }
  1606. }
  1607. return 0;
  1608. }
  1609. /** Find any circuits that are waiting on <b>or_conn</b> to become
  1610. * open and get them to send their create cells forward.
  1611. *
  1612. * Status is 1 if connect succeeded, or 0 if connect failed.
  1613. */
  1614. void
  1615. circuit_n_conn_done(or_connection_t *or_conn, int status)
  1616. {
  1617. smartlist_t *pending_circs;
  1618. int err_reason = 0;
  1619. log_debug(LD_CIRC,"or_conn to %s/%s, status=%d",
  1620. or_conn->nickname ? or_conn->nickname : "NULL",
  1621. or_conn->_base.address, status);
  1622. pending_circs = smartlist_create();
  1623. circuit_get_all_pending_on_or_conn(pending_circs, or_conn);
  1624. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  1625. {
  1626. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  1627. * leaving them in in case it's possible for the status of a circuit to
  1628. * change as we're going down the list. */
  1629. if (circ->marked_for_close || circ->n_conn || !circ->n_hop ||
  1630. circ->state != CIRCUIT_STATE_OR_WAIT)
  1631. continue;
  1632. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  1633. /* Look at addr/port. This is an unkeyed connection. */
  1634. if (!tor_addr_eq(&circ->n_hop->addr, &or_conn->_base.addr) ||
  1635. circ->n_hop->port != or_conn->_base.port)
  1636. continue;
  1637. } else {
  1638. /* We expected a key. See if it's the right one. */
  1639. if (memcmp(or_conn->identity_digest,
  1640. circ->n_hop->identity_digest, DIGEST_LEN))
  1641. continue;
  1642. }
  1643. if (!status) { /* or_conn failed; close circ */
  1644. log_info(LD_CIRC,"or_conn failed. Closing circ.");
  1645. circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
  1646. continue;
  1647. }
  1648. log_debug(LD_CIRC, "Found circ, sending create cell.");
  1649. /* circuit_deliver_create_cell will set n_circ_id and add us to
  1650. * orconn_circuid_circuit_map, so we don't need to call
  1651. * set_circid_orconn here. */
  1652. circ->n_conn = or_conn;
  1653. extend_info_free(circ->n_hop);
  1654. circ->n_hop = NULL;
  1655. if (CIRCUIT_IS_ORIGIN(circ)) {
  1656. if ((err_reason =
  1657. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  1658. log_info(LD_CIRC,
  1659. "send_next_onion_skin failed; circuit marked for closing.");
  1660. circuit_mark_for_close(circ, -err_reason);
  1661. continue;
  1662. /* XXX could this be bad, eg if next_onion_skin failed because conn
  1663. * died? */
  1664. }
  1665. } else {
  1666. /* pull the create cell out of circ->onionskin, and send it */
  1667. tor_assert(circ->n_conn_onionskin);
  1668. if (circuit_deliver_create_cell(circ,CELL_CREATE,
  1669. circ->n_conn_onionskin)<0) {
  1670. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  1671. continue;
  1672. }
  1673. tor_free(circ->n_conn_onionskin);
  1674. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  1675. }
  1676. }
  1677. SMARTLIST_FOREACH_END(circ);
  1678. smartlist_free(pending_circs);
  1679. }
  1680. /** Find a new circid that isn't currently in use on the circ->n_conn
  1681. * for the outgoing
  1682. * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
  1683. * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
  1684. * to this circuit.
  1685. * Return -1 if we failed to find a suitable circid, else return 0.
  1686. */
  1687. static int
  1688. circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
  1689. const char *payload)
  1690. {
  1691. cell_t cell;
  1692. circid_t id;
  1693. tor_assert(circ);
  1694. tor_assert(circ->n_conn);
  1695. tor_assert(payload);
  1696. tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
  1697. id = get_unique_circ_id_by_conn(circ->n_conn);
  1698. if (!id) {
  1699. log_warn(LD_CIRC,"failed to get unique circID.");
  1700. return -1;
  1701. }
  1702. log_debug(LD_CIRC,"Chosen circID %u.", id);
  1703. circuit_set_n_circid_orconn(circ, id, circ->n_conn);
  1704. memset(&cell, 0, sizeof(cell_t));
  1705. cell.command = cell_type;
  1706. cell.circ_id = circ->n_circ_id;
  1707. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  1708. append_cell_to_circuit_queue(circ, circ->n_conn, &cell,
  1709. CELL_DIRECTION_OUT, 0);
  1710. if (CIRCUIT_IS_ORIGIN(circ)) {
  1711. /* mark it so it gets better rate limiting treatment. */
  1712. circ->n_conn->client_used = time(NULL);
  1713. }
  1714. return 0;
  1715. }
  1716. /** We've decided to start our reachability testing. If all
  1717. * is set, log this to the user. Return 1 if we did, or 0 if
  1718. * we chose not to log anything. */
  1719. int
  1720. inform_testing_reachability(void)
  1721. {
  1722. char dirbuf[128];
  1723. routerinfo_t *me = router_get_my_routerinfo();
  1724. if (!me)
  1725. return 0;
  1726. control_event_server_status(LOG_NOTICE,
  1727. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  1728. me->address, me->or_port);
  1729. if (me->dir_port) {
  1730. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  1731. me->address, me->dir_port);
  1732. control_event_server_status(LOG_NOTICE,
  1733. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  1734. me->address, me->dir_port);
  1735. }
  1736. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  1737. "(this may take up to %d minutes -- look for log "
  1738. "messages indicating success)",
  1739. me->address, me->or_port,
  1740. me->dir_port ? dirbuf : "",
  1741. me->dir_port ? "are" : "is",
  1742. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  1743. return 1;
  1744. }
  1745. /** Return true iff we should send a create_fast cell to start building a given
  1746. * circuit */
  1747. static INLINE int
  1748. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  1749. {
  1750. or_options_t *options = get_options();
  1751. tor_assert(circ->cpath);
  1752. tor_assert(circ->cpath->extend_info);
  1753. if (!circ->cpath->extend_info->onion_key)
  1754. return 1; /* our hand is forced: only a create_fast will work. */
  1755. if (!options->FastFirstHopPK)
  1756. return 0; /* we prefer to avoid create_fast */
  1757. if (server_mode(options)) {
  1758. /* We're a server, and we know an onion key. We can choose.
  1759. * Prefer to blend in. */
  1760. return 0;
  1761. }
  1762. return 1;
  1763. }
  1764. /** Return true if <b>circ</b> is the type of circuit we want to count
  1765. * timeouts from. In particular, we want it to have not completed yet
  1766. * (already completing indicates we cannibalized it), and we want it to
  1767. * have exactly three hops.
  1768. */
  1769. int
  1770. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  1771. {
  1772. return !circ->has_opened
  1773. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  1774. }
  1775. /** This is the backbone function for building circuits.
  1776. *
  1777. * If circ's first hop is closed, then we need to build a create
  1778. * cell and send it forward.
  1779. *
  1780. * Otherwise, we need to build a relay extend cell and send it
  1781. * forward.
  1782. *
  1783. * Return -reason if we want to tear down circ, else return 0.
  1784. */
  1785. int
  1786. circuit_send_next_onion_skin(origin_circuit_t *circ)
  1787. {
  1788. crypt_path_t *hop;
  1789. routerinfo_t *router;
  1790. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  1791. char *onionskin;
  1792. size_t payload_len;
  1793. tor_assert(circ);
  1794. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  1795. int fast;
  1796. uint8_t cell_type;
  1797. log_debug(LD_CIRC,"First skin; sending create cell.");
  1798. if (circ->build_state->onehop_tunnel)
  1799. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  1800. else
  1801. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  1802. router = router_get_by_digest(circ->_base.n_conn->identity_digest);
  1803. fast = should_use_create_fast_for_circuit(circ);
  1804. if (!fast) {
  1805. /* We are an OR and we know the right onion key: we should
  1806. * send an old slow create cell.
  1807. */
  1808. cell_type = CELL_CREATE;
  1809. if (onion_skin_create(circ->cpath->extend_info->onion_key,
  1810. &(circ->cpath->dh_handshake_state),
  1811. payload) < 0) {
  1812. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  1813. return - END_CIRC_REASON_INTERNAL;
  1814. }
  1815. note_request("cell: create", 1);
  1816. } else {
  1817. /* We are not an OR, and we're building the first hop of a circuit to a
  1818. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  1819. * and a DH operation. */
  1820. cell_type = CELL_CREATE_FAST;
  1821. memset(payload, 0, sizeof(payload));
  1822. crypto_rand((char*) circ->cpath->fast_handshake_state,
  1823. sizeof(circ->cpath->fast_handshake_state));
  1824. memcpy(payload, circ->cpath->fast_handshake_state,
  1825. sizeof(circ->cpath->fast_handshake_state));
  1826. note_request("cell: create fast", 1);
  1827. }
  1828. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
  1829. return - END_CIRC_REASON_RESOURCELIMIT;
  1830. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  1831. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1832. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  1833. fast ? "CREATE_FAST" : "CREATE",
  1834. router ? router->nickname : "<unnamed>");
  1835. } else {
  1836. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  1837. tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
  1838. log_debug(LD_CIRC,"starting to send subsequent skin.");
  1839. hop = onion_next_hop_in_cpath(circ->cpath);
  1840. if (!hop) {
  1841. /* done building the circuit. whew. */
  1842. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1843. if (circuit_timeout_want_to_count_circ(circ)) {
  1844. struct timeval end;
  1845. long timediff;
  1846. tor_gettimeofday(&end);
  1847. timediff = tv_mdiff(&circ->_base.timestamp_created, &end);
  1848. /*
  1849. * If the circuit build time is much greater than we would have cut
  1850. * it off at, we probably had a suspend event along this codepath,
  1851. * and we should discard the value.
  1852. */
  1853. if (timediff < 0 || timediff > 2*circ_times.close_ms+1000) {
  1854. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  1855. "Assuming clock jump. Purpose %d (%s)", timediff,
  1856. circ->_base.purpose,
  1857. circuit_purpose_to_string(circ->_base.purpose));
  1858. } else if (!circuit_build_times_disabled()) {
  1859. /* Only count circuit times if the network is live */
  1860. if (circuit_build_times_network_check_live(&circ_times)) {
  1861. circuit_build_times_add_time(&circ_times, (build_time_t)timediff);
  1862. circuit_build_times_set_timeout(&circ_times);
  1863. }
  1864. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1865. circuit_build_times_network_circ_success(&circ_times);
  1866. }
  1867. }
  1868. }
  1869. log_info(LD_CIRC,"circuit built!");
  1870. circuit_reset_failure_count(0);
  1871. if (circ->build_state->onehop_tunnel)
  1872. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  1873. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  1874. or_options_t *options = get_options();
  1875. can_complete_circuit=1;
  1876. /* FFFF Log a count of known routers here */
  1877. log_notice(LD_GENERAL,
  1878. "Tor has successfully opened a circuit. "
  1879. "Looks like client functionality is working.");
  1880. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  1881. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  1882. if (server_mode(options) && !check_whether_orport_reachable()) {
  1883. inform_testing_reachability();
  1884. consider_testing_reachability(1, 1);
  1885. }
  1886. }
  1887. circuit_rep_hist_note_result(circ);
  1888. circuit_has_opened(circ); /* do other actions as necessary */
  1889. /* We're done with measurement circuits here. Just close them */
  1890. if (circ->_base.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  1891. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  1892. return 0;
  1893. }
  1894. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  1895. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  1896. return - END_CIRC_REASON_INTERNAL;
  1897. }
  1898. set_uint32(payload, tor_addr_to_ipv4n(&hop->extend_info->addr));
  1899. set_uint16(payload+4, htons(hop->extend_info->port));
  1900. onionskin = payload+2+4;
  1901. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
  1902. hop->extend_info->identity_digest, DIGEST_LEN);
  1903. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  1904. if (onion_skin_create(hop->extend_info->onion_key,
  1905. &(hop->dh_handshake_state), onionskin) < 0) {
  1906. log_warn(LD_CIRC,"onion_skin_create failed.");
  1907. return - END_CIRC_REASON_INTERNAL;
  1908. }
  1909. log_info(LD_CIRC,"Sending extend relay cell.");
  1910. note_request("cell: extend", 1);
  1911. /* send it to hop->prev, because it will transfer
  1912. * it to a create cell and then send to hop */
  1913. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  1914. RELAY_COMMAND_EXTEND,
  1915. payload, payload_len, hop->prev) < 0)
  1916. return 0; /* circuit is closed */
  1917. hop->state = CPATH_STATE_AWAITING_KEYS;
  1918. }
  1919. return 0;
  1920. }
  1921. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  1922. * something has also gone wrong with our network: notify the user,
  1923. * and abandon all not-yet-used circuits. */
  1924. void
  1925. circuit_note_clock_jumped(int seconds_elapsed)
  1926. {
  1927. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  1928. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  1929. "assuming established circuits no longer work.",
  1930. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  1931. seconds_elapsed >=0 ? "forward" : "backward");
  1932. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  1933. seconds_elapsed);
  1934. can_complete_circuit=0; /* so it'll log when it works again */
  1935. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  1936. "CLOCK_JUMPED");
  1937. circuit_mark_all_unused_circs();
  1938. circuit_expire_all_dirty_circs();
  1939. }
  1940. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  1941. * skin and identity digest for the next hop. If we're already connected,
  1942. * pass the onion skin to the next hop using a create cell; otherwise
  1943. * launch a new OR connection, and <b>circ</b> will notice when the
  1944. * connection succeeds or fails.
  1945. *
  1946. * Return -1 if we want to warn and tear down the circuit, else return 0.
  1947. */
  1948. int
  1949. circuit_extend(cell_t *cell, circuit_t *circ)
  1950. {
  1951. or_connection_t *n_conn;
  1952. relay_header_t rh;
  1953. char *onionskin;
  1954. char *id_digest=NULL;
  1955. uint32_t n_addr32;
  1956. uint16_t n_port;
  1957. tor_addr_t n_addr;
  1958. const char *msg = NULL;
  1959. int should_launch = 0;
  1960. if (circ->n_conn) {
  1961. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1962. "n_conn already set. Bug/attack. Closing.");
  1963. return -1;
  1964. }
  1965. if (circ->n_hop) {
  1966. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1967. "conn to next hop already launched. Bug/attack. Closing.");
  1968. return -1;
  1969. }
  1970. if (!server_mode(get_options())) {
  1971. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1972. "Got an extend cell, but running as a client. Closing.");
  1973. return -1;
  1974. }
  1975. relay_header_unpack(&rh, cell->payload);
  1976. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  1977. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1978. "Wrong length %d on extend cell. Closing circuit.",
  1979. rh.length);
  1980. return -1;
  1981. }
  1982. n_addr32 = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  1983. n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  1984. onionskin = (char*) cell->payload+RELAY_HEADER_SIZE+4+2;
  1985. id_digest = (char*) cell->payload+RELAY_HEADER_SIZE+4+2+
  1986. ONIONSKIN_CHALLENGE_LEN;
  1987. tor_addr_from_ipv4h(&n_addr, n_addr32);
  1988. if (!n_port || !n_addr32) {
  1989. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1990. "Client asked me to extend to zero destination port or addr.");
  1991. return -1;
  1992. }
  1993. /* Check if they asked us for 0000..0000. We support using
  1994. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  1995. * but we don't want to let people send us extend cells for empty
  1996. * fingerprints -- a) because it opens the user up to a mitm attack,
  1997. * and b) because it lets an attacker force the relay to hold open a
  1998. * new TLS connection for each extend request. */
  1999. if (tor_digest_is_zero(id_digest)) {
  2000. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2001. "Client asked me to extend without specifying an id_digest.");
  2002. return -1;
  2003. }
  2004. /* Next, check if we're being asked to connect to the hop that the
  2005. * extend cell came from. There isn't any reason for that, and it can
  2006. * assist circular-path attacks. */
  2007. if (!memcmp(id_digest, TO_OR_CIRCUIT(circ)->p_conn->identity_digest,
  2008. DIGEST_LEN)) {
  2009. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2010. "Client asked me to extend back to the previous hop.");
  2011. return -1;
  2012. }
  2013. n_conn = connection_or_get_for_extend(id_digest,
  2014. &n_addr,
  2015. &msg,
  2016. &should_launch);
  2017. if (!n_conn) {
  2018. log_debug(LD_CIRC|LD_OR,"Next router (%s:%d): %s",
  2019. fmt_addr(&n_addr), (int)n_port, msg?msg:"????");
  2020. circ->n_hop = extend_info_alloc(NULL /*nickname*/,
  2021. id_digest,
  2022. NULL /*onion_key*/,
  2023. &n_addr, n_port);
  2024. circ->n_conn_onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
  2025. memcpy(circ->n_conn_onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  2026. circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
  2027. if (should_launch) {
  2028. /* we should try to open a connection */
  2029. n_conn = connection_or_connect(&n_addr, n_port, id_digest);
  2030. if (!n_conn) {
  2031. log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
  2032. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  2033. return 0;
  2034. }
  2035. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  2036. }
  2037. /* return success. The onion/circuit/etc will be taken care of
  2038. * automatically (may already have been) whenever n_conn reaches
  2039. * OR_CONN_STATE_OPEN.
  2040. */
  2041. return 0;
  2042. }
  2043. tor_assert(!circ->n_hop); /* Connection is already established. */
  2044. circ->n_conn = n_conn;
  2045. log_debug(LD_CIRC,"n_conn is %s:%u",
  2046. n_conn->_base.address,n_conn->_base.port);
  2047. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  2048. return -1;
  2049. return 0;
  2050. }
  2051. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  2052. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  2053. * used as follows:
  2054. * - 20 to initialize f_digest
  2055. * - 20 to initialize b_digest
  2056. * - 16 to key f_crypto
  2057. * - 16 to key b_crypto
  2058. *
  2059. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  2060. */
  2061. int
  2062. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  2063. int reverse)
  2064. {
  2065. crypto_digest_env_t *tmp_digest;
  2066. crypto_cipher_env_t *tmp_crypto;
  2067. tor_assert(cpath);
  2068. tor_assert(key_data);
  2069. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  2070. cpath->f_digest || cpath->b_digest));
  2071. cpath->f_digest = crypto_new_digest_env();
  2072. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  2073. cpath->b_digest = crypto_new_digest_env();
  2074. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  2075. if (!(cpath->f_crypto =
  2076. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  2077. log_warn(LD_BUG,"Forward cipher initialization failed.");
  2078. return -1;
  2079. }
  2080. if (!(cpath->b_crypto =
  2081. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  2082. log_warn(LD_BUG,"Backward cipher initialization failed.");
  2083. return -1;
  2084. }
  2085. if (reverse) {
  2086. tmp_digest = cpath->f_digest;
  2087. cpath->f_digest = cpath->b_digest;
  2088. cpath->b_digest = tmp_digest;
  2089. tmp_crypto = cpath->f_crypto;
  2090. cpath->f_crypto = cpath->b_crypto;
  2091. cpath->b_crypto = tmp_crypto;
  2092. }
  2093. return 0;
  2094. }
  2095. /** A created or extended cell came back to us on the circuit, and it included
  2096. * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  2097. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  2098. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  2099. *
  2100. * Calculate the appropriate keys and digests, make sure KH is
  2101. * correct, and initialize this hop of the cpath.
  2102. *
  2103. * Return - reason if we want to mark circ for close, else return 0.
  2104. */
  2105. int
  2106. circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
  2107. const uint8_t *reply)
  2108. {
  2109. char keys[CPATH_KEY_MATERIAL_LEN];
  2110. crypt_path_t *hop;
  2111. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  2112. hop = circ->cpath;
  2113. else {
  2114. hop = onion_next_hop_in_cpath(circ->cpath);
  2115. if (!hop) { /* got an extended when we're all done? */
  2116. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  2117. return - END_CIRC_REASON_TORPROTOCOL;
  2118. }
  2119. }
  2120. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  2121. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  2122. if (onion_skin_client_handshake(hop->dh_handshake_state, (char*)reply,keys,
  2123. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  2124. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  2125. return -END_CIRC_REASON_TORPROTOCOL;
  2126. }
  2127. /* Remember hash of g^xy */
  2128. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  2129. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  2130. if (fast_client_handshake(hop->fast_handshake_state, reply,
  2131. (uint8_t*)keys,
  2132. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  2133. log_warn(LD_CIRC,"fast_client_handshake failed.");
  2134. return -END_CIRC_REASON_TORPROTOCOL;
  2135. }
  2136. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  2137. } else {
  2138. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  2139. return -END_CIRC_REASON_TORPROTOCOL;
  2140. }
  2141. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  2142. hop->dh_handshake_state = NULL;
  2143. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  2144. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  2145. return -END_CIRC_REASON_TORPROTOCOL;
  2146. }
  2147. hop->state = CPATH_STATE_OPEN;
  2148. log_info(LD_CIRC,"Finished building %scircuit hop:",
  2149. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  2150. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  2151. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  2152. return 0;
  2153. }
  2154. /** We received a relay truncated cell on circ.
  2155. *
  2156. * Since we don't ask for truncates currently, getting a truncated
  2157. * means that a connection broke or an extend failed. For now,
  2158. * just give up: for circ to close, and return 0.
  2159. */
  2160. int
  2161. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
  2162. {
  2163. // crypt_path_t *victim;
  2164. // connection_t *stream;
  2165. tor_assert(circ);
  2166. tor_assert(layer);
  2167. /* XXX Since we don't ask for truncates currently, getting a truncated
  2168. * means that a connection broke or an extend failed. For now,
  2169. * just give up.
  2170. */
  2171. circuit_mark_for_close(TO_CIRCUIT(circ),
  2172. END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
  2173. return 0;
  2174. #if 0
  2175. while (layer->next != circ->cpath) {
  2176. /* we need to clear out layer->next */
  2177. victim = layer->next;
  2178. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  2179. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  2180. if (stream->cpath_layer == victim) {
  2181. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  2182. stream->stream_id);
  2183. /* no need to send 'end' relay cells,
  2184. * because the other side's already dead
  2185. */
  2186. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  2187. }
  2188. }
  2189. layer->next = victim->next;
  2190. circuit_free_cpath_node(victim);
  2191. }
  2192. log_info(LD_CIRC, "finished");
  2193. return 0;
  2194. #endif
  2195. }
  2196. /** Given a response payload and keys, initialize, then send a created
  2197. * cell back.
  2198. */
  2199. int
  2200. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
  2201. const char *keys)
  2202. {
  2203. cell_t cell;
  2204. crypt_path_t *tmp_cpath;
  2205. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  2206. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  2207. memset(&cell, 0, sizeof(cell_t));
  2208. cell.command = cell_type;
  2209. cell.circ_id = circ->p_circ_id;
  2210. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  2211. memcpy(cell.payload, payload,
  2212. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  2213. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  2214. (unsigned int)get_uint32(keys),
  2215. (unsigned int)get_uint32(keys+20));
  2216. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  2217. log_warn(LD_BUG,"Circuit initialization failed");
  2218. tor_free(tmp_cpath);
  2219. return -1;
  2220. }
  2221. circ->n_digest = tmp_cpath->f_digest;
  2222. circ->n_crypto = tmp_cpath->f_crypto;
  2223. circ->p_digest = tmp_cpath->b_digest;
  2224. circ->p_crypto = tmp_cpath->b_crypto;
  2225. tmp_cpath->magic = 0;
  2226. tor_free(tmp_cpath);
  2227. if (cell_type == CELL_CREATED)
  2228. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  2229. else
  2230. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  2231. circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
  2232. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  2233. circ->p_conn, &cell, CELL_DIRECTION_IN, 0);
  2234. log_debug(LD_CIRC,"Finished sending 'created' cell.");
  2235. if (!is_local_addr(&circ->p_conn->_base.addr) &&
  2236. !connection_or_nonopen_was_started_here(circ->p_conn)) {
  2237. /* record that we could process create cells from a non-local conn
  2238. * that we didn't initiate; presumably this means that create cells
  2239. * can reach us too. */
  2240. router_orport_found_reachable();
  2241. }
  2242. return 0;
  2243. }
  2244. /** Choose a length for a circuit of purpose <b>purpose</b>.
  2245. * Default length is 3 + the number of endpoints that would give something
  2246. * away. If the routerlist <b>routers</b> doesn't have enough routers
  2247. * to handle the desired path length, return as large a path length as
  2248. * is feasible, except if it's less than 2, in which case return -1.
  2249. */
  2250. static int
  2251. new_route_len(uint8_t purpose, extend_info_t *exit,
  2252. smartlist_t *routers)
  2253. {
  2254. int num_acceptable_routers;
  2255. int routelen;
  2256. tor_assert(routers);
  2257. routelen = DEFAULT_ROUTE_LEN;
  2258. if (exit &&
  2259. purpose != CIRCUIT_PURPOSE_TESTING &&
  2260. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  2261. routelen++;
  2262. num_acceptable_routers = count_acceptable_routers(routers);
  2263. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  2264. routelen, num_acceptable_routers, smartlist_len(routers));
  2265. if (num_acceptable_routers < 2) {
  2266. log_info(LD_CIRC,
  2267. "Not enough acceptable routers (%d). Discarding this circuit.",
  2268. num_acceptable_routers);
  2269. return -1;
  2270. }
  2271. if (num_acceptable_routers < routelen) {
  2272. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  2273. routelen, num_acceptable_routers);
  2274. routelen = num_acceptable_routers;
  2275. }
  2276. return routelen;
  2277. }
  2278. /** Fetch the list of predicted ports, dup it into a smartlist of
  2279. * uint16_t's, remove the ones that are already handled by an
  2280. * existing circuit, and return it.
  2281. */
  2282. static smartlist_t *
  2283. circuit_get_unhandled_ports(time_t now)
  2284. {
  2285. smartlist_t *source = rep_hist_get_predicted_ports(now);
  2286. smartlist_t *dest = smartlist_create();
  2287. uint16_t *tmp;
  2288. int i;
  2289. for (i = 0; i < smartlist_len(source); ++i) {
  2290. tmp = tor_malloc(sizeof(uint16_t));
  2291. memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
  2292. smartlist_add(dest, tmp);
  2293. }
  2294. circuit_remove_handled_ports(dest);
  2295. return dest;
  2296. }
  2297. /** Return 1 if we already have circuits present or on the way for
  2298. * all anticipated ports. Return 0 if we should make more.
  2299. *
  2300. * If we're returning 0, set need_uptime and need_capacity to
  2301. * indicate any requirements that the unhandled ports have.
  2302. */
  2303. int
  2304. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  2305. int *need_capacity)
  2306. {
  2307. int i, enough;
  2308. uint16_t *port;
  2309. smartlist_t *sl = circuit_get_unhandled_ports(now);
  2310. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  2311. tor_assert(need_uptime);
  2312. tor_assert(need_capacity);
  2313. // Always predict need_capacity
  2314. *need_capacity = 1;
  2315. enough = (smartlist_len(sl) == 0);
  2316. for (i = 0; i < smartlist_len(sl); ++i) {
  2317. port = smartlist_get(sl, i);
  2318. if (smartlist_string_num_isin(LongLivedServices, *port))
  2319. *need_uptime = 1;
  2320. tor_free(port);
  2321. }
  2322. smartlist_free(sl);
  2323. return enough;
  2324. }
  2325. /** Return 1 if <b>router</b> can handle one or more of the ports in
  2326. * <b>needed_ports</b>, else return 0.
  2327. */
  2328. static int
  2329. router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
  2330. {
  2331. int i;
  2332. uint16_t port;
  2333. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  2334. addr_policy_result_t r;
  2335. /* alignment issues aren't a worry for this dereference, since
  2336. needed_ports is explicitly a smartlist of uint16_t's */
  2337. port = *(uint16_t *)smartlist_get(needed_ports, i);
  2338. tor_assert(port);
  2339. r = compare_addr_to_addr_policy(0, port, router->exit_policy);
  2340. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2341. return 1;
  2342. }
  2343. return 0;
  2344. }
  2345. /** Return true iff <b>conn</b> needs another general circuit to be
  2346. * built. */
  2347. static int
  2348. ap_stream_wants_exit_attention(connection_t *conn)
  2349. {
  2350. if (conn->type == CONN_TYPE_AP &&
  2351. conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  2352. !conn->marked_for_close &&
  2353. !(TO_EDGE_CONN(conn)->want_onehop) && /* ignore one-hop streams */
  2354. !(TO_EDGE_CONN(conn)->use_begindir) && /* ignore targeted dir fetches */
  2355. !(TO_EDGE_CONN(conn)->chosen_exit_name) && /* ignore defined streams */
  2356. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  2357. !circuit_stream_is_being_handled(TO_EDGE_CONN(conn), 0,
  2358. MIN_CIRCUITS_HANDLING_STREAM))
  2359. return 1;
  2360. return 0;
  2361. }
  2362. /** Return a pointer to a suitable router to be the exit node for the
  2363. * general-purpose circuit we're about to build.
  2364. *
  2365. * Look through the connection array, and choose a router that maximizes
  2366. * the number of pending streams that can exit from this router.
  2367. *
  2368. * Return NULL if we can't find any suitable routers.
  2369. */
  2370. static routerinfo_t *
  2371. choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
  2372. int need_capacity)
  2373. {
  2374. int *n_supported;
  2375. int i;
  2376. int n_pending_connections = 0;
  2377. smartlist_t *connections;
  2378. int best_support = -1;
  2379. int n_best_support=0;
  2380. routerinfo_t *router;
  2381. or_options_t *options = get_options();
  2382. connections = get_connection_array();
  2383. /* Count how many connections are waiting for a circuit to be built.
  2384. * We use this for log messages now, but in the future we may depend on it.
  2385. */
  2386. SMARTLIST_FOREACH(connections, connection_t *, conn,
  2387. {
  2388. if (ap_stream_wants_exit_attention(conn))
  2389. ++n_pending_connections;
  2390. });
  2391. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  2392. // n_pending_connections);
  2393. /* Now we count, for each of the routers in the directory, how many
  2394. * of the pending connections could possibly exit from that
  2395. * router (n_supported[i]). (We can't be sure about cases where we
  2396. * don't know the IP address of the pending connection.)
  2397. *
  2398. * -1 means "Don't use this router at all."
  2399. */
  2400. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  2401. for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
  2402. router = smartlist_get(dir->routers, i);
  2403. if (router_is_me(router)) {
  2404. n_supported[i] = -1;
  2405. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  2406. /* XXX there's probably a reverse predecessor attack here, but
  2407. * it's slow. should we take this out? -RD
  2408. */
  2409. continue;
  2410. }
  2411. if (!router->is_running || router->is_bad_exit) {
  2412. n_supported[i] = -1;
  2413. continue; /* skip routers that are known to be down or bad exits */
  2414. }
  2415. if (options->_ExcludeExitNodesUnion &&
  2416. routerset_contains_router(options->_ExcludeExitNodesUnion, router)) {
  2417. n_supported[i] = -1;
  2418. continue; /* user asked us not to use it, no matter what */
  2419. }
  2420. if (options->ExitNodes &&
  2421. !routerset_contains_router(options->ExitNodes, router)) {
  2422. n_supported[i] = -1;
  2423. continue; /* not one of our chosen exit nodes */
  2424. }
  2425. if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
  2426. n_supported[i] = -1;
  2427. continue; /* skip routers that are not suitable. Don't worry if
  2428. * this makes us reject all the possible routers: if so,
  2429. * we'll retry later in this function with need_update and
  2430. * need_capacity set to 0. */
  2431. }
  2432. if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
  2433. /* if it's invalid and we don't want it */
  2434. n_supported[i] = -1;
  2435. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  2436. // router->nickname, i);
  2437. continue; /* skip invalid routers */
  2438. }
  2439. if (options->ExcludeSingleHopRelays && router->allow_single_hop_exits) {
  2440. n_supported[i] = -1;
  2441. continue;
  2442. }
  2443. if (router_exit_policy_rejects_all(router)) {
  2444. n_supported[i] = -1;
  2445. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  2446. // router->nickname, i);
  2447. continue; /* skip routers that reject all */
  2448. }
  2449. n_supported[i] = 0;
  2450. /* iterate over connections */
  2451. SMARTLIST_FOREACH(connections, connection_t *, conn,
  2452. {
  2453. if (!ap_stream_wants_exit_attention(conn))
  2454. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  2455. if (connection_ap_can_use_exit(TO_EDGE_CONN(conn), router)) {
  2456. ++n_supported[i];
  2457. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  2458. // router->nickname, i, n_supported[i]);
  2459. } else {
  2460. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  2461. // router->nickname, i);
  2462. }
  2463. }); /* End looping over connections. */
  2464. if (n_pending_connections > 0 && n_supported[i] == 0) {
  2465. /* Leave best_support at -1 if that's where it is, so we can
  2466. * distinguish it later. */
  2467. continue;
  2468. }
  2469. if (n_supported[i] > best_support) {
  2470. /* If this router is better than previous ones, remember its index
  2471. * and goodness, and start counting how many routers are this good. */
  2472. best_support = n_supported[i]; n_best_support=1;
  2473. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  2474. // router->nickname);
  2475. } else if (n_supported[i] == best_support) {
  2476. /* If this router is _as good_ as the best one, just increment the
  2477. * count of equally good routers.*/
  2478. ++n_best_support;
  2479. }
  2480. }
  2481. log_info(LD_CIRC,
  2482. "Found %d servers that might support %d/%d pending connections.",
  2483. n_best_support, best_support >= 0 ? best_support : 0,
  2484. n_pending_connections);
  2485. /* If any routers definitely support any pending connections, choose one
  2486. * at random. */
  2487. if (best_support > 0) {
  2488. smartlist_t *supporting = smartlist_create();
  2489. for (i = 0; i < smartlist_len(dir->routers); i++)
  2490. if (n_supported[i] == best_support)
  2491. smartlist_add(supporting, smartlist_get(dir->routers, i));
  2492. router = routerlist_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2493. smartlist_free(supporting);
  2494. } else {
  2495. /* Either there are no pending connections, or no routers even seem to
  2496. * possibly support any of them. Choose a router at random that satisfies
  2497. * at least one predicted exit port. */
  2498. int attempt;
  2499. smartlist_t *needed_ports, *supporting;
  2500. if (best_support == -1) {
  2501. if (need_uptime || need_capacity) {
  2502. log_info(LD_CIRC,
  2503. "We couldn't find any live%s%s routers; falling back "
  2504. "to list of all routers.",
  2505. need_capacity?", fast":"",
  2506. need_uptime?", stable":"");
  2507. tor_free(n_supported);
  2508. return choose_good_exit_server_general(dir, 0, 0);
  2509. }
  2510. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  2511. "choosing a doomed exit at random.",
  2512. options->_ExcludeExitNodesUnion ? " or are Excluded" : "");
  2513. }
  2514. supporting = smartlist_create();
  2515. needed_ports = circuit_get_unhandled_ports(time(NULL));
  2516. for (attempt = 0; attempt < 2; attempt++) {
  2517. /* try once to pick only from routers that satisfy a needed port,
  2518. * then if there are none, pick from any that support exiting. */
  2519. for (i = 0; i < smartlist_len(dir->routers); i++) {
  2520. router = smartlist_get(dir->routers, i);
  2521. if (n_supported[i] != -1 &&
  2522. (attempt || router_handles_some_port(router, needed_ports))) {
  2523. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  2524. // try, router->nickname);
  2525. smartlist_add(supporting, router);
  2526. }
  2527. }
  2528. router = routerlist_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2529. if (router)
  2530. break;
  2531. smartlist_clear(supporting);
  2532. }
  2533. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  2534. smartlist_free(needed_ports);
  2535. smartlist_free(supporting);
  2536. }
  2537. tor_free(n_supported);
  2538. if (router) {
  2539. log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
  2540. return router;
  2541. }
  2542. if (options->ExitNodes) {
  2543. log_warn(LD_CIRC,
  2544. "No specified %sexit routers seem to be running: "
  2545. "can't choose an exit.",
  2546. options->_ExcludeExitNodesUnion ? "non-excluded " : "");
  2547. }
  2548. return NULL;
  2549. }
  2550. /** Return a pointer to a suitable router to be the exit node for the
  2551. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  2552. * if no router is suitable).
  2553. *
  2554. * For general-purpose circuits, pass it off to
  2555. * choose_good_exit_server_general()
  2556. *
  2557. * For client-side rendezvous circuits, choose a random node, weighted
  2558. * toward the preferences in 'options'.
  2559. */
  2560. static routerinfo_t *
  2561. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  2562. int need_uptime, int need_capacity, int is_internal)
  2563. {
  2564. or_options_t *options = get_options();
  2565. router_crn_flags_t flags = 0;
  2566. if (need_uptime)
  2567. flags |= CRN_NEED_UPTIME;
  2568. if (need_capacity)
  2569. flags |= CRN_NEED_CAPACITY;
  2570. switch (purpose) {
  2571. case CIRCUIT_PURPOSE_C_GENERAL:
  2572. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  2573. flags |= CRN_ALLOW_INVALID;
  2574. if (is_internal) /* pick it like a middle hop */
  2575. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2576. else
  2577. return choose_good_exit_server_general(dir,need_uptime,need_capacity);
  2578. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2579. if (options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS)
  2580. flags |= CRN_ALLOW_INVALID;
  2581. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2582. }
  2583. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  2584. tor_fragile_assert();
  2585. return NULL;
  2586. }
  2587. /** Log a warning if the user specified an exit for the circuit that
  2588. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  2589. static void
  2590. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  2591. {
  2592. or_options_t *options = get_options();
  2593. routerset_t *rs = options->ExcludeNodes;
  2594. const char *description;
  2595. uint8_t purpose = circ->_base.purpose;
  2596. if (circ->build_state->onehop_tunnel)
  2597. return;
  2598. switch (purpose)
  2599. {
  2600. default:
  2601. case CIRCUIT_PURPOSE_OR:
  2602. case CIRCUIT_PURPOSE_INTRO_POINT:
  2603. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  2604. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  2605. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  2606. (int)purpose,
  2607. circuit_purpose_to_string(purpose));
  2608. return;
  2609. case CIRCUIT_PURPOSE_C_GENERAL:
  2610. if (circ->build_state->is_internal)
  2611. return;
  2612. description = "requested exit node";
  2613. rs = options->_ExcludeExitNodesUnion;
  2614. break;
  2615. case CIRCUIT_PURPOSE_C_INTRODUCING:
  2616. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  2617. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  2618. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2619. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2620. case CIRCUIT_PURPOSE_S_REND_JOINED:
  2621. case CIRCUIT_PURPOSE_TESTING:
  2622. return;
  2623. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2624. case CIRCUIT_PURPOSE_C_REND_READY:
  2625. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  2626. case CIRCUIT_PURPOSE_C_REND_JOINED:
  2627. description = "chosen rendezvous point";
  2628. break;
  2629. case CIRCUIT_PURPOSE_CONTROLLER:
  2630. rs = options->_ExcludeExitNodesUnion;
  2631. description = "controller-selected circuit target";
  2632. break;
  2633. }
  2634. if (routerset_contains_extendinfo(rs, exit)) {
  2635. /* We should never get here if StrictNodes is set to 1. */
  2636. if (options->StrictNodes) {
  2637. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  2638. "even though StrictNodes is set. Please report. "
  2639. "(Circuit purpose: %s)",
  2640. description, exit->nickname,
  2641. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2642. circuit_purpose_to_string(purpose));
  2643. } else {
  2644. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  2645. "ExcludeNodes%s, because no better options were available. To "
  2646. "prevent this (and possibly break your Tor functionality), "
  2647. "set the StrictNodes configuration option. "
  2648. "(Circuit purpose: %s)",
  2649. description, exit->nickname,
  2650. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2651. circuit_purpose_to_string(purpose));
  2652. }
  2653. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  2654. }
  2655. return;
  2656. }
  2657. /** Decide a suitable length for circ's cpath, and pick an exit
  2658. * router (or use <b>exit</b> if provided). Store these in the
  2659. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  2660. static int
  2661. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  2662. {
  2663. cpath_build_state_t *state = circ->build_state;
  2664. routerlist_t *rl = router_get_routerlist();
  2665. if (state->onehop_tunnel) {
  2666. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  2667. state->desired_path_len = 1;
  2668. } else {
  2669. int r = new_route_len(circ->_base.purpose, exit, rl->routers);
  2670. if (r < 1) /* must be at least 1 */
  2671. return -1;
  2672. state->desired_path_len = r;
  2673. }
  2674. if (exit) { /* the circuit-builder pre-requested one */
  2675. warn_if_last_router_excluded(circ, exit);
  2676. log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
  2677. exit = extend_info_dup(exit);
  2678. } else { /* we have to decide one */
  2679. routerinfo_t *router =
  2680. choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
  2681. state->need_capacity, state->is_internal);
  2682. if (!router) {
  2683. log_warn(LD_CIRC,"failed to choose an exit server");
  2684. return -1;
  2685. }
  2686. exit = extend_info_from_router(router);
  2687. }
  2688. state->chosen_exit = exit;
  2689. return 0;
  2690. }
  2691. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  2692. * hop to the cpath reflecting this. Don't send the next extend cell --
  2693. * the caller will do this if it wants to.
  2694. */
  2695. int
  2696. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2697. {
  2698. cpath_build_state_t *state;
  2699. tor_assert(exit);
  2700. tor_assert(circ);
  2701. state = circ->build_state;
  2702. tor_assert(state);
  2703. extend_info_free(state->chosen_exit);
  2704. state->chosen_exit = extend_info_dup(exit);
  2705. ++circ->build_state->desired_path_len;
  2706. onion_append_hop(&circ->cpath, exit);
  2707. return 0;
  2708. }
  2709. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  2710. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  2711. * send the next extend cell to begin connecting to that hop.
  2712. */
  2713. int
  2714. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  2715. {
  2716. int err_reason = 0;
  2717. warn_if_last_router_excluded(circ, exit);
  2718. circuit_append_new_exit(circ, exit);
  2719. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2720. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  2721. log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
  2722. exit->nickname);
  2723. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2724. return -1;
  2725. }
  2726. return 0;
  2727. }
  2728. /** Return the number of routers in <b>routers</b> that are currently up
  2729. * and available for building circuits through.
  2730. */
  2731. static int
  2732. count_acceptable_routers(smartlist_t *routers)
  2733. {
  2734. int i, n;
  2735. int num=0;
  2736. routerinfo_t *r;
  2737. n = smartlist_len(routers);
  2738. for (i=0;i<n;i++) {
  2739. r = smartlist_get(routers, i);
  2740. // log_debug(LD_CIRC,
  2741. // "Contemplating whether router %d (%s) is a new option.",
  2742. // i, r->nickname);
  2743. if (r->is_running == 0) {
  2744. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  2745. goto next_i_loop;
  2746. }
  2747. if (r->is_valid == 0) {
  2748. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  2749. goto next_i_loop;
  2750. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  2751. * allows this node in some places, then we're getting an inaccurate
  2752. * count. For now, be conservative and don't count it. But later we
  2753. * should try to be smarter. */
  2754. }
  2755. num++;
  2756. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  2757. next_i_loop:
  2758. ; /* C requires an explicit statement after the label */
  2759. }
  2760. return num;
  2761. }
  2762. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  2763. * This function is used to extend cpath by another hop.
  2764. */
  2765. void
  2766. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  2767. {
  2768. if (*head_ptr) {
  2769. new_hop->next = (*head_ptr);
  2770. new_hop->prev = (*head_ptr)->prev;
  2771. (*head_ptr)->prev->next = new_hop;
  2772. (*head_ptr)->prev = new_hop;
  2773. } else {
  2774. *head_ptr = new_hop;
  2775. new_hop->prev = new_hop->next = new_hop;
  2776. }
  2777. }
  2778. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  2779. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  2780. * to length <b>cur_len</b> to decide a suitable middle hop for a
  2781. * circuit. In particular, make sure we don't pick the exit node or its
  2782. * family, and make sure we don't duplicate any previous nodes or their
  2783. * families. */
  2784. static routerinfo_t *
  2785. choose_good_middle_server(uint8_t purpose,
  2786. cpath_build_state_t *state,
  2787. crypt_path_t *head,
  2788. int cur_len)
  2789. {
  2790. int i;
  2791. routerinfo_t *r, *choice;
  2792. crypt_path_t *cpath;
  2793. smartlist_t *excluded;
  2794. or_options_t *options = get_options();
  2795. router_crn_flags_t flags = 0;
  2796. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  2797. purpose <= _CIRCUIT_PURPOSE_MAX);
  2798. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  2799. excluded = smartlist_create();
  2800. if ((r = build_state_get_exit_router(state))) {
  2801. smartlist_add(excluded, r);
  2802. routerlist_add_family(excluded, r);
  2803. }
  2804. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  2805. if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
  2806. smartlist_add(excluded, r);
  2807. routerlist_add_family(excluded, r);
  2808. }
  2809. }
  2810. if (state->need_uptime)
  2811. flags |= CRN_NEED_UPTIME;
  2812. if (state->need_capacity)
  2813. flags |= CRN_NEED_CAPACITY;
  2814. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  2815. flags |= CRN_ALLOW_INVALID;
  2816. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2817. smartlist_free(excluded);
  2818. return choice;
  2819. }
  2820. /** Pick a good entry server for the circuit to be built according to
  2821. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  2822. * router (if we're an OR), and respect firewall settings; if we're
  2823. * configured to use entry guards, return one.
  2824. *
  2825. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  2826. * guard, not for any particular circuit.
  2827. */
  2828. static routerinfo_t *
  2829. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  2830. {
  2831. routerinfo_t *r, *choice;
  2832. smartlist_t *excluded;
  2833. or_options_t *options = get_options();
  2834. router_crn_flags_t flags = CRN_NEED_GUARD;
  2835. if (state && options->UseEntryGuards &&
  2836. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  2837. return choose_random_entry(state);
  2838. }
  2839. excluded = smartlist_create();
  2840. if (state && (r = build_state_get_exit_router(state))) {
  2841. smartlist_add(excluded, r);
  2842. routerlist_add_family(excluded, r);
  2843. }
  2844. if (firewall_is_fascist_or()) {
  2845. /*XXXX This could slow things down a lot; use a smarter implementation */
  2846. /* exclude all ORs that listen on the wrong port, if anybody notices. */
  2847. routerlist_t *rl = router_get_routerlist();
  2848. int i;
  2849. for (i=0; i < smartlist_len(rl->routers); i++) {
  2850. r = smartlist_get(rl->routers, i);
  2851. if (!fascist_firewall_allows_or(r))
  2852. smartlist_add(excluded, r);
  2853. }
  2854. }
  2855. /* and exclude current entry guards, if applicable */
  2856. if (options->UseEntryGuards && entry_guards) {
  2857. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2858. {
  2859. if ((r = router_get_by_digest(entry->identity))) {
  2860. smartlist_add(excluded, r);
  2861. routerlist_add_family(excluded, r);
  2862. }
  2863. });
  2864. }
  2865. if (state) {
  2866. if (state->need_uptime)
  2867. flags |= CRN_NEED_UPTIME;
  2868. if (state->need_capacity)
  2869. flags |= CRN_NEED_CAPACITY;
  2870. }
  2871. if (options->_AllowInvalid & ALLOW_INVALID_ENTRY)
  2872. flags |= CRN_ALLOW_INVALID;
  2873. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  2874. smartlist_free(excluded);
  2875. return choice;
  2876. }
  2877. /** Return the first non-open hop in cpath, or return NULL if all
  2878. * hops are open. */
  2879. static crypt_path_t *
  2880. onion_next_hop_in_cpath(crypt_path_t *cpath)
  2881. {
  2882. crypt_path_t *hop = cpath;
  2883. do {
  2884. if (hop->state != CPATH_STATE_OPEN)
  2885. return hop;
  2886. hop = hop->next;
  2887. } while (hop != cpath);
  2888. return NULL;
  2889. }
  2890. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  2891. * based on <b>state</b>. Append the hop info to head_ptr.
  2892. */
  2893. static int
  2894. onion_extend_cpath(origin_circuit_t *circ)
  2895. {
  2896. uint8_t purpose = circ->_base.purpose;
  2897. cpath_build_state_t *state = circ->build_state;
  2898. int cur_len = circuit_get_cpath_len(circ);
  2899. extend_info_t *info = NULL;
  2900. if (cur_len >= state->desired_path_len) {
  2901. log_debug(LD_CIRC, "Path is complete: %d steps long",
  2902. state->desired_path_len);
  2903. return 1;
  2904. }
  2905. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  2906. state->desired_path_len);
  2907. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  2908. info = extend_info_dup(state->chosen_exit);
  2909. } else if (cur_len == 0) { /* picking first node */
  2910. routerinfo_t *r = choose_good_entry_server(purpose, state);
  2911. if (r)
  2912. info = extend_info_from_router(r);
  2913. } else {
  2914. routerinfo_t *r =
  2915. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  2916. if (r)
  2917. info = extend_info_from_router(r);
  2918. }
  2919. if (!info) {
  2920. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  2921. "this circuit.", cur_len);
  2922. return -1;
  2923. }
  2924. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  2925. info->nickname, cur_len+1, build_state_get_exit_nickname(state));
  2926. onion_append_hop(&circ->cpath, info);
  2927. extend_info_free(info);
  2928. return 0;
  2929. }
  2930. /** Create a new hop, annotate it with information about its
  2931. * corresponding router <b>choice</b>, and append it to the
  2932. * end of the cpath <b>head_ptr</b>. */
  2933. static int
  2934. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  2935. {
  2936. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  2937. /* link hop into the cpath, at the end. */
  2938. onion_append_to_cpath(head_ptr, hop);
  2939. hop->magic = CRYPT_PATH_MAGIC;
  2940. hop->state = CPATH_STATE_CLOSED;
  2941. hop->extend_info = extend_info_dup(choice);
  2942. hop->package_window = circuit_initial_package_window();
  2943. hop->deliver_window = CIRCWINDOW_START;
  2944. return 0;
  2945. }
  2946. /** Allocate a new extend_info object based on the various arguments. */
  2947. extend_info_t *
  2948. extend_info_alloc(const char *nickname, const char *digest,
  2949. crypto_pk_env_t *onion_key,
  2950. const tor_addr_t *addr, uint16_t port)
  2951. {
  2952. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  2953. memcpy(info->identity_digest, digest, DIGEST_LEN);
  2954. if (nickname)
  2955. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  2956. if (onion_key)
  2957. info->onion_key = crypto_pk_dup_key(onion_key);
  2958. tor_addr_copy(&info->addr, addr);
  2959. info->port = port;
  2960. return info;
  2961. }
  2962. /** Allocate and return a new extend_info_t that can be used to build a
  2963. * circuit to or through the router <b>r</b>. */
  2964. extend_info_t *
  2965. extend_info_from_router(routerinfo_t *r)
  2966. {
  2967. tor_addr_t addr;
  2968. tor_assert(r);
  2969. tor_addr_from_ipv4h(&addr, r->addr);
  2970. return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
  2971. r->onion_pkey, &addr, r->or_port);
  2972. }
  2973. /** Release storage held by an extend_info_t struct. */
  2974. void
  2975. extend_info_free(extend_info_t *info)
  2976. {
  2977. if (!info)
  2978. return;
  2979. crypto_free_pk_env(info->onion_key);
  2980. tor_free(info);
  2981. }
  2982. /** Allocate and return a new extend_info_t with the same contents as
  2983. * <b>info</b>. */
  2984. extend_info_t *
  2985. extend_info_dup(extend_info_t *info)
  2986. {
  2987. extend_info_t *newinfo;
  2988. tor_assert(info);
  2989. newinfo = tor_malloc(sizeof(extend_info_t));
  2990. memcpy(newinfo, info, sizeof(extend_info_t));
  2991. if (info->onion_key)
  2992. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  2993. else
  2994. newinfo->onion_key = NULL;
  2995. return newinfo;
  2996. }
  2997. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  2998. * If there is no chosen exit, or if we don't know the routerinfo_t for
  2999. * the chosen exit, return NULL.
  3000. */
  3001. routerinfo_t *
  3002. build_state_get_exit_router(cpath_build_state_t *state)
  3003. {
  3004. if (!state || !state->chosen_exit)
  3005. return NULL;
  3006. return router_get_by_digest(state->chosen_exit->identity_digest);
  3007. }
  3008. /** Return the nickname for the chosen exit router in <b>state</b>. If
  3009. * there is no chosen exit, or if we don't know the routerinfo_t for the
  3010. * chosen exit, return NULL.
  3011. */
  3012. const char *
  3013. build_state_get_exit_nickname(cpath_build_state_t *state)
  3014. {
  3015. if (!state || !state->chosen_exit)
  3016. return NULL;
  3017. return state->chosen_exit->nickname;
  3018. }
  3019. /** Check whether the entry guard <b>e</b> is usable, given the directory
  3020. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  3021. * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
  3022. * accordingly. Return true iff the entry guard's status changes.
  3023. *
  3024. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  3025. */
  3026. /*XXXX take a routerstatus, not a routerinfo. */
  3027. static int
  3028. entry_guard_set_status(entry_guard_t *e, routerinfo_t *ri,
  3029. time_t now, or_options_t *options, const char **reason)
  3030. {
  3031. char buf[HEX_DIGEST_LEN+1];
  3032. int changed = 0;
  3033. *reason = NULL;
  3034. /* Do we want to mark this guard as bad? */
  3035. if (!ri)
  3036. *reason = "unlisted";
  3037. else if (!ri->is_running)
  3038. *reason = "down";
  3039. else if (options->UseBridges && ri->purpose != ROUTER_PURPOSE_BRIDGE)
  3040. *reason = "not a bridge";
  3041. else if (!options->UseBridges && !ri->is_possible_guard &&
  3042. !routerset_contains_router(options->EntryNodes,ri))
  3043. *reason = "not recommended as a guard";
  3044. else if (routerset_contains_router(options->ExcludeNodes, ri))
  3045. *reason = "excluded";
  3046. if (*reason && ! e->bad_since) {
  3047. /* Router is newly bad. */
  3048. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  3049. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  3050. e->nickname, buf, *reason);
  3051. e->bad_since = now;
  3052. control_event_guard(e->nickname, e->identity, "BAD");
  3053. changed = 1;
  3054. } else if (!*reason && e->bad_since) {
  3055. /* There's nothing wrong with the router any more. */
  3056. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  3057. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  3058. "marking as ok.", e->nickname, buf);
  3059. e->bad_since = 0;
  3060. control_event_guard(e->nickname, e->identity, "GOOD");
  3061. changed = 1;
  3062. }
  3063. return changed;
  3064. }
  3065. /** Return true iff enough time has passed since we last tried to connect
  3066. * to the unreachable guard <b>e</b> that we're willing to try again. */
  3067. static int
  3068. entry_is_time_to_retry(entry_guard_t *e, time_t now)
  3069. {
  3070. long diff;
  3071. if (e->last_attempted < e->unreachable_since)
  3072. return 1;
  3073. diff = now - e->unreachable_since;
  3074. if (diff < 6*60*60)
  3075. return now > (e->last_attempted + 60*60);
  3076. else if (diff < 3*24*60*60)
  3077. return now > (e->last_attempted + 4*60*60);
  3078. else if (diff < 7*24*60*60)
  3079. return now > (e->last_attempted + 18*60*60);
  3080. else
  3081. return now > (e->last_attempted + 36*60*60);
  3082. }
  3083. /** Return the router corresponding to <b>e</b>, if <b>e</b> is
  3084. * working well enough that we are willing to use it as an entry
  3085. * right now. (Else return NULL.) In particular, it must be
  3086. * - Listed as either up or never yet contacted;
  3087. * - Present in the routerlist;
  3088. * - Listed as 'stable' or 'fast' by the current dirserver consensus,
  3089. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
  3090. * (unless it's a configured EntryNode);
  3091. * - Allowed by our current ReachableORAddresses config option; and
  3092. * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
  3093. * is true).
  3094. *
  3095. * If the answer is no, set *<b>msg</b> to an explanation of why.
  3096. */
  3097. static INLINE routerinfo_t *
  3098. entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
  3099. int assume_reachable, const char **msg)
  3100. {
  3101. routerinfo_t *r;
  3102. or_options_t *options = get_options();
  3103. tor_assert(msg);
  3104. if (e->bad_since) {
  3105. *msg = "bad";
  3106. return NULL;
  3107. }
  3108. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  3109. if (!assume_reachable && !e->can_retry &&
  3110. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
  3111. *msg = "unreachable";
  3112. return NULL;
  3113. }
  3114. r = router_get_by_digest(e->identity);
  3115. if (!r) {
  3116. *msg = "no descriptor";
  3117. return NULL;
  3118. }
  3119. if (get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_BRIDGE) {
  3120. *msg = "not a bridge";
  3121. return NULL;
  3122. }
  3123. if (!get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_GENERAL) {
  3124. *msg = "not general-purpose";
  3125. return NULL;
  3126. }
  3127. if (options->EntryNodes &&
  3128. routerset_contains_router(options->EntryNodes, r)) {
  3129. /* they asked for it, they get it */
  3130. need_uptime = need_capacity = 0;
  3131. }
  3132. if (router_is_unreliable(r, need_uptime, need_capacity, 0)) {
  3133. *msg = "not fast/stable";
  3134. return NULL;
  3135. }
  3136. if (!fascist_firewall_allows_or(r)) {
  3137. *msg = "unreachable by config";
  3138. return NULL;
  3139. }
  3140. return r;
  3141. }
  3142. /** Return the number of entry guards that we think are usable. */
  3143. static int
  3144. num_live_entry_guards(void)
  3145. {
  3146. int n = 0;
  3147. const char *msg;
  3148. if (! entry_guards)
  3149. return 0;
  3150. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3151. {
  3152. if (entry_is_live(entry, 0, 1, 0, &msg))
  3153. ++n;
  3154. });
  3155. return n;
  3156. }
  3157. /** If <b>digest</b> matches the identity of any node in the
  3158. * entry_guards list, return that node. Else return NULL. */
  3159. static INLINE entry_guard_t *
  3160. is_an_entry_guard(const char *digest)
  3161. {
  3162. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3163. if (!memcmp(digest, entry->identity, DIGEST_LEN))
  3164. return entry;
  3165. );
  3166. return NULL;
  3167. }
  3168. /** Dump a description of our list of entry guards to the log at level
  3169. * <b>severity</b>. */
  3170. static void
  3171. log_entry_guards(int severity)
  3172. {
  3173. smartlist_t *elements = smartlist_create();
  3174. char *s;
  3175. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3176. {
  3177. const char *msg = NULL;
  3178. char *cp;
  3179. if (entry_is_live(e, 0, 1, 0, &msg))
  3180. tor_asprintf(&cp, "%s (up %s)",
  3181. e->nickname,
  3182. e->made_contact ? "made-contact" : "never-contacted");
  3183. else
  3184. tor_asprintf(&cp, "%s (%s, %s)",
  3185. e->nickname, msg,
  3186. e->made_contact ? "made-contact" : "never-contacted");
  3187. smartlist_add(elements, cp);
  3188. });
  3189. s = smartlist_join_strings(elements, ",", 0, NULL);
  3190. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  3191. smartlist_free(elements);
  3192. log_fn(severity,LD_CIRC,"%s",s);
  3193. tor_free(s);
  3194. }
  3195. /** Called when one or more guards that we would previously have used for some
  3196. * purpose are no longer in use because a higher-priority guard has become
  3197. * usable again. */
  3198. static void
  3199. control_event_guard_deferred(void)
  3200. {
  3201. /* XXXX We don't actually have a good way to figure out _how many_ entries
  3202. * are live for some purpose. We need an entry_is_even_slightly_live()
  3203. * function for this to work right. NumEntryGuards isn't reliable: if we
  3204. * need guards with weird properties, we can have more than that number
  3205. * live.
  3206. **/
  3207. #if 0
  3208. int n = 0;
  3209. const char *msg;
  3210. or_options_t *options = get_options();
  3211. if (!entry_guards)
  3212. return;
  3213. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3214. {
  3215. if (entry_is_live(entry, 0, 1, 0, &msg)) {
  3216. if (n++ == options->NumEntryGuards) {
  3217. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  3218. return;
  3219. }
  3220. }
  3221. });
  3222. #endif
  3223. }
  3224. /** Add a new (preferably stable and fast) router to our
  3225. * entry_guards list. Return a pointer to the router if we succeed,
  3226. * or NULL if we can't find any more suitable entries.
  3227. *
  3228. * If <b>chosen</b> is defined, use that one, and if it's not
  3229. * already in our entry_guards list, put it at the *beginning*.
  3230. * Else, put the one we pick at the end of the list. */
  3231. static routerinfo_t *
  3232. add_an_entry_guard(routerinfo_t *chosen, int reset_status)
  3233. {
  3234. routerinfo_t *router;
  3235. entry_guard_t *entry;
  3236. if (chosen) {
  3237. router = chosen;
  3238. entry = is_an_entry_guard(router->cache_info.identity_digest);
  3239. if (entry) {
  3240. if (reset_status) {
  3241. entry->bad_since = 0;
  3242. entry->can_retry = 1;
  3243. }
  3244. return NULL;
  3245. }
  3246. } else {
  3247. router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  3248. if (!router)
  3249. return NULL;
  3250. }
  3251. entry = tor_malloc_zero(sizeof(entry_guard_t));
  3252. log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
  3253. strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
  3254. memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
  3255. /* Choose expiry time smudged over the past month. The goal here
  3256. * is to a) spread out when Tor clients rotate their guards, so they
  3257. * don't all select them on the same day, and b) avoid leaving a
  3258. * precise timestamp in the state file about when we first picked
  3259. * this guard. For details, see the Jan 2010 or-dev thread. */
  3260. entry->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
  3261. entry->chosen_by_version = tor_strdup(VERSION);
  3262. if (chosen) /* prepend */
  3263. smartlist_insert(entry_guards, 0, entry);
  3264. else /* append */
  3265. smartlist_add(entry_guards, entry);
  3266. control_event_guard(entry->nickname, entry->identity, "NEW");
  3267. control_event_guard_deferred();
  3268. log_entry_guards(LOG_INFO);
  3269. return router;
  3270. }
  3271. /** If the use of entry guards is configured, choose more entry guards
  3272. * until we have enough in the list. */
  3273. static void
  3274. pick_entry_guards(or_options_t *options)
  3275. {
  3276. int changed = 0;
  3277. tor_assert(entry_guards);
  3278. while (num_live_entry_guards() < options->NumEntryGuards) {
  3279. if (!add_an_entry_guard(NULL, 0))
  3280. break;
  3281. changed = 1;
  3282. }
  3283. if (changed)
  3284. entry_guards_changed();
  3285. }
  3286. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  3287. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  3288. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  3289. /** Release all storage held by <b>e</b>. */
  3290. static void
  3291. entry_guard_free(entry_guard_t *e)
  3292. {
  3293. if (!e)
  3294. return;
  3295. tor_free(e->chosen_by_version);
  3296. tor_free(e);
  3297. }
  3298. /** Remove any entry guard which was selected by an unknown version of Tor,
  3299. * or which was selected by a version of Tor that's known to select
  3300. * entry guards badly. */
  3301. static int
  3302. remove_obsolete_entry_guards(time_t now)
  3303. {
  3304. int changed = 0, i;
  3305. for (i = 0; i < smartlist_len(entry_guards); ++i) {
  3306. entry_guard_t *entry = smartlist_get(entry_guards, i);
  3307. const char *ver = entry->chosen_by_version;
  3308. const char *msg = NULL;
  3309. tor_version_t v;
  3310. int version_is_bad = 0, date_is_bad = 0;
  3311. if (!ver) {
  3312. msg = "does not say what version of Tor it was selected by";
  3313. version_is_bad = 1;
  3314. } else if (tor_version_parse(ver, &v)) {
  3315. msg = "does not seem to be from any recognized version of Tor";
  3316. version_is_bad = 1;
  3317. } else {
  3318. size_t len = strlen(ver)+5;
  3319. char *tor_ver = tor_malloc(len);
  3320. tor_snprintf(tor_ver, len, "Tor %s", ver);
  3321. if ((tor_version_as_new_as(tor_ver, "0.1.0.10-alpha") &&
  3322. !tor_version_as_new_as(tor_ver, "0.1.2.16-dev")) ||
  3323. (tor_version_as_new_as(tor_ver, "0.2.0.0-alpha") &&
  3324. !tor_version_as_new_as(tor_ver, "0.2.0.6-alpha")) ||
  3325. /* above are bug 440; below are bug 1217 */
  3326. (tor_version_as_new_as(tor_ver, "0.2.1.3-alpha") &&
  3327. !tor_version_as_new_as(tor_ver, "0.2.1.23")) ||
  3328. (tor_version_as_new_as(tor_ver, "0.2.2.0-alpha") &&
  3329. !tor_version_as_new_as(tor_ver, "0.2.2.7-alpha"))) {
  3330. msg = "was selected without regard for guard bandwidth";
  3331. version_is_bad = 1;
  3332. }
  3333. tor_free(tor_ver);
  3334. }
  3335. if (!version_is_bad && entry->chosen_on_date + 3600*24*60 < now) {
  3336. /* It's been 2 months since the date listed in our state file. */
  3337. msg = "was selected several months ago";
  3338. date_is_bad = 1;
  3339. }
  3340. if (version_is_bad || date_is_bad) { /* we need to drop it */
  3341. char dbuf[HEX_DIGEST_LEN+1];
  3342. tor_assert(msg);
  3343. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  3344. log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
  3345. "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
  3346. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  3347. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3348. entry_guard_free(entry);
  3349. smartlist_del_keeporder(entry_guards, i--);
  3350. log_entry_guards(LOG_INFO);
  3351. changed = 1;
  3352. }
  3353. }
  3354. return changed ? 1 : 0;
  3355. }
  3356. /** Remove all entry guards that have been down or unlisted for so
  3357. * long that we don't think they'll come up again. Return 1 if we
  3358. * removed any, or 0 if we did nothing. */
  3359. static int
  3360. remove_dead_entry_guards(time_t now)
  3361. {
  3362. char dbuf[HEX_DIGEST_LEN+1];
  3363. char tbuf[ISO_TIME_LEN+1];
  3364. int i;
  3365. int changed = 0;
  3366. for (i = 0; i < smartlist_len(entry_guards); ) {
  3367. entry_guard_t *entry = smartlist_get(entry_guards, i);
  3368. if (entry->bad_since &&
  3369. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  3370. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  3371. format_local_iso_time(tbuf, entry->bad_since);
  3372. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  3373. "since %s local time; removing.",
  3374. entry->nickname, dbuf, tbuf);
  3375. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3376. entry_guard_free(entry);
  3377. smartlist_del_keeporder(entry_guards, i);
  3378. log_entry_guards(LOG_INFO);
  3379. changed = 1;
  3380. } else
  3381. ++i;
  3382. }
  3383. return changed ? 1 : 0;
  3384. }
  3385. /** A new directory or router-status has arrived; update the down/listed
  3386. * status of the entry guards.
  3387. *
  3388. * An entry is 'down' if the directory lists it as nonrunning.
  3389. * An entry is 'unlisted' if the directory doesn't include it.
  3390. *
  3391. * Don't call this on startup; only on a fresh download. Otherwise we'll
  3392. * think that things are unlisted.
  3393. */
  3394. void
  3395. entry_guards_compute_status(or_options_t *options, time_t now)
  3396. {
  3397. int changed = 0;
  3398. int severity = LOG_DEBUG;
  3399. digestmap_t *reasons;
  3400. if (! entry_guards)
  3401. return;
  3402. if (options->EntryNodes) /* reshuffle the entry guard list if needed */
  3403. entry_nodes_should_be_added();
  3404. reasons = digestmap_new();
  3405. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
  3406. {
  3407. routerinfo_t *r = router_get_by_digest(entry->identity);
  3408. const char *reason = NULL;
  3409. if (entry_guard_set_status(entry, r, now, options, &reason))
  3410. changed = 1;
  3411. if (entry->bad_since)
  3412. tor_assert(reason);
  3413. if (reason)
  3414. digestmap_set(reasons, entry->identity, (char*)reason);
  3415. }
  3416. SMARTLIST_FOREACH_END(entry);
  3417. if (remove_dead_entry_guards(now))
  3418. changed = 1;
  3419. severity = changed ? LOG_DEBUG : LOG_INFO;
  3420. if (changed) {
  3421. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
  3422. const char *reason = digestmap_get(reasons, entry->identity);
  3423. const char *live_msg = "";
  3424. routerinfo_t *r = entry_is_live(entry, 0, 1, 0, &live_msg);
  3425. log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s%s%s, and %s%s.",
  3426. entry->nickname,
  3427. entry->unreachable_since ? "unreachable" : "reachable",
  3428. entry->bad_since ? "unusable" : "usable",
  3429. reason ? ", ": "",
  3430. reason ? reason : "",
  3431. r ? "live" : "not live / ",
  3432. r ? "" : live_msg);
  3433. } SMARTLIST_FOREACH_END(entry);
  3434. log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
  3435. num_live_entry_guards(), smartlist_len(entry_guards));
  3436. log_entry_guards(LOG_INFO);
  3437. entry_guards_changed();
  3438. }
  3439. digestmap_free(reasons, NULL);
  3440. }
  3441. /** Called when a connection to an OR with the identity digest <b>digest</b>
  3442. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  3443. * If the OR is an entry, change that entry's up/down status.
  3444. * Return 0 normally, or -1 if we want to tear down the new connection.
  3445. *
  3446. * If <b>mark_relay_status</b>, also call router_set_status() on this
  3447. * relay.
  3448. *
  3449. * XXX023 change succeeded and mark_relay_status into 'int flags'.
  3450. */
  3451. int
  3452. entry_guard_register_connect_status(const char *digest, int succeeded,
  3453. int mark_relay_status, time_t now)
  3454. {
  3455. int changed = 0;
  3456. int refuse_conn = 0;
  3457. int first_contact = 0;
  3458. entry_guard_t *entry = NULL;
  3459. int idx = -1;
  3460. char buf[HEX_DIGEST_LEN+1];
  3461. if (! entry_guards)
  3462. return 0;
  3463. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3464. {
  3465. if (!memcmp(e->identity, digest, DIGEST_LEN)) {
  3466. entry = e;
  3467. idx = e_sl_idx;
  3468. break;
  3469. }
  3470. });
  3471. if (!entry)
  3472. return 0;
  3473. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  3474. if (succeeded) {
  3475. if (entry->unreachable_since) {
  3476. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  3477. entry->nickname, buf);
  3478. entry->can_retry = 0;
  3479. entry->unreachable_since = 0;
  3480. entry->last_attempted = now;
  3481. control_event_guard(entry->nickname, entry->identity, "UP");
  3482. changed = 1;
  3483. }
  3484. if (!entry->made_contact) {
  3485. entry->made_contact = 1;
  3486. first_contact = changed = 1;
  3487. }
  3488. } else { /* ! succeeded */
  3489. if (!entry->made_contact) {
  3490. /* We've never connected to this one. */
  3491. log_info(LD_CIRC,
  3492. "Connection to never-contacted entry guard '%s' (%s) failed. "
  3493. "Removing from the list. %d/%d entry guards usable/new.",
  3494. entry->nickname, buf,
  3495. num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
  3496. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3497. entry_guard_free(entry);
  3498. smartlist_del_keeporder(entry_guards, idx);
  3499. log_entry_guards(LOG_INFO);
  3500. changed = 1;
  3501. } else if (!entry->unreachable_since) {
  3502. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  3503. "Marking as unreachable.", entry->nickname, buf);
  3504. entry->unreachable_since = entry->last_attempted = now;
  3505. control_event_guard(entry->nickname, entry->identity, "DOWN");
  3506. changed = 1;
  3507. entry->can_retry = 0; /* We gave it an early chance; no good. */
  3508. } else {
  3509. char tbuf[ISO_TIME_LEN+1];
  3510. format_iso_time(tbuf, entry->unreachable_since);
  3511. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  3512. "'%s' (%s). It has been unreachable since %s.",
  3513. entry->nickname, buf, tbuf);
  3514. entry->last_attempted = now;
  3515. entry->can_retry = 0; /* We gave it an early chance; no good. */
  3516. }
  3517. }
  3518. /* if the caller asked us to, also update the is_running flags for this
  3519. * relay */
  3520. if (mark_relay_status)
  3521. router_set_status(digest, succeeded);
  3522. if (first_contact) {
  3523. /* We've just added a new long-term entry guard. Perhaps the network just
  3524. * came back? We should give our earlier entries another try too,
  3525. * and close this connection so we don't use it before we've given
  3526. * the others a shot. */
  3527. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  3528. if (e == entry)
  3529. break;
  3530. if (e->made_contact) {
  3531. const char *msg;
  3532. routerinfo_t *r = entry_is_live(e, 0, 1, 1, &msg);
  3533. if (r && e->unreachable_since) {
  3534. refuse_conn = 1;
  3535. e->can_retry = 1;
  3536. }
  3537. }
  3538. });
  3539. if (refuse_conn) {
  3540. log_info(LD_CIRC,
  3541. "Connected to new entry guard '%s' (%s). Marking earlier "
  3542. "entry guards up. %d/%d entry guards usable/new.",
  3543. entry->nickname, buf,
  3544. num_live_entry_guards(), smartlist_len(entry_guards));
  3545. log_entry_guards(LOG_INFO);
  3546. changed = 1;
  3547. }
  3548. }
  3549. if (changed)
  3550. entry_guards_changed();
  3551. return refuse_conn ? -1 : 0;
  3552. }
  3553. /** When we try to choose an entry guard, should we parse and add
  3554. * config's EntryNodes first? */
  3555. static int should_add_entry_nodes = 0;
  3556. /** Called when the value of EntryNodes changes in our configuration. */
  3557. void
  3558. entry_nodes_should_be_added(void)
  3559. {
  3560. log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
  3561. "relays at the front of the entry guard list.");
  3562. should_add_entry_nodes = 1;
  3563. }
  3564. /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
  3565. * of guard nodes, at the front. */
  3566. static void
  3567. entry_guards_prepend_from_config(or_options_t *options)
  3568. {
  3569. smartlist_t *entry_routers, *entry_fps;
  3570. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  3571. tor_assert(entry_guards);
  3572. should_add_entry_nodes = 0;
  3573. if (!options->EntryNodes) {
  3574. /* It's possible that a controller set EntryNodes, thus making
  3575. * should_add_entry_nodes set, then cleared it again, all before the
  3576. * call to choose_random_entry() that triggered us. If so, just return.
  3577. */
  3578. return;
  3579. }
  3580. {
  3581. char *string = routerset_to_string(options->EntryNodes);
  3582. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
  3583. tor_free(string);
  3584. }
  3585. entry_routers = smartlist_create();
  3586. entry_fps = smartlist_create();
  3587. old_entry_guards_on_list = smartlist_create();
  3588. old_entry_guards_not_on_list = smartlist_create();
  3589. /* Split entry guards into those on the list and those not. */
  3590. /* XXXX023 Now that we allow countries and IP ranges in EntryNodes, this is
  3591. * potentially an enormous list. For now, we disable such values for
  3592. * EntryNodes in options_validate(); really, this wants a better solution.
  3593. * Perhaps we should do this calculation once whenever the list of routers
  3594. * changes or the entrynodes setting changes.
  3595. */
  3596. routerset_get_all_routers(entry_routers, options->EntryNodes,
  3597. options->ExcludeNodes, 0);
  3598. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
  3599. smartlist_add(entry_fps,ri->cache_info.identity_digest));
  3600. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  3601. if (smartlist_digest_isin(entry_fps, e->identity))
  3602. smartlist_add(old_entry_guards_on_list, e);
  3603. else
  3604. smartlist_add(old_entry_guards_not_on_list, e);
  3605. });
  3606. /* Remove all currently configured entry guards from entry_routers. */
  3607. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  3608. if (is_an_entry_guard(ri->cache_info.identity_digest)) {
  3609. SMARTLIST_DEL_CURRENT(entry_routers, ri);
  3610. }
  3611. });
  3612. /* Now build the new entry_guards list. */
  3613. smartlist_clear(entry_guards);
  3614. /* First, the previously configured guards that are in EntryNodes. */
  3615. smartlist_add_all(entry_guards, old_entry_guards_on_list);
  3616. /* Next, the rest of EntryNodes */
  3617. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  3618. add_an_entry_guard(ri, 0);
  3619. });
  3620. /* Finally, free the remaining previously configured guards that are not in
  3621. * EntryNodes. */
  3622. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  3623. entry_guard_free(e));
  3624. smartlist_free(entry_routers);
  3625. smartlist_free(entry_fps);
  3626. smartlist_free(old_entry_guards_on_list);
  3627. smartlist_free(old_entry_guards_not_on_list);
  3628. entry_guards_changed();
  3629. }
  3630. /** Return 0 if we're fine adding arbitrary routers out of the
  3631. * directory to our entry guard list, or return 1 if we have a
  3632. * list already and we must stick to it.
  3633. */
  3634. int
  3635. entry_list_is_constrained(or_options_t *options)
  3636. {
  3637. if (options->EntryNodes)
  3638. return 1;
  3639. if (options->UseBridges)
  3640. return 1;
  3641. return 0;
  3642. }
  3643. /** Pick a live (up and listed) entry guard from entry_guards. If
  3644. * <b>state</b> is non-NULL, this is for a specific circuit --
  3645. * make sure not to pick this circuit's exit or any node in the
  3646. * exit's family. If <b>state</b> is NULL, we're looking for a random
  3647. * guard (likely a bridge). */
  3648. routerinfo_t *
  3649. choose_random_entry(cpath_build_state_t *state)
  3650. {
  3651. or_options_t *options = get_options();
  3652. smartlist_t *live_entry_guards = smartlist_create();
  3653. smartlist_t *exit_family = smartlist_create();
  3654. routerinfo_t *chosen_exit = state?build_state_get_exit_router(state) : NULL;
  3655. routerinfo_t *r = NULL;
  3656. int need_uptime = state ? state->need_uptime : 0;
  3657. int need_capacity = state ? state->need_capacity : 0;
  3658. int preferred_min, consider_exit_family = 0;
  3659. if (chosen_exit) {
  3660. routerlist_add_family(exit_family, chosen_exit);
  3661. consider_exit_family = 1;
  3662. }
  3663. if (!entry_guards)
  3664. entry_guards = smartlist_create();
  3665. if (should_add_entry_nodes)
  3666. entry_guards_prepend_from_config(options);
  3667. if (!entry_list_is_constrained(options) &&
  3668. smartlist_len(entry_guards) < options->NumEntryGuards)
  3669. pick_entry_guards(options);
  3670. retry:
  3671. smartlist_clear(live_entry_guards);
  3672. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3673. {
  3674. const char *msg;
  3675. r = entry_is_live(entry, need_uptime, need_capacity, 0, &msg);
  3676. if (!r)
  3677. continue; /* down, no point */
  3678. if (r == chosen_exit)
  3679. continue; /* don't pick the same node for entry and exit */
  3680. if (consider_exit_family && smartlist_isin(exit_family, r))
  3681. continue; /* avoid relays that are family members of our exit */
  3682. #if 0 /* since EntryNodes is always strict now, this clause is moot */
  3683. if (options->EntryNodes &&
  3684. !routerset_contains_router(options->EntryNodes, r)) {
  3685. /* We've come to the end of our preferred entry nodes. */
  3686. if (smartlist_len(live_entry_guards))
  3687. goto choose_and_finish; /* only choose from the ones we like */
  3688. if (options->StrictNodes) {
  3689. /* in theory this case should never happen, since
  3690. * entry_guards_prepend_from_config() drops unwanted relays */
  3691. tor_fragile_assert();
  3692. } else {
  3693. log_info(LD_CIRC,
  3694. "No relays from EntryNodes available. Using others.");
  3695. }
  3696. }
  3697. #endif
  3698. smartlist_add(live_entry_guards, r);
  3699. if (!entry->made_contact) {
  3700. /* Always start with the first not-yet-contacted entry
  3701. * guard. Otherwise we might add several new ones, pick
  3702. * the second new one, and now we've expanded our entry
  3703. * guard list without needing to. */
  3704. goto choose_and_finish;
  3705. }
  3706. if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
  3707. break; /* we have enough */
  3708. });
  3709. if (entry_list_is_constrained(options)) {
  3710. /* If we prefer the entry nodes we've got, and we have at least
  3711. * one choice, that's great. Use it. */
  3712. preferred_min = 1;
  3713. } else {
  3714. /* Try to have at least 2 choices available. This way we don't
  3715. * get stuck with a single live-but-crummy entry and just keep
  3716. * using him.
  3717. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  3718. preferred_min = 2;
  3719. }
  3720. if (smartlist_len(live_entry_guards) < preferred_min) {
  3721. if (!entry_list_is_constrained(options)) {
  3722. /* still no? try adding a new entry then */
  3723. /* XXX if guard doesn't imply fast and stable, then we need
  3724. * to tell add_an_entry_guard below what we want, or it might
  3725. * be a long time til we get it. -RD */
  3726. r = add_an_entry_guard(NULL, 0);
  3727. if (r) {
  3728. entry_guards_changed();
  3729. /* XXX we start over here in case the new node we added shares
  3730. * a family with our exit node. There's a chance that we'll just
  3731. * load up on entry guards here, if the network we're using is
  3732. * one big family. Perhaps we should teach add_an_entry_guard()
  3733. * to understand nodes-to-avoid-if-possible? -RD */
  3734. goto retry;
  3735. }
  3736. }
  3737. if (!r && need_uptime) {
  3738. need_uptime = 0; /* try without that requirement */
  3739. goto retry;
  3740. }
  3741. if (!r && need_capacity) {
  3742. /* still no? last attempt, try without requiring capacity */
  3743. need_capacity = 0;
  3744. goto retry;
  3745. }
  3746. #if 0
  3747. /* Removing this retry logic: if we only allow one exit, and it is in the
  3748. same family as all our entries, then we are just plain not going to win
  3749. here. */
  3750. if (!r && entry_list_is_constrained(options) && consider_exit_family) {
  3751. /* still no? if we're using bridges,
  3752. * and our chosen exit is in the same family as all our
  3753. * bridges, then be flexible about families. */
  3754. consider_exit_family = 0;
  3755. goto retry;
  3756. }
  3757. #endif
  3758. /* live_entry_guards may be empty below. Oh well, we tried. */
  3759. }
  3760. choose_and_finish:
  3761. if (entry_list_is_constrained(options)) {
  3762. /* We need to weight by bandwidth, because our bridges or entryguards
  3763. * were not already selected proportional to their bandwidth. */
  3764. r = routerlist_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  3765. } else {
  3766. /* We choose uniformly at random here, because choose_good_entry_server()
  3767. * already weights its choices by bandwidth, so we don't want to
  3768. * *double*-weight our guard selection. */
  3769. r = smartlist_choose(live_entry_guards);
  3770. }
  3771. smartlist_free(live_entry_guards);
  3772. smartlist_free(exit_family);
  3773. return r;
  3774. }
  3775. /** Parse <b>state</b> and learn about the entry guards it describes.
  3776. * If <b>set</b> is true, and there are no errors, replace the global
  3777. * entry_list with what we find.
  3778. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  3779. * describing the error, and return -1.
  3780. */
  3781. int
  3782. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  3783. {
  3784. entry_guard_t *node = NULL;
  3785. smartlist_t *new_entry_guards = smartlist_create();
  3786. config_line_t *line;
  3787. time_t now = time(NULL);
  3788. const char *state_version = state->TorVersion;
  3789. digestmap_t *added_by = digestmap_new();
  3790. *msg = NULL;
  3791. for (line = state->EntryGuards; line; line = line->next) {
  3792. if (!strcasecmp(line->key, "EntryGuard")) {
  3793. smartlist_t *args = smartlist_create();
  3794. node = tor_malloc_zero(sizeof(entry_guard_t));
  3795. /* all entry guards on disk have been contacted */
  3796. node->made_contact = 1;
  3797. smartlist_add(new_entry_guards, node);
  3798. smartlist_split_string(args, line->value, " ",
  3799. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3800. if (smartlist_len(args)<2) {
  3801. *msg = tor_strdup("Unable to parse entry nodes: "
  3802. "Too few arguments to EntryGuard");
  3803. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  3804. *msg = tor_strdup("Unable to parse entry nodes: "
  3805. "Bad nickname for EntryGuard");
  3806. } else {
  3807. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  3808. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  3809. strlen(smartlist_get(args,1)))<0) {
  3810. *msg = tor_strdup("Unable to parse entry nodes: "
  3811. "Bad hex digest for EntryGuard");
  3812. }
  3813. }
  3814. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  3815. smartlist_free(args);
  3816. if (*msg)
  3817. break;
  3818. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  3819. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  3820. time_t when;
  3821. time_t last_try = 0;
  3822. if (!node) {
  3823. *msg = tor_strdup("Unable to parse entry nodes: "
  3824. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  3825. break;
  3826. }
  3827. if (parse_iso_time(line->value, &when)<0) {
  3828. *msg = tor_strdup("Unable to parse entry nodes: "
  3829. "Bad time in EntryGuardDownSince/UnlistedSince");
  3830. break;
  3831. }
  3832. if (when > now) {
  3833. /* It's a bad idea to believe info in the future: you can wind
  3834. * up with timeouts that aren't allowed to happen for years. */
  3835. continue;
  3836. }
  3837. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  3838. /* ignore failure */
  3839. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  3840. }
  3841. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  3842. node->unreachable_since = when;
  3843. node->last_attempted = last_try;
  3844. } else {
  3845. node->bad_since = when;
  3846. }
  3847. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  3848. char d[DIGEST_LEN];
  3849. /* format is digest version date */
  3850. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  3851. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  3852. continue;
  3853. }
  3854. if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
  3855. line->value[HEX_DIGEST_LEN] != ' ') {
  3856. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  3857. "hex digest", escaped(line->value));
  3858. continue;
  3859. }
  3860. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  3861. } else {
  3862. log_warn(LD_BUG, "Unexpected key %s", line->key);
  3863. }
  3864. }
  3865. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  3866. {
  3867. char *sp;
  3868. char *val = digestmap_get(added_by, e->identity);
  3869. if (val && (sp = strchr(val, ' '))) {
  3870. time_t when;
  3871. *sp++ = '\0';
  3872. if (parse_iso_time(sp, &when)<0) {
  3873. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  3874. } else {
  3875. e->chosen_by_version = tor_strdup(val);
  3876. e->chosen_on_date = when;
  3877. }
  3878. } else {
  3879. if (state_version) {
  3880. e->chosen_by_version = tor_strdup(state_version);
  3881. e->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
  3882. }
  3883. }
  3884. });
  3885. if (*msg || !set) {
  3886. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  3887. entry_guard_free(e));
  3888. smartlist_free(new_entry_guards);
  3889. } else { /* !err && set */
  3890. if (entry_guards) {
  3891. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3892. entry_guard_free(e));
  3893. smartlist_free(entry_guards);
  3894. }
  3895. entry_guards = new_entry_guards;
  3896. entry_guards_dirty = 0;
  3897. /* XXX023 hand new_entry_guards to this func, and move it up a
  3898. * few lines, so we don't have to re-dirty it */
  3899. if (remove_obsolete_entry_guards(now))
  3900. entry_guards_dirty = 1;
  3901. }
  3902. digestmap_free(added_by, _tor_free);
  3903. return *msg ? -1 : 0;
  3904. }
  3905. /** Our list of entry guards has changed, or some element of one
  3906. * of our entry guards has changed. Write the changes to disk within
  3907. * the next few minutes.
  3908. */
  3909. static void
  3910. entry_guards_changed(void)
  3911. {
  3912. time_t when;
  3913. entry_guards_dirty = 1;
  3914. /* or_state_save() will call entry_guards_update_state(). */
  3915. when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
  3916. or_state_mark_dirty(get_or_state(), when);
  3917. }
  3918. /** If the entry guard info has not changed, do nothing and return.
  3919. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  3920. * a new one out of the global entry_guards list, and then mark
  3921. * <b>state</b> dirty so it will get saved to disk.
  3922. */
  3923. void
  3924. entry_guards_update_state(or_state_t *state)
  3925. {
  3926. config_line_t **next, *line;
  3927. if (! entry_guards_dirty)
  3928. return;
  3929. config_free_lines(state->EntryGuards);
  3930. next = &state->EntryGuards;
  3931. *next = NULL;
  3932. if (!entry_guards)
  3933. entry_guards = smartlist_create();
  3934. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  3935. {
  3936. char dbuf[HEX_DIGEST_LEN+1];
  3937. if (!e->made_contact)
  3938. continue; /* don't write this one to disk */
  3939. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3940. line->key = tor_strdup("EntryGuard");
  3941. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  3942. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  3943. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  3944. "%s %s", e->nickname, dbuf);
  3945. next = &(line->next);
  3946. if (e->unreachable_since) {
  3947. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3948. line->key = tor_strdup("EntryGuardDownSince");
  3949. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  3950. format_iso_time(line->value, e->unreachable_since);
  3951. if (e->last_attempted) {
  3952. line->value[ISO_TIME_LEN] = ' ';
  3953. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  3954. }
  3955. next = &(line->next);
  3956. }
  3957. if (e->bad_since) {
  3958. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3959. line->key = tor_strdup("EntryGuardUnlistedSince");
  3960. line->value = tor_malloc(ISO_TIME_LEN+1);
  3961. format_iso_time(line->value, e->bad_since);
  3962. next = &(line->next);
  3963. }
  3964. if (e->chosen_on_date && e->chosen_by_version &&
  3965. !strchr(e->chosen_by_version, ' ')) {
  3966. char d[HEX_DIGEST_LEN+1];
  3967. char t[ISO_TIME_LEN+1];
  3968. size_t val_len;
  3969. *next = line = tor_malloc_zero(sizeof(config_line_t));
  3970. line->key = tor_strdup("EntryGuardAddedBy");
  3971. val_len = (HEX_DIGEST_LEN+1+strlen(e->chosen_by_version)
  3972. +1+ISO_TIME_LEN+1);
  3973. line->value = tor_malloc(val_len);
  3974. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  3975. format_iso_time(t, e->chosen_on_date);
  3976. tor_snprintf(line->value, val_len, "%s %s %s",
  3977. d, e->chosen_by_version, t);
  3978. next = &(line->next);
  3979. }
  3980. });
  3981. if (!get_options()->AvoidDiskWrites)
  3982. or_state_mark_dirty(get_or_state(), 0);
  3983. entry_guards_dirty = 0;
  3984. }
  3985. /** If <b>question</b> is the string "entry-guards", then dump
  3986. * to *<b>answer</b> a newly allocated string describing all of
  3987. * the nodes in the global entry_guards list. See control-spec.txt
  3988. * for details.
  3989. * For backward compatibility, we also handle the string "helper-nodes".
  3990. * */
  3991. int
  3992. getinfo_helper_entry_guards(control_connection_t *conn,
  3993. const char *question, char **answer,
  3994. const char **errmsg)
  3995. {
  3996. (void) conn;
  3997. (void) errmsg;
  3998. if (!strcmp(question,"entry-guards") ||
  3999. !strcmp(question,"helper-nodes")) {
  4000. smartlist_t *sl = smartlist_create();
  4001. char tbuf[ISO_TIME_LEN+1];
  4002. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  4003. if (!entry_guards)
  4004. entry_guards = smartlist_create();
  4005. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
  4006. size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
  4007. char *c = tor_malloc(len);
  4008. const char *status = NULL;
  4009. time_t when = 0;
  4010. routerinfo_t *ri;
  4011. if (!e->made_contact) {
  4012. status = "never-connected";
  4013. } else if (e->bad_since) {
  4014. when = e->bad_since;
  4015. status = "unusable";
  4016. } else {
  4017. status = "up";
  4018. }
  4019. ri = router_get_by_digest(e->identity);
  4020. if (ri) {
  4021. router_get_verbose_nickname(nbuf, ri);
  4022. } else {
  4023. nbuf[0] = '$';
  4024. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  4025. /* e->nickname field is not very reliable if we don't know about
  4026. * this router any longer; don't include it. */
  4027. }
  4028. if (when) {
  4029. format_iso_time(tbuf, when);
  4030. tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
  4031. } else {
  4032. tor_snprintf(c, len, "%s %s\n", nbuf, status);
  4033. }
  4034. smartlist_add(sl, c);
  4035. } SMARTLIST_FOREACH_END(e);
  4036. *answer = smartlist_join_strings(sl, "", 0, NULL);
  4037. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  4038. smartlist_free(sl);
  4039. }
  4040. return 0;
  4041. }
  4042. /** Information about a configured bridge. Currently this just matches the
  4043. * ones in the torrc file, but one day we may be able to learn about new
  4044. * bridges on our own, and remember them in the state file. */
  4045. typedef struct {
  4046. /** Address of the bridge. */
  4047. tor_addr_t addr;
  4048. /** TLS port for the bridge. */
  4049. uint16_t port;
  4050. /** Expected identity digest, or all zero bytes if we don't know what the
  4051. * digest should be. */
  4052. char identity[DIGEST_LEN];
  4053. /** When should we next try to fetch a descriptor for this bridge? */
  4054. download_status_t fetch_status;
  4055. } bridge_info_t;
  4056. /** A list of configured bridges. Whenever we actually get a descriptor
  4057. * for one, we add it as an entry guard. */
  4058. static smartlist_t *bridge_list = NULL;
  4059. /** Initialize the bridge list to empty, creating it if needed. */
  4060. void
  4061. clear_bridge_list(void)
  4062. {
  4063. if (!bridge_list)
  4064. bridge_list = smartlist_create();
  4065. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, tor_free(b));
  4066. smartlist_clear(bridge_list);
  4067. }
  4068. /** Return a bridge pointer if <b>ri</b> is one of our known bridges
  4069. * (either by comparing keys if possible, else by comparing addr/port).
  4070. * Else return NULL. */
  4071. static bridge_info_t *
  4072. get_configured_bridge_by_addr_port_digest(tor_addr_t *addr, uint16_t port,
  4073. const char *digest)
  4074. {
  4075. if (!bridge_list)
  4076. return NULL;
  4077. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  4078. {
  4079. if (tor_digest_is_zero(bridge->identity) &&
  4080. !tor_addr_compare(&bridge->addr, addr, CMP_EXACT) &&
  4081. bridge->port == port)
  4082. return bridge;
  4083. if (!memcmp(bridge->identity, digest, DIGEST_LEN))
  4084. return bridge;
  4085. }
  4086. SMARTLIST_FOREACH_END(bridge);
  4087. return NULL;
  4088. }
  4089. /** Wrapper around get_configured_bridge_by_addr_port_digest() to look
  4090. * it up via router descriptor <b>ri</b>. */
  4091. static bridge_info_t *
  4092. get_configured_bridge_by_routerinfo(routerinfo_t *ri)
  4093. {
  4094. tor_addr_t addr;
  4095. tor_addr_from_ipv4h(&addr, ri->addr);
  4096. return get_configured_bridge_by_addr_port_digest(&addr,
  4097. ri->or_port, ri->cache_info.identity_digest);
  4098. }
  4099. /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
  4100. int
  4101. routerinfo_is_a_configured_bridge(routerinfo_t *ri)
  4102. {
  4103. return get_configured_bridge_by_routerinfo(ri) ? 1 : 0;
  4104. }
  4105. /** We made a connection to a router at <b>addr</b>:<b>port</b>
  4106. * without knowing its digest. Its digest turned out to be <b>digest</b>.
  4107. * If it was a bridge, and we still don't know its digest, record it.
  4108. */
  4109. void
  4110. learned_router_identity(tor_addr_t *addr, uint16_t port, const char *digest)
  4111. {
  4112. bridge_info_t *bridge =
  4113. get_configured_bridge_by_addr_port_digest(addr, port, digest);
  4114. if (bridge && tor_digest_is_zero(bridge->identity)) {
  4115. memcpy(bridge->identity, digest, DIGEST_LEN);
  4116. log_notice(LD_DIR, "Learned fingerprint %s for bridge %s:%d",
  4117. hex_str(digest, DIGEST_LEN), fmt_addr(addr), port);
  4118. }
  4119. }
  4120. /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
  4121. * is set, it tells us the identity key too. */
  4122. void
  4123. bridge_add_from_config(const tor_addr_t *addr, uint16_t port, char *digest)
  4124. {
  4125. bridge_info_t *b = tor_malloc_zero(sizeof(bridge_info_t));
  4126. tor_addr_copy(&b->addr, addr);
  4127. b->port = port;
  4128. if (digest)
  4129. memcpy(b->identity, digest, DIGEST_LEN);
  4130. b->fetch_status.schedule = DL_SCHED_BRIDGE;
  4131. if (!bridge_list)
  4132. bridge_list = smartlist_create();
  4133. smartlist_add(bridge_list, b);
  4134. }
  4135. /** Return true iff <b>routerset</b> contains the bridge <b>bridge</b>. */
  4136. static int
  4137. routerset_contains_bridge(const routerset_t *routerset,
  4138. const bridge_info_t *bridge)
  4139. {
  4140. int result;
  4141. extend_info_t *extinfo;
  4142. tor_assert(bridge);
  4143. if (!routerset)
  4144. return 0;
  4145. extinfo = extend_info_alloc(
  4146. NULL, bridge->identity, NULL, &bridge->addr, bridge->port);
  4147. result = routerset_contains_extendinfo(routerset, extinfo);
  4148. extend_info_free(extinfo);
  4149. return result;
  4150. }
  4151. /** If <b>digest</b> is one of our known bridges, return it. */
  4152. static bridge_info_t *
  4153. find_bridge_by_digest(const char *digest)
  4154. {
  4155. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  4156. {
  4157. if (!memcmp(bridge->identity, digest, DIGEST_LEN))
  4158. return bridge;
  4159. });
  4160. return NULL;
  4161. }
  4162. /** We need to ask <b>bridge</b> for its server descriptor. */
  4163. static void
  4164. launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
  4165. {
  4166. char *address;
  4167. or_options_t *options = get_options();
  4168. if (connection_get_by_type_addr_port_purpose(
  4169. CONN_TYPE_DIR, &bridge->addr, bridge->port,
  4170. DIR_PURPOSE_FETCH_SERVERDESC))
  4171. return; /* it's already on the way */
  4172. address = tor_dup_addr(&bridge->addr);
  4173. if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
  4174. download_status_mark_impossible(&bridge->fetch_status);
  4175. log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
  4176. safe_str_client(fmt_addr(&bridge->addr)));
  4177. return;
  4178. }
  4179. directory_initiate_command(address, &bridge->addr,
  4180. bridge->port, 0,
  4181. 0, /* does not matter */
  4182. 1, bridge->identity,
  4183. DIR_PURPOSE_FETCH_SERVERDESC,
  4184. ROUTER_PURPOSE_BRIDGE,
  4185. 0, "authority.z", NULL, 0, 0);
  4186. tor_free(address);
  4187. }
  4188. /** Fetching the bridge descriptor from the bridge authority returned a
  4189. * "not found". Fall back to trying a direct fetch. */
  4190. void
  4191. retry_bridge_descriptor_fetch_directly(const char *digest)
  4192. {
  4193. bridge_info_t *bridge = find_bridge_by_digest(digest);
  4194. if (!bridge)
  4195. return; /* not found? oh well. */
  4196. launch_direct_bridge_descriptor_fetch(bridge);
  4197. }
  4198. /** For each bridge in our list for which we don't currently have a
  4199. * descriptor, fetch a new copy of its descriptor -- either directly
  4200. * from the bridge or via a bridge authority. */
  4201. void
  4202. fetch_bridge_descriptors(or_options_t *options, time_t now)
  4203. {
  4204. int num_bridge_auths = get_n_authorities(BRIDGE_AUTHORITY);
  4205. int ask_bridge_directly;
  4206. int can_use_bridge_authority;
  4207. if (!bridge_list)
  4208. return;
  4209. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  4210. {
  4211. if (!download_status_is_ready(&bridge->fetch_status, now,
  4212. IMPOSSIBLE_TO_DOWNLOAD))
  4213. continue; /* don't bother, no need to retry yet */
  4214. if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
  4215. download_status_mark_impossible(&bridge->fetch_status);
  4216. log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
  4217. safe_str_client(fmt_addr(&bridge->addr)));
  4218. continue;
  4219. }
  4220. /* schedule another fetch as if this one will fail, in case it does */
  4221. download_status_failed(&bridge->fetch_status, 0);
  4222. can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
  4223. num_bridge_auths;
  4224. ask_bridge_directly = !can_use_bridge_authority ||
  4225. !options->UpdateBridgesFromAuthority;
  4226. log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
  4227. ask_bridge_directly, tor_digest_is_zero(bridge->identity),
  4228. !options->UpdateBridgesFromAuthority, !num_bridge_auths);
  4229. if (ask_bridge_directly &&
  4230. !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
  4231. log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
  4232. "firewall policy. %s.", fmt_addr(&bridge->addr),
  4233. bridge->port,
  4234. can_use_bridge_authority ?
  4235. "Asking bridge authority instead" : "Skipping");
  4236. if (can_use_bridge_authority)
  4237. ask_bridge_directly = 0;
  4238. else
  4239. continue;
  4240. }
  4241. if (ask_bridge_directly) {
  4242. /* we need to ask the bridge itself for its descriptor. */
  4243. launch_direct_bridge_descriptor_fetch(bridge);
  4244. } else {
  4245. /* We have a digest and we want to ask an authority. We could
  4246. * combine all the requests into one, but that may give more
  4247. * hints to the bridge authority than we want to give. */
  4248. char resource[10 + HEX_DIGEST_LEN];
  4249. memcpy(resource, "fp/", 3);
  4250. base16_encode(resource+3, HEX_DIGEST_LEN+1,
  4251. bridge->identity, DIGEST_LEN);
  4252. memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
  4253. log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
  4254. resource);
  4255. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  4256. ROUTER_PURPOSE_BRIDGE, resource, 0);
  4257. }
  4258. }
  4259. SMARTLIST_FOREACH_END(bridge);
  4260. }
  4261. /** If our <b>bridge</b> is configured to be a different address than
  4262. * the bridge gives in its routerinfo <b>ri</b>, rewrite the routerinfo
  4263. * we received to use the address we meant to use. Now we handle
  4264. * multihomed bridges better.
  4265. */
  4266. static void
  4267. rewrite_routerinfo_address_for_bridge(bridge_info_t *bridge, routerinfo_t *ri)
  4268. {
  4269. tor_addr_t addr;
  4270. tor_addr_from_ipv4h(&addr, ri->addr);
  4271. if (!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
  4272. bridge->port == ri->or_port)
  4273. return; /* they match, so no need to do anything */
  4274. ri->addr = tor_addr_to_ipv4h(&bridge->addr);
  4275. tor_free(ri->address);
  4276. ri->address = tor_dup_ip(ri->addr);
  4277. ri->or_port = bridge->port;
  4278. log_info(LD_DIR, "Adjusted bridge '%s' to match configured address %s:%d.",
  4279. ri->nickname, ri->address, ri->or_port);
  4280. }
  4281. /** We just learned a descriptor for a bridge. See if that
  4282. * digest is in our entry guard list, and add it if not. */
  4283. void
  4284. learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
  4285. {
  4286. tor_assert(ri);
  4287. tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
  4288. if (get_options()->UseBridges) {
  4289. int first = !any_bridge_descriptors_known();
  4290. bridge_info_t *bridge = get_configured_bridge_by_routerinfo(ri);
  4291. time_t now = time(NULL);
  4292. ri->is_running = 1;
  4293. if (bridge) { /* if we actually want to use this one */
  4294. /* it's here; schedule its re-fetch for a long time from now. */
  4295. if (!from_cache)
  4296. download_status_reset(&bridge->fetch_status);
  4297. rewrite_routerinfo_address_for_bridge(bridge, ri);
  4298. add_an_entry_guard(ri, 1);
  4299. log_notice(LD_DIR, "new bridge descriptor '%s' (%s)", ri->nickname,
  4300. from_cache ? "cached" : "fresh");
  4301. /* set entry->made_contact so if it goes down we don't drop it from
  4302. * our entry node list */
  4303. entry_guard_register_connect_status(ri->cache_info.identity_digest,
  4304. 1, 0, now);
  4305. if (first)
  4306. routerlist_retry_directory_downloads(now);
  4307. }
  4308. }
  4309. }
  4310. /** Return 1 if any of our entry guards have descriptors that
  4311. * are marked with purpose 'bridge' and are running. Else return 0.
  4312. *
  4313. * We use this function to decide if we're ready to start building
  4314. * circuits through our bridges, or if we need to wait until the
  4315. * directory "server/authority" requests finish. */
  4316. int
  4317. any_bridge_descriptors_known(void)
  4318. {
  4319. tor_assert(get_options()->UseBridges);
  4320. return choose_random_entry(NULL)!=NULL ? 1 : 0;
  4321. }
  4322. /** Return 1 if there are any directory conns fetching bridge descriptors
  4323. * that aren't marked for close. We use this to guess if we should tell
  4324. * the controller that we have a problem. */
  4325. int
  4326. any_pending_bridge_descriptor_fetches(void)
  4327. {
  4328. smartlist_t *conns = get_connection_array();
  4329. SMARTLIST_FOREACH(conns, connection_t *, conn,
  4330. {
  4331. if (conn->type == CONN_TYPE_DIR &&
  4332. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  4333. TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
  4334. !conn->marked_for_close &&
  4335. conn->linked &&
  4336. conn->linked_conn && !conn->linked_conn->marked_for_close) {
  4337. log_debug(LD_DIR, "found one: %s", conn->address);
  4338. return 1;
  4339. }
  4340. });
  4341. return 0;
  4342. }
  4343. /** Return 1 if we have at least one descriptor for an entry guard
  4344. * (bridge or member of EntryNodes) and all descriptors we know are
  4345. * down. Else return 0. If <b>act</b> is 1, then mark the down guards
  4346. * up; else just observe and report. */
  4347. static int
  4348. entries_retry_helper(or_options_t *options, int act)
  4349. {
  4350. routerinfo_t *ri;
  4351. int any_known = 0;
  4352. int any_running = 0;
  4353. int purpose = options->UseBridges ?
  4354. ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  4355. if (!entry_guards)
  4356. entry_guards = smartlist_create();
  4357. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  4358. {
  4359. ri = router_get_by_digest(e->identity);
  4360. if (ri && ri->purpose == purpose) {
  4361. any_known = 1;
  4362. if (ri->is_running)
  4363. any_running = 1; /* some entry is both known and running */
  4364. else if (act) {
  4365. /* Mark all current connections to this OR as unhealthy, since
  4366. * otherwise there could be one that started 30 seconds
  4367. * ago, and in 30 seconds it will time out, causing us to mark
  4368. * the node down and undermine the retry attempt. We mark even
  4369. * the established conns, since if the network just came back
  4370. * we'll want to attach circuits to fresh conns. */
  4371. connection_or_set_bad_connections(ri->cache_info.identity_digest, 1);
  4372. /* mark this entry node for retry */
  4373. router_set_status(ri->cache_info.identity_digest, 1);
  4374. e->can_retry = 1;
  4375. e->bad_since = 0;
  4376. }
  4377. }
  4378. });
  4379. log_debug(LD_DIR, "%d: any_known %d, any_running %d",
  4380. act, any_known, any_running);
  4381. return any_known && !any_running;
  4382. }
  4383. /** Do we know any descriptors for our bridges / entrynodes, and are
  4384. * all the ones we have descriptors for down? */
  4385. int
  4386. entries_known_but_down(or_options_t *options)
  4387. {
  4388. tor_assert(entry_list_is_constrained(options));
  4389. return entries_retry_helper(options, 0);
  4390. }
  4391. /** Mark all down known bridges / entrynodes up. */
  4392. void
  4393. entries_retry_all(or_options_t *options)
  4394. {
  4395. tor_assert(entry_list_is_constrained(options));
  4396. entries_retry_helper(options, 1);
  4397. }
  4398. /** Release all storage held by the list of entry guards and related
  4399. * memory structs. */
  4400. void
  4401. entry_guards_free_all(void)
  4402. {
  4403. if (entry_guards) {
  4404. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  4405. entry_guard_free(e));
  4406. smartlist_free(entry_guards);
  4407. entry_guards = NULL;
  4408. }
  4409. clear_bridge_list();
  4410. smartlist_free(bridge_list);
  4411. bridge_list = NULL;
  4412. }