circuitbuild.c 155 KB

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