circuitbuild.c 156 KB

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