circuitbuild.c 153 KB

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