circuitbuild.c 156 KB

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