circuitbuild.c 143 KB

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