circuitbuild.c 163 KB

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