circuitbuild.c 203 KB

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