circuitbuild.c 172 KB

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