circuitbuild.c 153 KB

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