circuitbuild.c 154 KB

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