circuitbuild.c 153 KB

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