circuitbuild.c 167 KB

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