circuitbuild.c 153 KB

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