circuitbuild.c 153 KB

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