circuitbuild.c 161 KB

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