circuitbuild.c 158 KB

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