circuitbuild.c 198 KB

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